Upload
couchbase
View
583
Download
1
Embed Size (px)
Citation preview
BUILDING A PEER-TO-PEER APPWITH COUCHBASE MOBILE
Jens AlfkePasin Suriyentrakorn
Couchbase Inc
copy2015 Couchbase Inc lsaquorsaquo
Session Overview
What is peer-to-peerP2P with Couchbase Mobilersquos replication
architectureImplementing peer-to-peerUsing Bonjour (aka mDNS Network Service
Discoveryhellip)Direct pairing via QR-code scanningDemos
Peer-to-Peer Overview
copy2015 Couchbase Inc lsaquorsaquo
What Is Peer-To-Peer
Direct communication between clientsNo server requiredNo Internet connection required
copy2015 Couchbase Inc lsaquorsaquo
Benefits Of Peer-To-Peer
Developer doesnrsquot need to run serversEnd-user privacyUnmetered high bandwidth connectionsUseable with no Internet infrastructureCellular ldquodead zonesrdquoWildernessDisaster areas
copy2015 Couchbase Inc lsaquorsaquo
Drawbacks Of Peer-To-Peer
Less reliableHard to securely identify users or authenticate
contentDifficult to scale upOn a LAN Bandwidth growthBeyond a LAN Connectivity and peer discovery
copy2015 Couchbase Inc lsaquorsaquo
Hybrid Approaches
ldquoA server is just a well-connected peerrdquoClients can connect to local peers and to a
server
Peer-to-Peer With Couchbase Mobile
copy2015 Couchbase Inc lsaquorsaquo
Couchbase Mobile Replication
Based on CouchDB architectureDesigned from the start for arbitrary topologies
Not the same as Couchbase Serverrsquos XDCR
Replicator
REST API
Active Passive
copy2015 Couchbase Inc lsaquorsaquo
Star Topology
copy2015 Couchbase Inc lsaquorsaquo
Cluster Topology
ldquoCluster Of Unreliable Cheap Hardwarerdquo
copy2015 Couchbase Inc lsaquorsaquo
P2P Mesh Topology
copy2015 Couchbase Inc lsaquorsaquoReplicating Documents amp Revisions
doc1
3-a9ff
doc1
2-c31b
B ldquoWhatrsquos new since last we spokerdquoA ldquoI added rev 3-a9ff of doc1rdquoB ldquoThatrsquos new to merdquoA ldquoIrsquoll send it overhelliprdquo
A
B
copy2015 Couchbase Inc lsaquorsaquo
P2P Mesh Topology
copy2015 Couchbase Inc lsaquorsaquo
The Problem With Naiumlve Meshes
O(n2) connections is badReal mesh networks limit connectionsSpanning treesGossip protocols
Implementing Peer-to-PeerPart 1
Allowing Connections
copy2015 Couchbase Inc lsaquorsaquo
Allowing Peer Connections
Link Couchbase Lite Listener component into appStart listenerCongratulations You are now a replication
ldquoserverrdquo
Datastore
CBL API
App
ReplicatorCBL API
App
Datastore
REST API
copy2015 Couchbase Inc lsaquorsaquo
Allowing Peer Connections
listener = CBLListener(manager databasemanager port 55555) listenerreadOnly = true
For SecurityPrevents peers from pushing Docs to you
Or port 0 to allow the OS to choose a random open port
but a fixed port is more optimal for the peerrsquos replicator
Implementing Peer-to-PeerPart 2
Automatic Peer Discovery
copy2015 Couchbase Inc lsaquorsaquo
Automatic Peer Discovery
ldquoWhorsquos running this serviceapp [on this LAN]rdquoAdvertise your own serviceTypeNameAddress + portSmall metadata (timestamphellip)
Browse for same service typeNotified as peers go onoffline
copy2015 Couchbase Inc lsaquorsaquo
Multicast DNS (mDNS) DNS Service Discovery (DNS-SD)
aka Bonjourtrade ZeroConf Avahi Network Service Discovery
RFC 6762 RFC 6763iOS Mac OS X Android (41+) LinuxWindows apps can integrate Applersquos
mDNSResponderdeveloperapplecomlibrarymacdocumentation
NetworkingConceptualNSNetServiceProgGuidedeveloperandroidcomtrainingconnect-devices-
wirelessly
copy2015 Couchbase Inc lsaquorsaquo
Advertising Your Service
listener = CBLListener(manager databasemanager port 55555) listenerreadOnly = true listenersetBonjourName(userNickname type _myapp_tcp)
Note setBonjourName isnrsquot available in CBL on Android yet Instead use NsdServiceInfo directly
Service name might be altered (number appended) to disambiguate it
copy2015 Couchbase Inc lsaquorsaquo
Browsing For Peers (iOS)
browser = NSNetServiceBrowsernew() browserincludesPeerToPeer = true browserdelegate = self browsersearchForServicesOfType(_myapp_tcp inDomain local)
public func netServiceBrowser(sender NSNetServiceBrowser didFindService service NSNetService moreComing Bool) hellip
public func netServiceBrowser(sender NSNetServiceBrowser didRemoveService service NSNetService moreComing Bool) hellip
copy2015 Couchbase Inc lsaquorsaquo
Connecting To A Peer (iOS)
Start async resolve to find servicersquos hostname servicedelegate = self serviceresolveWithTimeout(50)
NSNetService delegate callback public func netServiceDidResolveAddress(service NSNetService) Construct the remote DB URL var components = NSURLComponents() componentsscheme = http Or https if peer uses SSL componentshost = servicehostName componentsport = serviceport componentspath = + remoteDatabaseName let url = componentsURL
Start replication pull = localDBcreatePullReplication(url) pullstart()
copy2015 Couchbase Inc lsaquorsaquo
Using Bonjour To Replicate
Advertise a UUID as part of your service namePublish my dblatestSequence in service
metadataRemember UUID latestSequence of each lsquopairedrsquo
peerWhen peerrsquos latestSequence changes start a
pull replication
DEMO IPeerSync App
Q Whatrsquos Wrong With That DemoA No authentication
copy2015 Couchbase Inc lsaquorsaquo
C
Forging Documents or Revisions
docByA
B
A
B is sending me lsquodocByArsquo hellip but how
do I know it was really created by A
128530
128519
128564
copy2015 Couchbase Inc lsaquorsaquo
P2P Authentication Is A Hard Problem
With no server accountshow do you prove who you are
With no server to trusthow do you know whether data is valid
copy2015 Couchbase Inc lsaquorsaquo
This Is Not A Typical Auth Problem
SSL doesnrsquot helpHTTP authentication (ArArrB or BrArrC) doesnrsquot helpOnly authenticating the data helps
copy2015 Couchbase Inc lsaquorsaquo
Digital Signatures
Every user or device generates a key-pairEvery revision is signed by the party who created
itTo validate a revisionMake sure the signature is validLook up the authorrsquos public keyCompare signing key with authorrsquos key
copy2015 Couchbase Inc lsaquorsaquo
Key Distribution
Traditional StyleTrusted authority (server) signs key into a
certificateServer distributes certificate
P2P StyleDevice uses raw key or self-signed certificateUsers lsquopairrsquo devices in person
trading keys over a secure channel
Implementing Peer-to-PeerPart 3
Manual 11 Pairing
Pasin Suriyentrakorn
copy2015 Couchbase Inc lsaquorsaquo
PhotoDrop
Receiver ndash Presenting the QR Code and Receiving Photos
Sender ndash Selecting Photos Sender ndash Scanning a QR Code and Sending Photos
copy2015 Couchbase Inc lsaquorsaquo
ImplementationUses a QR code for peer discoveryUses one-time push replication to transfer photosUses digest authenticationGenerates one-time user credentialsSupports multiple platforms (eg iOS and
Android)
copy2015 Couchbase Inc lsaquorsaquo
StoryboardViewController SendViewController
ReceiveViewController
QR Code Scanner
Presents a QR code
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 1 Start a listener
listener = CBLListener(manager CBLManagersharedInstance() port 0)
listenerrequiresAuth = truelet username = secureGenerateKey(NSCharacterSetURLUserAllowedCharacterSet())let password = secureGenerateKey(NSCharacterSetURLPasswordAllowedCharacterSet())listenersetPasswords([username password])
var success = listenerstart(amperror)if (success)
syncUrl = genearteSyncURL(listenerURL username username password password dbName databasename)
startObserveDatabaseChange()
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Observe database changes
func startObserveDatabaseChange() NSNotificationCenterdefaultCenter()addObserverForName(kCBLDatabaseChangeNotification object database queue nil) (notification) -gt Void
in if let changes = notificationuserInfo[changes] as [CBLDatabaseChange] for change in changes
dispatch_async(dispatch_get_main_queue() selfsaveImageFromDocument(changedocumentID) )
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Generate and display a QR code
httpuserpasswordltlistener hostgtltportgtdb
Uses the iOS Core Image filter
copy2015 Couchbase Inc lsaquorsaquo
SendViewControllerStep 1 Scan a QR code
Uses the iOS class AVCaptureSession with the output type AVMetadataObjectTypeQRCode
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Create documents
var docIds [String] = []for asset in sharedAssets
var data = NSData(bytesNoCopy imageBytes length buffered freeWhenDone true)
let doc = databasecreateDocument()let rev = docnewRevision()revsetAttachmentNamed(photo withContentType applicationoctet-stream
content data)let saved = revsave(amperror)
if saved = nil docIdsappend(docdocumentID)
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Replicate documents
replicator = databasecreatePushReplication(url)replicatordocumentIDs = docIds
NSNotificationCenterdefaultCenter()addObserverForName(kCBLReplicationChangeNotification object replicator queue nil) (notification) -gt Void in
if selfreplicatorlastError == nil var totalCount = selfreplicatorchangesCountvar completedCount = selfreplicatorcompletedChangesCountif completedCount gt 0 ampamp completedCount == totalCount
selfstatusLabeltext = Sending Completedrdquo
else selfstatusLabeltext = Sending Abort
replicatorstart()
copy2015 Couchbase Inc lsaquorsaquo
Source Code
httpsgithubcomcouchbaselabsphoto-drop
Demo 2PhotoDrop App
The End mdash Any Questions
copy2015 Couchbase Inc lsaquorsaquo
Session Overview
What is peer-to-peerP2P with Couchbase Mobilersquos replication
architectureImplementing peer-to-peerUsing Bonjour (aka mDNS Network Service
Discoveryhellip)Direct pairing via QR-code scanningDemos
Peer-to-Peer Overview
copy2015 Couchbase Inc lsaquorsaquo
What Is Peer-To-Peer
Direct communication between clientsNo server requiredNo Internet connection required
copy2015 Couchbase Inc lsaquorsaquo
Benefits Of Peer-To-Peer
Developer doesnrsquot need to run serversEnd-user privacyUnmetered high bandwidth connectionsUseable with no Internet infrastructureCellular ldquodead zonesrdquoWildernessDisaster areas
copy2015 Couchbase Inc lsaquorsaquo
Drawbacks Of Peer-To-Peer
Less reliableHard to securely identify users or authenticate
contentDifficult to scale upOn a LAN Bandwidth growthBeyond a LAN Connectivity and peer discovery
copy2015 Couchbase Inc lsaquorsaquo
Hybrid Approaches
ldquoA server is just a well-connected peerrdquoClients can connect to local peers and to a
server
Peer-to-Peer With Couchbase Mobile
copy2015 Couchbase Inc lsaquorsaquo
Couchbase Mobile Replication
Based on CouchDB architectureDesigned from the start for arbitrary topologies
Not the same as Couchbase Serverrsquos XDCR
Replicator
REST API
Active Passive
copy2015 Couchbase Inc lsaquorsaquo
Star Topology
copy2015 Couchbase Inc lsaquorsaquo
Cluster Topology
ldquoCluster Of Unreliable Cheap Hardwarerdquo
copy2015 Couchbase Inc lsaquorsaquo
P2P Mesh Topology
copy2015 Couchbase Inc lsaquorsaquoReplicating Documents amp Revisions
doc1
3-a9ff
doc1
2-c31b
B ldquoWhatrsquos new since last we spokerdquoA ldquoI added rev 3-a9ff of doc1rdquoB ldquoThatrsquos new to merdquoA ldquoIrsquoll send it overhelliprdquo
A
B
copy2015 Couchbase Inc lsaquorsaquo
P2P Mesh Topology
copy2015 Couchbase Inc lsaquorsaquo
The Problem With Naiumlve Meshes
O(n2) connections is badReal mesh networks limit connectionsSpanning treesGossip protocols
Implementing Peer-to-PeerPart 1
Allowing Connections
copy2015 Couchbase Inc lsaquorsaquo
Allowing Peer Connections
Link Couchbase Lite Listener component into appStart listenerCongratulations You are now a replication
ldquoserverrdquo
Datastore
CBL API
App
ReplicatorCBL API
App
Datastore
REST API
copy2015 Couchbase Inc lsaquorsaquo
Allowing Peer Connections
listener = CBLListener(manager databasemanager port 55555) listenerreadOnly = true
For SecurityPrevents peers from pushing Docs to you
Or port 0 to allow the OS to choose a random open port
but a fixed port is more optimal for the peerrsquos replicator
Implementing Peer-to-PeerPart 2
Automatic Peer Discovery
copy2015 Couchbase Inc lsaquorsaquo
Automatic Peer Discovery
ldquoWhorsquos running this serviceapp [on this LAN]rdquoAdvertise your own serviceTypeNameAddress + portSmall metadata (timestamphellip)
Browse for same service typeNotified as peers go onoffline
copy2015 Couchbase Inc lsaquorsaquo
Multicast DNS (mDNS) DNS Service Discovery (DNS-SD)
aka Bonjourtrade ZeroConf Avahi Network Service Discovery
RFC 6762 RFC 6763iOS Mac OS X Android (41+) LinuxWindows apps can integrate Applersquos
mDNSResponderdeveloperapplecomlibrarymacdocumentation
NetworkingConceptualNSNetServiceProgGuidedeveloperandroidcomtrainingconnect-devices-
wirelessly
copy2015 Couchbase Inc lsaquorsaquo
Advertising Your Service
listener = CBLListener(manager databasemanager port 55555) listenerreadOnly = true listenersetBonjourName(userNickname type _myapp_tcp)
Note setBonjourName isnrsquot available in CBL on Android yet Instead use NsdServiceInfo directly
Service name might be altered (number appended) to disambiguate it
copy2015 Couchbase Inc lsaquorsaquo
Browsing For Peers (iOS)
browser = NSNetServiceBrowsernew() browserincludesPeerToPeer = true browserdelegate = self browsersearchForServicesOfType(_myapp_tcp inDomain local)
public func netServiceBrowser(sender NSNetServiceBrowser didFindService service NSNetService moreComing Bool) hellip
public func netServiceBrowser(sender NSNetServiceBrowser didRemoveService service NSNetService moreComing Bool) hellip
copy2015 Couchbase Inc lsaquorsaquo
Connecting To A Peer (iOS)
Start async resolve to find servicersquos hostname servicedelegate = self serviceresolveWithTimeout(50)
NSNetService delegate callback public func netServiceDidResolveAddress(service NSNetService) Construct the remote DB URL var components = NSURLComponents() componentsscheme = http Or https if peer uses SSL componentshost = servicehostName componentsport = serviceport componentspath = + remoteDatabaseName let url = componentsURL
Start replication pull = localDBcreatePullReplication(url) pullstart()
copy2015 Couchbase Inc lsaquorsaquo
Using Bonjour To Replicate
Advertise a UUID as part of your service namePublish my dblatestSequence in service
metadataRemember UUID latestSequence of each lsquopairedrsquo
peerWhen peerrsquos latestSequence changes start a
pull replication
DEMO IPeerSync App
Q Whatrsquos Wrong With That DemoA No authentication
copy2015 Couchbase Inc lsaquorsaquo
C
Forging Documents or Revisions
docByA
B
A
B is sending me lsquodocByArsquo hellip but how
do I know it was really created by A
128530
128519
128564
copy2015 Couchbase Inc lsaquorsaquo
P2P Authentication Is A Hard Problem
With no server accountshow do you prove who you are
With no server to trusthow do you know whether data is valid
copy2015 Couchbase Inc lsaquorsaquo
This Is Not A Typical Auth Problem
SSL doesnrsquot helpHTTP authentication (ArArrB or BrArrC) doesnrsquot helpOnly authenticating the data helps
copy2015 Couchbase Inc lsaquorsaquo
Digital Signatures
Every user or device generates a key-pairEvery revision is signed by the party who created
itTo validate a revisionMake sure the signature is validLook up the authorrsquos public keyCompare signing key with authorrsquos key
copy2015 Couchbase Inc lsaquorsaquo
Key Distribution
Traditional StyleTrusted authority (server) signs key into a
certificateServer distributes certificate
P2P StyleDevice uses raw key or self-signed certificateUsers lsquopairrsquo devices in person
trading keys over a secure channel
Implementing Peer-to-PeerPart 3
Manual 11 Pairing
Pasin Suriyentrakorn
copy2015 Couchbase Inc lsaquorsaquo
PhotoDrop
Receiver ndash Presenting the QR Code and Receiving Photos
Sender ndash Selecting Photos Sender ndash Scanning a QR Code and Sending Photos
copy2015 Couchbase Inc lsaquorsaquo
ImplementationUses a QR code for peer discoveryUses one-time push replication to transfer photosUses digest authenticationGenerates one-time user credentialsSupports multiple platforms (eg iOS and
Android)
copy2015 Couchbase Inc lsaquorsaquo
StoryboardViewController SendViewController
ReceiveViewController
QR Code Scanner
Presents a QR code
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 1 Start a listener
listener = CBLListener(manager CBLManagersharedInstance() port 0)
listenerrequiresAuth = truelet username = secureGenerateKey(NSCharacterSetURLUserAllowedCharacterSet())let password = secureGenerateKey(NSCharacterSetURLPasswordAllowedCharacterSet())listenersetPasswords([username password])
var success = listenerstart(amperror)if (success)
syncUrl = genearteSyncURL(listenerURL username username password password dbName databasename)
startObserveDatabaseChange()
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Observe database changes
func startObserveDatabaseChange() NSNotificationCenterdefaultCenter()addObserverForName(kCBLDatabaseChangeNotification object database queue nil) (notification) -gt Void
in if let changes = notificationuserInfo[changes] as [CBLDatabaseChange] for change in changes
dispatch_async(dispatch_get_main_queue() selfsaveImageFromDocument(changedocumentID) )
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Generate and display a QR code
httpuserpasswordltlistener hostgtltportgtdb
Uses the iOS Core Image filter
copy2015 Couchbase Inc lsaquorsaquo
SendViewControllerStep 1 Scan a QR code
Uses the iOS class AVCaptureSession with the output type AVMetadataObjectTypeQRCode
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Create documents
var docIds [String] = []for asset in sharedAssets
var data = NSData(bytesNoCopy imageBytes length buffered freeWhenDone true)
let doc = databasecreateDocument()let rev = docnewRevision()revsetAttachmentNamed(photo withContentType applicationoctet-stream
content data)let saved = revsave(amperror)
if saved = nil docIdsappend(docdocumentID)
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Replicate documents
replicator = databasecreatePushReplication(url)replicatordocumentIDs = docIds
NSNotificationCenterdefaultCenter()addObserverForName(kCBLReplicationChangeNotification object replicator queue nil) (notification) -gt Void in
if selfreplicatorlastError == nil var totalCount = selfreplicatorchangesCountvar completedCount = selfreplicatorcompletedChangesCountif completedCount gt 0 ampamp completedCount == totalCount
selfstatusLabeltext = Sending Completedrdquo
else selfstatusLabeltext = Sending Abort
replicatorstart()
copy2015 Couchbase Inc lsaquorsaquo
Source Code
httpsgithubcomcouchbaselabsphoto-drop
Demo 2PhotoDrop App
The End mdash Any Questions
Peer-to-Peer Overview
copy2015 Couchbase Inc lsaquorsaquo
What Is Peer-To-Peer
Direct communication between clientsNo server requiredNo Internet connection required
copy2015 Couchbase Inc lsaquorsaquo
Benefits Of Peer-To-Peer
Developer doesnrsquot need to run serversEnd-user privacyUnmetered high bandwidth connectionsUseable with no Internet infrastructureCellular ldquodead zonesrdquoWildernessDisaster areas
copy2015 Couchbase Inc lsaquorsaquo
Drawbacks Of Peer-To-Peer
Less reliableHard to securely identify users or authenticate
contentDifficult to scale upOn a LAN Bandwidth growthBeyond a LAN Connectivity and peer discovery
copy2015 Couchbase Inc lsaquorsaquo
Hybrid Approaches
ldquoA server is just a well-connected peerrdquoClients can connect to local peers and to a
server
Peer-to-Peer With Couchbase Mobile
copy2015 Couchbase Inc lsaquorsaquo
Couchbase Mobile Replication
Based on CouchDB architectureDesigned from the start for arbitrary topologies
Not the same as Couchbase Serverrsquos XDCR
Replicator
REST API
Active Passive
copy2015 Couchbase Inc lsaquorsaquo
Star Topology
copy2015 Couchbase Inc lsaquorsaquo
Cluster Topology
ldquoCluster Of Unreliable Cheap Hardwarerdquo
copy2015 Couchbase Inc lsaquorsaquo
P2P Mesh Topology
copy2015 Couchbase Inc lsaquorsaquoReplicating Documents amp Revisions
doc1
3-a9ff
doc1
2-c31b
B ldquoWhatrsquos new since last we spokerdquoA ldquoI added rev 3-a9ff of doc1rdquoB ldquoThatrsquos new to merdquoA ldquoIrsquoll send it overhelliprdquo
A
B
copy2015 Couchbase Inc lsaquorsaquo
P2P Mesh Topology
copy2015 Couchbase Inc lsaquorsaquo
The Problem With Naiumlve Meshes
O(n2) connections is badReal mesh networks limit connectionsSpanning treesGossip protocols
Implementing Peer-to-PeerPart 1
Allowing Connections
copy2015 Couchbase Inc lsaquorsaquo
Allowing Peer Connections
Link Couchbase Lite Listener component into appStart listenerCongratulations You are now a replication
ldquoserverrdquo
Datastore
CBL API
App
ReplicatorCBL API
App
Datastore
REST API
copy2015 Couchbase Inc lsaquorsaquo
Allowing Peer Connections
listener = CBLListener(manager databasemanager port 55555) listenerreadOnly = true
For SecurityPrevents peers from pushing Docs to you
Or port 0 to allow the OS to choose a random open port
but a fixed port is more optimal for the peerrsquos replicator
Implementing Peer-to-PeerPart 2
Automatic Peer Discovery
copy2015 Couchbase Inc lsaquorsaquo
Automatic Peer Discovery
ldquoWhorsquos running this serviceapp [on this LAN]rdquoAdvertise your own serviceTypeNameAddress + portSmall metadata (timestamphellip)
Browse for same service typeNotified as peers go onoffline
copy2015 Couchbase Inc lsaquorsaquo
Multicast DNS (mDNS) DNS Service Discovery (DNS-SD)
aka Bonjourtrade ZeroConf Avahi Network Service Discovery
RFC 6762 RFC 6763iOS Mac OS X Android (41+) LinuxWindows apps can integrate Applersquos
mDNSResponderdeveloperapplecomlibrarymacdocumentation
NetworkingConceptualNSNetServiceProgGuidedeveloperandroidcomtrainingconnect-devices-
wirelessly
copy2015 Couchbase Inc lsaquorsaquo
Advertising Your Service
listener = CBLListener(manager databasemanager port 55555) listenerreadOnly = true listenersetBonjourName(userNickname type _myapp_tcp)
Note setBonjourName isnrsquot available in CBL on Android yet Instead use NsdServiceInfo directly
Service name might be altered (number appended) to disambiguate it
copy2015 Couchbase Inc lsaquorsaquo
Browsing For Peers (iOS)
browser = NSNetServiceBrowsernew() browserincludesPeerToPeer = true browserdelegate = self browsersearchForServicesOfType(_myapp_tcp inDomain local)
public func netServiceBrowser(sender NSNetServiceBrowser didFindService service NSNetService moreComing Bool) hellip
public func netServiceBrowser(sender NSNetServiceBrowser didRemoveService service NSNetService moreComing Bool) hellip
copy2015 Couchbase Inc lsaquorsaquo
Connecting To A Peer (iOS)
Start async resolve to find servicersquos hostname servicedelegate = self serviceresolveWithTimeout(50)
NSNetService delegate callback public func netServiceDidResolveAddress(service NSNetService) Construct the remote DB URL var components = NSURLComponents() componentsscheme = http Or https if peer uses SSL componentshost = servicehostName componentsport = serviceport componentspath = + remoteDatabaseName let url = componentsURL
Start replication pull = localDBcreatePullReplication(url) pullstart()
copy2015 Couchbase Inc lsaquorsaquo
Using Bonjour To Replicate
Advertise a UUID as part of your service namePublish my dblatestSequence in service
metadataRemember UUID latestSequence of each lsquopairedrsquo
peerWhen peerrsquos latestSequence changes start a
pull replication
DEMO IPeerSync App
Q Whatrsquos Wrong With That DemoA No authentication
copy2015 Couchbase Inc lsaquorsaquo
C
Forging Documents or Revisions
docByA
B
A
B is sending me lsquodocByArsquo hellip but how
do I know it was really created by A
128530
128519
128564
copy2015 Couchbase Inc lsaquorsaquo
P2P Authentication Is A Hard Problem
With no server accountshow do you prove who you are
With no server to trusthow do you know whether data is valid
copy2015 Couchbase Inc lsaquorsaquo
This Is Not A Typical Auth Problem
SSL doesnrsquot helpHTTP authentication (ArArrB or BrArrC) doesnrsquot helpOnly authenticating the data helps
copy2015 Couchbase Inc lsaquorsaquo
Digital Signatures
Every user or device generates a key-pairEvery revision is signed by the party who created
itTo validate a revisionMake sure the signature is validLook up the authorrsquos public keyCompare signing key with authorrsquos key
copy2015 Couchbase Inc lsaquorsaquo
Key Distribution
Traditional StyleTrusted authority (server) signs key into a
certificateServer distributes certificate
P2P StyleDevice uses raw key or self-signed certificateUsers lsquopairrsquo devices in person
trading keys over a secure channel
Implementing Peer-to-PeerPart 3
Manual 11 Pairing
Pasin Suriyentrakorn
copy2015 Couchbase Inc lsaquorsaquo
PhotoDrop
Receiver ndash Presenting the QR Code and Receiving Photos
Sender ndash Selecting Photos Sender ndash Scanning a QR Code and Sending Photos
copy2015 Couchbase Inc lsaquorsaquo
ImplementationUses a QR code for peer discoveryUses one-time push replication to transfer photosUses digest authenticationGenerates one-time user credentialsSupports multiple platforms (eg iOS and
Android)
copy2015 Couchbase Inc lsaquorsaquo
StoryboardViewController SendViewController
ReceiveViewController
QR Code Scanner
Presents a QR code
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 1 Start a listener
listener = CBLListener(manager CBLManagersharedInstance() port 0)
listenerrequiresAuth = truelet username = secureGenerateKey(NSCharacterSetURLUserAllowedCharacterSet())let password = secureGenerateKey(NSCharacterSetURLPasswordAllowedCharacterSet())listenersetPasswords([username password])
var success = listenerstart(amperror)if (success)
syncUrl = genearteSyncURL(listenerURL username username password password dbName databasename)
startObserveDatabaseChange()
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Observe database changes
func startObserveDatabaseChange() NSNotificationCenterdefaultCenter()addObserverForName(kCBLDatabaseChangeNotification object database queue nil) (notification) -gt Void
in if let changes = notificationuserInfo[changes] as [CBLDatabaseChange] for change in changes
dispatch_async(dispatch_get_main_queue() selfsaveImageFromDocument(changedocumentID) )
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Generate and display a QR code
httpuserpasswordltlistener hostgtltportgtdb
Uses the iOS Core Image filter
copy2015 Couchbase Inc lsaquorsaquo
SendViewControllerStep 1 Scan a QR code
Uses the iOS class AVCaptureSession with the output type AVMetadataObjectTypeQRCode
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Create documents
var docIds [String] = []for asset in sharedAssets
var data = NSData(bytesNoCopy imageBytes length buffered freeWhenDone true)
let doc = databasecreateDocument()let rev = docnewRevision()revsetAttachmentNamed(photo withContentType applicationoctet-stream
content data)let saved = revsave(amperror)
if saved = nil docIdsappend(docdocumentID)
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Replicate documents
replicator = databasecreatePushReplication(url)replicatordocumentIDs = docIds
NSNotificationCenterdefaultCenter()addObserverForName(kCBLReplicationChangeNotification object replicator queue nil) (notification) -gt Void in
if selfreplicatorlastError == nil var totalCount = selfreplicatorchangesCountvar completedCount = selfreplicatorcompletedChangesCountif completedCount gt 0 ampamp completedCount == totalCount
selfstatusLabeltext = Sending Completedrdquo
else selfstatusLabeltext = Sending Abort
replicatorstart()
copy2015 Couchbase Inc lsaquorsaquo
Source Code
httpsgithubcomcouchbaselabsphoto-drop
Demo 2PhotoDrop App
The End mdash Any Questions
copy2015 Couchbase Inc lsaquorsaquo
What Is Peer-To-Peer
Direct communication between clientsNo server requiredNo Internet connection required
copy2015 Couchbase Inc lsaquorsaquo
Benefits Of Peer-To-Peer
Developer doesnrsquot need to run serversEnd-user privacyUnmetered high bandwidth connectionsUseable with no Internet infrastructureCellular ldquodead zonesrdquoWildernessDisaster areas
copy2015 Couchbase Inc lsaquorsaquo
Drawbacks Of Peer-To-Peer
Less reliableHard to securely identify users or authenticate
contentDifficult to scale upOn a LAN Bandwidth growthBeyond a LAN Connectivity and peer discovery
copy2015 Couchbase Inc lsaquorsaquo
Hybrid Approaches
ldquoA server is just a well-connected peerrdquoClients can connect to local peers and to a
server
Peer-to-Peer With Couchbase Mobile
copy2015 Couchbase Inc lsaquorsaquo
Couchbase Mobile Replication
Based on CouchDB architectureDesigned from the start for arbitrary topologies
Not the same as Couchbase Serverrsquos XDCR
Replicator
REST API
Active Passive
copy2015 Couchbase Inc lsaquorsaquo
Star Topology
copy2015 Couchbase Inc lsaquorsaquo
Cluster Topology
ldquoCluster Of Unreliable Cheap Hardwarerdquo
copy2015 Couchbase Inc lsaquorsaquo
P2P Mesh Topology
copy2015 Couchbase Inc lsaquorsaquoReplicating Documents amp Revisions
doc1
3-a9ff
doc1
2-c31b
B ldquoWhatrsquos new since last we spokerdquoA ldquoI added rev 3-a9ff of doc1rdquoB ldquoThatrsquos new to merdquoA ldquoIrsquoll send it overhelliprdquo
A
B
copy2015 Couchbase Inc lsaquorsaquo
P2P Mesh Topology
copy2015 Couchbase Inc lsaquorsaquo
The Problem With Naiumlve Meshes
O(n2) connections is badReal mesh networks limit connectionsSpanning treesGossip protocols
Implementing Peer-to-PeerPart 1
Allowing Connections
copy2015 Couchbase Inc lsaquorsaquo
Allowing Peer Connections
Link Couchbase Lite Listener component into appStart listenerCongratulations You are now a replication
ldquoserverrdquo
Datastore
CBL API
App
ReplicatorCBL API
App
Datastore
REST API
copy2015 Couchbase Inc lsaquorsaquo
Allowing Peer Connections
listener = CBLListener(manager databasemanager port 55555) listenerreadOnly = true
For SecurityPrevents peers from pushing Docs to you
Or port 0 to allow the OS to choose a random open port
but a fixed port is more optimal for the peerrsquos replicator
Implementing Peer-to-PeerPart 2
Automatic Peer Discovery
copy2015 Couchbase Inc lsaquorsaquo
Automatic Peer Discovery
ldquoWhorsquos running this serviceapp [on this LAN]rdquoAdvertise your own serviceTypeNameAddress + portSmall metadata (timestamphellip)
Browse for same service typeNotified as peers go onoffline
copy2015 Couchbase Inc lsaquorsaquo
Multicast DNS (mDNS) DNS Service Discovery (DNS-SD)
aka Bonjourtrade ZeroConf Avahi Network Service Discovery
RFC 6762 RFC 6763iOS Mac OS X Android (41+) LinuxWindows apps can integrate Applersquos
mDNSResponderdeveloperapplecomlibrarymacdocumentation
NetworkingConceptualNSNetServiceProgGuidedeveloperandroidcomtrainingconnect-devices-
wirelessly
copy2015 Couchbase Inc lsaquorsaquo
Advertising Your Service
listener = CBLListener(manager databasemanager port 55555) listenerreadOnly = true listenersetBonjourName(userNickname type _myapp_tcp)
Note setBonjourName isnrsquot available in CBL on Android yet Instead use NsdServiceInfo directly
Service name might be altered (number appended) to disambiguate it
copy2015 Couchbase Inc lsaquorsaquo
Browsing For Peers (iOS)
browser = NSNetServiceBrowsernew() browserincludesPeerToPeer = true browserdelegate = self browsersearchForServicesOfType(_myapp_tcp inDomain local)
public func netServiceBrowser(sender NSNetServiceBrowser didFindService service NSNetService moreComing Bool) hellip
public func netServiceBrowser(sender NSNetServiceBrowser didRemoveService service NSNetService moreComing Bool) hellip
copy2015 Couchbase Inc lsaquorsaquo
Connecting To A Peer (iOS)
Start async resolve to find servicersquos hostname servicedelegate = self serviceresolveWithTimeout(50)
NSNetService delegate callback public func netServiceDidResolveAddress(service NSNetService) Construct the remote DB URL var components = NSURLComponents() componentsscheme = http Or https if peer uses SSL componentshost = servicehostName componentsport = serviceport componentspath = + remoteDatabaseName let url = componentsURL
Start replication pull = localDBcreatePullReplication(url) pullstart()
copy2015 Couchbase Inc lsaquorsaquo
Using Bonjour To Replicate
Advertise a UUID as part of your service namePublish my dblatestSequence in service
metadataRemember UUID latestSequence of each lsquopairedrsquo
peerWhen peerrsquos latestSequence changes start a
pull replication
DEMO IPeerSync App
Q Whatrsquos Wrong With That DemoA No authentication
copy2015 Couchbase Inc lsaquorsaquo
C
Forging Documents or Revisions
docByA
B
A
B is sending me lsquodocByArsquo hellip but how
do I know it was really created by A
128530
128519
128564
copy2015 Couchbase Inc lsaquorsaquo
P2P Authentication Is A Hard Problem
With no server accountshow do you prove who you are
With no server to trusthow do you know whether data is valid
copy2015 Couchbase Inc lsaquorsaquo
This Is Not A Typical Auth Problem
SSL doesnrsquot helpHTTP authentication (ArArrB or BrArrC) doesnrsquot helpOnly authenticating the data helps
copy2015 Couchbase Inc lsaquorsaquo
Digital Signatures
Every user or device generates a key-pairEvery revision is signed by the party who created
itTo validate a revisionMake sure the signature is validLook up the authorrsquos public keyCompare signing key with authorrsquos key
copy2015 Couchbase Inc lsaquorsaquo
Key Distribution
Traditional StyleTrusted authority (server) signs key into a
certificateServer distributes certificate
P2P StyleDevice uses raw key or self-signed certificateUsers lsquopairrsquo devices in person
trading keys over a secure channel
Implementing Peer-to-PeerPart 3
Manual 11 Pairing
Pasin Suriyentrakorn
copy2015 Couchbase Inc lsaquorsaquo
PhotoDrop
Receiver ndash Presenting the QR Code and Receiving Photos
Sender ndash Selecting Photos Sender ndash Scanning a QR Code and Sending Photos
copy2015 Couchbase Inc lsaquorsaquo
ImplementationUses a QR code for peer discoveryUses one-time push replication to transfer photosUses digest authenticationGenerates one-time user credentialsSupports multiple platforms (eg iOS and
Android)
copy2015 Couchbase Inc lsaquorsaquo
StoryboardViewController SendViewController
ReceiveViewController
QR Code Scanner
Presents a QR code
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 1 Start a listener
listener = CBLListener(manager CBLManagersharedInstance() port 0)
listenerrequiresAuth = truelet username = secureGenerateKey(NSCharacterSetURLUserAllowedCharacterSet())let password = secureGenerateKey(NSCharacterSetURLPasswordAllowedCharacterSet())listenersetPasswords([username password])
var success = listenerstart(amperror)if (success)
syncUrl = genearteSyncURL(listenerURL username username password password dbName databasename)
startObserveDatabaseChange()
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Observe database changes
func startObserveDatabaseChange() NSNotificationCenterdefaultCenter()addObserverForName(kCBLDatabaseChangeNotification object database queue nil) (notification) -gt Void
in if let changes = notificationuserInfo[changes] as [CBLDatabaseChange] for change in changes
dispatch_async(dispatch_get_main_queue() selfsaveImageFromDocument(changedocumentID) )
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Generate and display a QR code
httpuserpasswordltlistener hostgtltportgtdb
Uses the iOS Core Image filter
copy2015 Couchbase Inc lsaquorsaquo
SendViewControllerStep 1 Scan a QR code
Uses the iOS class AVCaptureSession with the output type AVMetadataObjectTypeQRCode
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Create documents
var docIds [String] = []for asset in sharedAssets
var data = NSData(bytesNoCopy imageBytes length buffered freeWhenDone true)
let doc = databasecreateDocument()let rev = docnewRevision()revsetAttachmentNamed(photo withContentType applicationoctet-stream
content data)let saved = revsave(amperror)
if saved = nil docIdsappend(docdocumentID)
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Replicate documents
replicator = databasecreatePushReplication(url)replicatordocumentIDs = docIds
NSNotificationCenterdefaultCenter()addObserverForName(kCBLReplicationChangeNotification object replicator queue nil) (notification) -gt Void in
if selfreplicatorlastError == nil var totalCount = selfreplicatorchangesCountvar completedCount = selfreplicatorcompletedChangesCountif completedCount gt 0 ampamp completedCount == totalCount
selfstatusLabeltext = Sending Completedrdquo
else selfstatusLabeltext = Sending Abort
replicatorstart()
copy2015 Couchbase Inc lsaquorsaquo
Source Code
httpsgithubcomcouchbaselabsphoto-drop
Demo 2PhotoDrop App
The End mdash Any Questions
copy2015 Couchbase Inc lsaquorsaquo
Benefits Of Peer-To-Peer
Developer doesnrsquot need to run serversEnd-user privacyUnmetered high bandwidth connectionsUseable with no Internet infrastructureCellular ldquodead zonesrdquoWildernessDisaster areas
copy2015 Couchbase Inc lsaquorsaquo
Drawbacks Of Peer-To-Peer
Less reliableHard to securely identify users or authenticate
contentDifficult to scale upOn a LAN Bandwidth growthBeyond a LAN Connectivity and peer discovery
copy2015 Couchbase Inc lsaquorsaquo
Hybrid Approaches
ldquoA server is just a well-connected peerrdquoClients can connect to local peers and to a
server
Peer-to-Peer With Couchbase Mobile
copy2015 Couchbase Inc lsaquorsaquo
Couchbase Mobile Replication
Based on CouchDB architectureDesigned from the start for arbitrary topologies
Not the same as Couchbase Serverrsquos XDCR
Replicator
REST API
Active Passive
copy2015 Couchbase Inc lsaquorsaquo
Star Topology
copy2015 Couchbase Inc lsaquorsaquo
Cluster Topology
ldquoCluster Of Unreliable Cheap Hardwarerdquo
copy2015 Couchbase Inc lsaquorsaquo
P2P Mesh Topology
copy2015 Couchbase Inc lsaquorsaquoReplicating Documents amp Revisions
doc1
3-a9ff
doc1
2-c31b
B ldquoWhatrsquos new since last we spokerdquoA ldquoI added rev 3-a9ff of doc1rdquoB ldquoThatrsquos new to merdquoA ldquoIrsquoll send it overhelliprdquo
A
B
copy2015 Couchbase Inc lsaquorsaquo
P2P Mesh Topology
copy2015 Couchbase Inc lsaquorsaquo
The Problem With Naiumlve Meshes
O(n2) connections is badReal mesh networks limit connectionsSpanning treesGossip protocols
Implementing Peer-to-PeerPart 1
Allowing Connections
copy2015 Couchbase Inc lsaquorsaquo
Allowing Peer Connections
Link Couchbase Lite Listener component into appStart listenerCongratulations You are now a replication
ldquoserverrdquo
Datastore
CBL API
App
ReplicatorCBL API
App
Datastore
REST API
copy2015 Couchbase Inc lsaquorsaquo
Allowing Peer Connections
listener = CBLListener(manager databasemanager port 55555) listenerreadOnly = true
For SecurityPrevents peers from pushing Docs to you
Or port 0 to allow the OS to choose a random open port
but a fixed port is more optimal for the peerrsquos replicator
Implementing Peer-to-PeerPart 2
Automatic Peer Discovery
copy2015 Couchbase Inc lsaquorsaquo
Automatic Peer Discovery
ldquoWhorsquos running this serviceapp [on this LAN]rdquoAdvertise your own serviceTypeNameAddress + portSmall metadata (timestamphellip)
Browse for same service typeNotified as peers go onoffline
copy2015 Couchbase Inc lsaquorsaquo
Multicast DNS (mDNS) DNS Service Discovery (DNS-SD)
aka Bonjourtrade ZeroConf Avahi Network Service Discovery
RFC 6762 RFC 6763iOS Mac OS X Android (41+) LinuxWindows apps can integrate Applersquos
mDNSResponderdeveloperapplecomlibrarymacdocumentation
NetworkingConceptualNSNetServiceProgGuidedeveloperandroidcomtrainingconnect-devices-
wirelessly
copy2015 Couchbase Inc lsaquorsaquo
Advertising Your Service
listener = CBLListener(manager databasemanager port 55555) listenerreadOnly = true listenersetBonjourName(userNickname type _myapp_tcp)
Note setBonjourName isnrsquot available in CBL on Android yet Instead use NsdServiceInfo directly
Service name might be altered (number appended) to disambiguate it
copy2015 Couchbase Inc lsaquorsaquo
Browsing For Peers (iOS)
browser = NSNetServiceBrowsernew() browserincludesPeerToPeer = true browserdelegate = self browsersearchForServicesOfType(_myapp_tcp inDomain local)
public func netServiceBrowser(sender NSNetServiceBrowser didFindService service NSNetService moreComing Bool) hellip
public func netServiceBrowser(sender NSNetServiceBrowser didRemoveService service NSNetService moreComing Bool) hellip
copy2015 Couchbase Inc lsaquorsaquo
Connecting To A Peer (iOS)
Start async resolve to find servicersquos hostname servicedelegate = self serviceresolveWithTimeout(50)
NSNetService delegate callback public func netServiceDidResolveAddress(service NSNetService) Construct the remote DB URL var components = NSURLComponents() componentsscheme = http Or https if peer uses SSL componentshost = servicehostName componentsport = serviceport componentspath = + remoteDatabaseName let url = componentsURL
Start replication pull = localDBcreatePullReplication(url) pullstart()
copy2015 Couchbase Inc lsaquorsaquo
Using Bonjour To Replicate
Advertise a UUID as part of your service namePublish my dblatestSequence in service
metadataRemember UUID latestSequence of each lsquopairedrsquo
peerWhen peerrsquos latestSequence changes start a
pull replication
DEMO IPeerSync App
Q Whatrsquos Wrong With That DemoA No authentication
copy2015 Couchbase Inc lsaquorsaquo
C
Forging Documents or Revisions
docByA
B
A
B is sending me lsquodocByArsquo hellip but how
do I know it was really created by A
128530
128519
128564
copy2015 Couchbase Inc lsaquorsaquo
P2P Authentication Is A Hard Problem
With no server accountshow do you prove who you are
With no server to trusthow do you know whether data is valid
copy2015 Couchbase Inc lsaquorsaquo
This Is Not A Typical Auth Problem
SSL doesnrsquot helpHTTP authentication (ArArrB or BrArrC) doesnrsquot helpOnly authenticating the data helps
copy2015 Couchbase Inc lsaquorsaquo
Digital Signatures
Every user or device generates a key-pairEvery revision is signed by the party who created
itTo validate a revisionMake sure the signature is validLook up the authorrsquos public keyCompare signing key with authorrsquos key
copy2015 Couchbase Inc lsaquorsaquo
Key Distribution
Traditional StyleTrusted authority (server) signs key into a
certificateServer distributes certificate
P2P StyleDevice uses raw key or self-signed certificateUsers lsquopairrsquo devices in person
trading keys over a secure channel
Implementing Peer-to-PeerPart 3
Manual 11 Pairing
Pasin Suriyentrakorn
copy2015 Couchbase Inc lsaquorsaquo
PhotoDrop
Receiver ndash Presenting the QR Code and Receiving Photos
Sender ndash Selecting Photos Sender ndash Scanning a QR Code and Sending Photos
copy2015 Couchbase Inc lsaquorsaquo
ImplementationUses a QR code for peer discoveryUses one-time push replication to transfer photosUses digest authenticationGenerates one-time user credentialsSupports multiple platforms (eg iOS and
Android)
copy2015 Couchbase Inc lsaquorsaquo
StoryboardViewController SendViewController
ReceiveViewController
QR Code Scanner
Presents a QR code
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 1 Start a listener
listener = CBLListener(manager CBLManagersharedInstance() port 0)
listenerrequiresAuth = truelet username = secureGenerateKey(NSCharacterSetURLUserAllowedCharacterSet())let password = secureGenerateKey(NSCharacterSetURLPasswordAllowedCharacterSet())listenersetPasswords([username password])
var success = listenerstart(amperror)if (success)
syncUrl = genearteSyncURL(listenerURL username username password password dbName databasename)
startObserveDatabaseChange()
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Observe database changes
func startObserveDatabaseChange() NSNotificationCenterdefaultCenter()addObserverForName(kCBLDatabaseChangeNotification object database queue nil) (notification) -gt Void
in if let changes = notificationuserInfo[changes] as [CBLDatabaseChange] for change in changes
dispatch_async(dispatch_get_main_queue() selfsaveImageFromDocument(changedocumentID) )
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Generate and display a QR code
httpuserpasswordltlistener hostgtltportgtdb
Uses the iOS Core Image filter
copy2015 Couchbase Inc lsaquorsaquo
SendViewControllerStep 1 Scan a QR code
Uses the iOS class AVCaptureSession with the output type AVMetadataObjectTypeQRCode
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Create documents
var docIds [String] = []for asset in sharedAssets
var data = NSData(bytesNoCopy imageBytes length buffered freeWhenDone true)
let doc = databasecreateDocument()let rev = docnewRevision()revsetAttachmentNamed(photo withContentType applicationoctet-stream
content data)let saved = revsave(amperror)
if saved = nil docIdsappend(docdocumentID)
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Replicate documents
replicator = databasecreatePushReplication(url)replicatordocumentIDs = docIds
NSNotificationCenterdefaultCenter()addObserverForName(kCBLReplicationChangeNotification object replicator queue nil) (notification) -gt Void in
if selfreplicatorlastError == nil var totalCount = selfreplicatorchangesCountvar completedCount = selfreplicatorcompletedChangesCountif completedCount gt 0 ampamp completedCount == totalCount
selfstatusLabeltext = Sending Completedrdquo
else selfstatusLabeltext = Sending Abort
replicatorstart()
copy2015 Couchbase Inc lsaquorsaquo
Source Code
httpsgithubcomcouchbaselabsphoto-drop
Demo 2PhotoDrop App
The End mdash Any Questions
copy2015 Couchbase Inc lsaquorsaquo
Drawbacks Of Peer-To-Peer
Less reliableHard to securely identify users or authenticate
contentDifficult to scale upOn a LAN Bandwidth growthBeyond a LAN Connectivity and peer discovery
copy2015 Couchbase Inc lsaquorsaquo
Hybrid Approaches
ldquoA server is just a well-connected peerrdquoClients can connect to local peers and to a
server
Peer-to-Peer With Couchbase Mobile
copy2015 Couchbase Inc lsaquorsaquo
Couchbase Mobile Replication
Based on CouchDB architectureDesigned from the start for arbitrary topologies
Not the same as Couchbase Serverrsquos XDCR
Replicator
REST API
Active Passive
copy2015 Couchbase Inc lsaquorsaquo
Star Topology
copy2015 Couchbase Inc lsaquorsaquo
Cluster Topology
ldquoCluster Of Unreliable Cheap Hardwarerdquo
copy2015 Couchbase Inc lsaquorsaquo
P2P Mesh Topology
copy2015 Couchbase Inc lsaquorsaquoReplicating Documents amp Revisions
doc1
3-a9ff
doc1
2-c31b
B ldquoWhatrsquos new since last we spokerdquoA ldquoI added rev 3-a9ff of doc1rdquoB ldquoThatrsquos new to merdquoA ldquoIrsquoll send it overhelliprdquo
A
B
copy2015 Couchbase Inc lsaquorsaquo
P2P Mesh Topology
copy2015 Couchbase Inc lsaquorsaquo
The Problem With Naiumlve Meshes
O(n2) connections is badReal mesh networks limit connectionsSpanning treesGossip protocols
Implementing Peer-to-PeerPart 1
Allowing Connections
copy2015 Couchbase Inc lsaquorsaquo
Allowing Peer Connections
Link Couchbase Lite Listener component into appStart listenerCongratulations You are now a replication
ldquoserverrdquo
Datastore
CBL API
App
ReplicatorCBL API
App
Datastore
REST API
copy2015 Couchbase Inc lsaquorsaquo
Allowing Peer Connections
listener = CBLListener(manager databasemanager port 55555) listenerreadOnly = true
For SecurityPrevents peers from pushing Docs to you
Or port 0 to allow the OS to choose a random open port
but a fixed port is more optimal for the peerrsquos replicator
Implementing Peer-to-PeerPart 2
Automatic Peer Discovery
copy2015 Couchbase Inc lsaquorsaquo
Automatic Peer Discovery
ldquoWhorsquos running this serviceapp [on this LAN]rdquoAdvertise your own serviceTypeNameAddress + portSmall metadata (timestamphellip)
Browse for same service typeNotified as peers go onoffline
copy2015 Couchbase Inc lsaquorsaquo
Multicast DNS (mDNS) DNS Service Discovery (DNS-SD)
aka Bonjourtrade ZeroConf Avahi Network Service Discovery
RFC 6762 RFC 6763iOS Mac OS X Android (41+) LinuxWindows apps can integrate Applersquos
mDNSResponderdeveloperapplecomlibrarymacdocumentation
NetworkingConceptualNSNetServiceProgGuidedeveloperandroidcomtrainingconnect-devices-
wirelessly
copy2015 Couchbase Inc lsaquorsaquo
Advertising Your Service
listener = CBLListener(manager databasemanager port 55555) listenerreadOnly = true listenersetBonjourName(userNickname type _myapp_tcp)
Note setBonjourName isnrsquot available in CBL on Android yet Instead use NsdServiceInfo directly
Service name might be altered (number appended) to disambiguate it
copy2015 Couchbase Inc lsaquorsaquo
Browsing For Peers (iOS)
browser = NSNetServiceBrowsernew() browserincludesPeerToPeer = true browserdelegate = self browsersearchForServicesOfType(_myapp_tcp inDomain local)
public func netServiceBrowser(sender NSNetServiceBrowser didFindService service NSNetService moreComing Bool) hellip
public func netServiceBrowser(sender NSNetServiceBrowser didRemoveService service NSNetService moreComing Bool) hellip
copy2015 Couchbase Inc lsaquorsaquo
Connecting To A Peer (iOS)
Start async resolve to find servicersquos hostname servicedelegate = self serviceresolveWithTimeout(50)
NSNetService delegate callback public func netServiceDidResolveAddress(service NSNetService) Construct the remote DB URL var components = NSURLComponents() componentsscheme = http Or https if peer uses SSL componentshost = servicehostName componentsport = serviceport componentspath = + remoteDatabaseName let url = componentsURL
Start replication pull = localDBcreatePullReplication(url) pullstart()
copy2015 Couchbase Inc lsaquorsaquo
Using Bonjour To Replicate
Advertise a UUID as part of your service namePublish my dblatestSequence in service
metadataRemember UUID latestSequence of each lsquopairedrsquo
peerWhen peerrsquos latestSequence changes start a
pull replication
DEMO IPeerSync App
Q Whatrsquos Wrong With That DemoA No authentication
copy2015 Couchbase Inc lsaquorsaquo
C
Forging Documents or Revisions
docByA
B
A
B is sending me lsquodocByArsquo hellip but how
do I know it was really created by A
128530
128519
128564
copy2015 Couchbase Inc lsaquorsaquo
P2P Authentication Is A Hard Problem
With no server accountshow do you prove who you are
With no server to trusthow do you know whether data is valid
copy2015 Couchbase Inc lsaquorsaquo
This Is Not A Typical Auth Problem
SSL doesnrsquot helpHTTP authentication (ArArrB or BrArrC) doesnrsquot helpOnly authenticating the data helps
copy2015 Couchbase Inc lsaquorsaquo
Digital Signatures
Every user or device generates a key-pairEvery revision is signed by the party who created
itTo validate a revisionMake sure the signature is validLook up the authorrsquos public keyCompare signing key with authorrsquos key
copy2015 Couchbase Inc lsaquorsaquo
Key Distribution
Traditional StyleTrusted authority (server) signs key into a
certificateServer distributes certificate
P2P StyleDevice uses raw key or self-signed certificateUsers lsquopairrsquo devices in person
trading keys over a secure channel
Implementing Peer-to-PeerPart 3
Manual 11 Pairing
Pasin Suriyentrakorn
copy2015 Couchbase Inc lsaquorsaquo
PhotoDrop
Receiver ndash Presenting the QR Code and Receiving Photos
Sender ndash Selecting Photos Sender ndash Scanning a QR Code and Sending Photos
copy2015 Couchbase Inc lsaquorsaquo
ImplementationUses a QR code for peer discoveryUses one-time push replication to transfer photosUses digest authenticationGenerates one-time user credentialsSupports multiple platforms (eg iOS and
Android)
copy2015 Couchbase Inc lsaquorsaquo
StoryboardViewController SendViewController
ReceiveViewController
QR Code Scanner
Presents a QR code
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 1 Start a listener
listener = CBLListener(manager CBLManagersharedInstance() port 0)
listenerrequiresAuth = truelet username = secureGenerateKey(NSCharacterSetURLUserAllowedCharacterSet())let password = secureGenerateKey(NSCharacterSetURLPasswordAllowedCharacterSet())listenersetPasswords([username password])
var success = listenerstart(amperror)if (success)
syncUrl = genearteSyncURL(listenerURL username username password password dbName databasename)
startObserveDatabaseChange()
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Observe database changes
func startObserveDatabaseChange() NSNotificationCenterdefaultCenter()addObserverForName(kCBLDatabaseChangeNotification object database queue nil) (notification) -gt Void
in if let changes = notificationuserInfo[changes] as [CBLDatabaseChange] for change in changes
dispatch_async(dispatch_get_main_queue() selfsaveImageFromDocument(changedocumentID) )
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Generate and display a QR code
httpuserpasswordltlistener hostgtltportgtdb
Uses the iOS Core Image filter
copy2015 Couchbase Inc lsaquorsaquo
SendViewControllerStep 1 Scan a QR code
Uses the iOS class AVCaptureSession with the output type AVMetadataObjectTypeQRCode
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Create documents
var docIds [String] = []for asset in sharedAssets
var data = NSData(bytesNoCopy imageBytes length buffered freeWhenDone true)
let doc = databasecreateDocument()let rev = docnewRevision()revsetAttachmentNamed(photo withContentType applicationoctet-stream
content data)let saved = revsave(amperror)
if saved = nil docIdsappend(docdocumentID)
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Replicate documents
replicator = databasecreatePushReplication(url)replicatordocumentIDs = docIds
NSNotificationCenterdefaultCenter()addObserverForName(kCBLReplicationChangeNotification object replicator queue nil) (notification) -gt Void in
if selfreplicatorlastError == nil var totalCount = selfreplicatorchangesCountvar completedCount = selfreplicatorcompletedChangesCountif completedCount gt 0 ampamp completedCount == totalCount
selfstatusLabeltext = Sending Completedrdquo
else selfstatusLabeltext = Sending Abort
replicatorstart()
copy2015 Couchbase Inc lsaquorsaquo
Source Code
httpsgithubcomcouchbaselabsphoto-drop
Demo 2PhotoDrop App
The End mdash Any Questions
copy2015 Couchbase Inc lsaquorsaquo
Hybrid Approaches
ldquoA server is just a well-connected peerrdquoClients can connect to local peers and to a
server
Peer-to-Peer With Couchbase Mobile
copy2015 Couchbase Inc lsaquorsaquo
Couchbase Mobile Replication
Based on CouchDB architectureDesigned from the start for arbitrary topologies
Not the same as Couchbase Serverrsquos XDCR
Replicator
REST API
Active Passive
copy2015 Couchbase Inc lsaquorsaquo
Star Topology
copy2015 Couchbase Inc lsaquorsaquo
Cluster Topology
ldquoCluster Of Unreliable Cheap Hardwarerdquo
copy2015 Couchbase Inc lsaquorsaquo
P2P Mesh Topology
copy2015 Couchbase Inc lsaquorsaquoReplicating Documents amp Revisions
doc1
3-a9ff
doc1
2-c31b
B ldquoWhatrsquos new since last we spokerdquoA ldquoI added rev 3-a9ff of doc1rdquoB ldquoThatrsquos new to merdquoA ldquoIrsquoll send it overhelliprdquo
A
B
copy2015 Couchbase Inc lsaquorsaquo
P2P Mesh Topology
copy2015 Couchbase Inc lsaquorsaquo
The Problem With Naiumlve Meshes
O(n2) connections is badReal mesh networks limit connectionsSpanning treesGossip protocols
Implementing Peer-to-PeerPart 1
Allowing Connections
copy2015 Couchbase Inc lsaquorsaquo
Allowing Peer Connections
Link Couchbase Lite Listener component into appStart listenerCongratulations You are now a replication
ldquoserverrdquo
Datastore
CBL API
App
ReplicatorCBL API
App
Datastore
REST API
copy2015 Couchbase Inc lsaquorsaquo
Allowing Peer Connections
listener = CBLListener(manager databasemanager port 55555) listenerreadOnly = true
For SecurityPrevents peers from pushing Docs to you
Or port 0 to allow the OS to choose a random open port
but a fixed port is more optimal for the peerrsquos replicator
Implementing Peer-to-PeerPart 2
Automatic Peer Discovery
copy2015 Couchbase Inc lsaquorsaquo
Automatic Peer Discovery
ldquoWhorsquos running this serviceapp [on this LAN]rdquoAdvertise your own serviceTypeNameAddress + portSmall metadata (timestamphellip)
Browse for same service typeNotified as peers go onoffline
copy2015 Couchbase Inc lsaquorsaquo
Multicast DNS (mDNS) DNS Service Discovery (DNS-SD)
aka Bonjourtrade ZeroConf Avahi Network Service Discovery
RFC 6762 RFC 6763iOS Mac OS X Android (41+) LinuxWindows apps can integrate Applersquos
mDNSResponderdeveloperapplecomlibrarymacdocumentation
NetworkingConceptualNSNetServiceProgGuidedeveloperandroidcomtrainingconnect-devices-
wirelessly
copy2015 Couchbase Inc lsaquorsaquo
Advertising Your Service
listener = CBLListener(manager databasemanager port 55555) listenerreadOnly = true listenersetBonjourName(userNickname type _myapp_tcp)
Note setBonjourName isnrsquot available in CBL on Android yet Instead use NsdServiceInfo directly
Service name might be altered (number appended) to disambiguate it
copy2015 Couchbase Inc lsaquorsaquo
Browsing For Peers (iOS)
browser = NSNetServiceBrowsernew() browserincludesPeerToPeer = true browserdelegate = self browsersearchForServicesOfType(_myapp_tcp inDomain local)
public func netServiceBrowser(sender NSNetServiceBrowser didFindService service NSNetService moreComing Bool) hellip
public func netServiceBrowser(sender NSNetServiceBrowser didRemoveService service NSNetService moreComing Bool) hellip
copy2015 Couchbase Inc lsaquorsaquo
Connecting To A Peer (iOS)
Start async resolve to find servicersquos hostname servicedelegate = self serviceresolveWithTimeout(50)
NSNetService delegate callback public func netServiceDidResolveAddress(service NSNetService) Construct the remote DB URL var components = NSURLComponents() componentsscheme = http Or https if peer uses SSL componentshost = servicehostName componentsport = serviceport componentspath = + remoteDatabaseName let url = componentsURL
Start replication pull = localDBcreatePullReplication(url) pullstart()
copy2015 Couchbase Inc lsaquorsaquo
Using Bonjour To Replicate
Advertise a UUID as part of your service namePublish my dblatestSequence in service
metadataRemember UUID latestSequence of each lsquopairedrsquo
peerWhen peerrsquos latestSequence changes start a
pull replication
DEMO IPeerSync App
Q Whatrsquos Wrong With That DemoA No authentication
copy2015 Couchbase Inc lsaquorsaquo
C
Forging Documents or Revisions
docByA
B
A
B is sending me lsquodocByArsquo hellip but how
do I know it was really created by A
128530
128519
128564
copy2015 Couchbase Inc lsaquorsaquo
P2P Authentication Is A Hard Problem
With no server accountshow do you prove who you are
With no server to trusthow do you know whether data is valid
copy2015 Couchbase Inc lsaquorsaquo
This Is Not A Typical Auth Problem
SSL doesnrsquot helpHTTP authentication (ArArrB or BrArrC) doesnrsquot helpOnly authenticating the data helps
copy2015 Couchbase Inc lsaquorsaquo
Digital Signatures
Every user or device generates a key-pairEvery revision is signed by the party who created
itTo validate a revisionMake sure the signature is validLook up the authorrsquos public keyCompare signing key with authorrsquos key
copy2015 Couchbase Inc lsaquorsaquo
Key Distribution
Traditional StyleTrusted authority (server) signs key into a
certificateServer distributes certificate
P2P StyleDevice uses raw key or self-signed certificateUsers lsquopairrsquo devices in person
trading keys over a secure channel
Implementing Peer-to-PeerPart 3
Manual 11 Pairing
Pasin Suriyentrakorn
copy2015 Couchbase Inc lsaquorsaquo
PhotoDrop
Receiver ndash Presenting the QR Code and Receiving Photos
Sender ndash Selecting Photos Sender ndash Scanning a QR Code and Sending Photos
copy2015 Couchbase Inc lsaquorsaquo
ImplementationUses a QR code for peer discoveryUses one-time push replication to transfer photosUses digest authenticationGenerates one-time user credentialsSupports multiple platforms (eg iOS and
Android)
copy2015 Couchbase Inc lsaquorsaquo
StoryboardViewController SendViewController
ReceiveViewController
QR Code Scanner
Presents a QR code
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 1 Start a listener
listener = CBLListener(manager CBLManagersharedInstance() port 0)
listenerrequiresAuth = truelet username = secureGenerateKey(NSCharacterSetURLUserAllowedCharacterSet())let password = secureGenerateKey(NSCharacterSetURLPasswordAllowedCharacterSet())listenersetPasswords([username password])
var success = listenerstart(amperror)if (success)
syncUrl = genearteSyncURL(listenerURL username username password password dbName databasename)
startObserveDatabaseChange()
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Observe database changes
func startObserveDatabaseChange() NSNotificationCenterdefaultCenter()addObserverForName(kCBLDatabaseChangeNotification object database queue nil) (notification) -gt Void
in if let changes = notificationuserInfo[changes] as [CBLDatabaseChange] for change in changes
dispatch_async(dispatch_get_main_queue() selfsaveImageFromDocument(changedocumentID) )
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Generate and display a QR code
httpuserpasswordltlistener hostgtltportgtdb
Uses the iOS Core Image filter
copy2015 Couchbase Inc lsaquorsaquo
SendViewControllerStep 1 Scan a QR code
Uses the iOS class AVCaptureSession with the output type AVMetadataObjectTypeQRCode
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Create documents
var docIds [String] = []for asset in sharedAssets
var data = NSData(bytesNoCopy imageBytes length buffered freeWhenDone true)
let doc = databasecreateDocument()let rev = docnewRevision()revsetAttachmentNamed(photo withContentType applicationoctet-stream
content data)let saved = revsave(amperror)
if saved = nil docIdsappend(docdocumentID)
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Replicate documents
replicator = databasecreatePushReplication(url)replicatordocumentIDs = docIds
NSNotificationCenterdefaultCenter()addObserverForName(kCBLReplicationChangeNotification object replicator queue nil) (notification) -gt Void in
if selfreplicatorlastError == nil var totalCount = selfreplicatorchangesCountvar completedCount = selfreplicatorcompletedChangesCountif completedCount gt 0 ampamp completedCount == totalCount
selfstatusLabeltext = Sending Completedrdquo
else selfstatusLabeltext = Sending Abort
replicatorstart()
copy2015 Couchbase Inc lsaquorsaquo
Source Code
httpsgithubcomcouchbaselabsphoto-drop
Demo 2PhotoDrop App
The End mdash Any Questions
Peer-to-Peer With Couchbase Mobile
copy2015 Couchbase Inc lsaquorsaquo
Couchbase Mobile Replication
Based on CouchDB architectureDesigned from the start for arbitrary topologies
Not the same as Couchbase Serverrsquos XDCR
Replicator
REST API
Active Passive
copy2015 Couchbase Inc lsaquorsaquo
Star Topology
copy2015 Couchbase Inc lsaquorsaquo
Cluster Topology
ldquoCluster Of Unreliable Cheap Hardwarerdquo
copy2015 Couchbase Inc lsaquorsaquo
P2P Mesh Topology
copy2015 Couchbase Inc lsaquorsaquoReplicating Documents amp Revisions
doc1
3-a9ff
doc1
2-c31b
B ldquoWhatrsquos new since last we spokerdquoA ldquoI added rev 3-a9ff of doc1rdquoB ldquoThatrsquos new to merdquoA ldquoIrsquoll send it overhelliprdquo
A
B
copy2015 Couchbase Inc lsaquorsaquo
P2P Mesh Topology
copy2015 Couchbase Inc lsaquorsaquo
The Problem With Naiumlve Meshes
O(n2) connections is badReal mesh networks limit connectionsSpanning treesGossip protocols
Implementing Peer-to-PeerPart 1
Allowing Connections
copy2015 Couchbase Inc lsaquorsaquo
Allowing Peer Connections
Link Couchbase Lite Listener component into appStart listenerCongratulations You are now a replication
ldquoserverrdquo
Datastore
CBL API
App
ReplicatorCBL API
App
Datastore
REST API
copy2015 Couchbase Inc lsaquorsaquo
Allowing Peer Connections
listener = CBLListener(manager databasemanager port 55555) listenerreadOnly = true
For SecurityPrevents peers from pushing Docs to you
Or port 0 to allow the OS to choose a random open port
but a fixed port is more optimal for the peerrsquos replicator
Implementing Peer-to-PeerPart 2
Automatic Peer Discovery
copy2015 Couchbase Inc lsaquorsaquo
Automatic Peer Discovery
ldquoWhorsquos running this serviceapp [on this LAN]rdquoAdvertise your own serviceTypeNameAddress + portSmall metadata (timestamphellip)
Browse for same service typeNotified as peers go onoffline
copy2015 Couchbase Inc lsaquorsaquo
Multicast DNS (mDNS) DNS Service Discovery (DNS-SD)
aka Bonjourtrade ZeroConf Avahi Network Service Discovery
RFC 6762 RFC 6763iOS Mac OS X Android (41+) LinuxWindows apps can integrate Applersquos
mDNSResponderdeveloperapplecomlibrarymacdocumentation
NetworkingConceptualNSNetServiceProgGuidedeveloperandroidcomtrainingconnect-devices-
wirelessly
copy2015 Couchbase Inc lsaquorsaquo
Advertising Your Service
listener = CBLListener(manager databasemanager port 55555) listenerreadOnly = true listenersetBonjourName(userNickname type _myapp_tcp)
Note setBonjourName isnrsquot available in CBL on Android yet Instead use NsdServiceInfo directly
Service name might be altered (number appended) to disambiguate it
copy2015 Couchbase Inc lsaquorsaquo
Browsing For Peers (iOS)
browser = NSNetServiceBrowsernew() browserincludesPeerToPeer = true browserdelegate = self browsersearchForServicesOfType(_myapp_tcp inDomain local)
public func netServiceBrowser(sender NSNetServiceBrowser didFindService service NSNetService moreComing Bool) hellip
public func netServiceBrowser(sender NSNetServiceBrowser didRemoveService service NSNetService moreComing Bool) hellip
copy2015 Couchbase Inc lsaquorsaquo
Connecting To A Peer (iOS)
Start async resolve to find servicersquos hostname servicedelegate = self serviceresolveWithTimeout(50)
NSNetService delegate callback public func netServiceDidResolveAddress(service NSNetService) Construct the remote DB URL var components = NSURLComponents() componentsscheme = http Or https if peer uses SSL componentshost = servicehostName componentsport = serviceport componentspath = + remoteDatabaseName let url = componentsURL
Start replication pull = localDBcreatePullReplication(url) pullstart()
copy2015 Couchbase Inc lsaquorsaquo
Using Bonjour To Replicate
Advertise a UUID as part of your service namePublish my dblatestSequence in service
metadataRemember UUID latestSequence of each lsquopairedrsquo
peerWhen peerrsquos latestSequence changes start a
pull replication
DEMO IPeerSync App
Q Whatrsquos Wrong With That DemoA No authentication
copy2015 Couchbase Inc lsaquorsaquo
C
Forging Documents or Revisions
docByA
B
A
B is sending me lsquodocByArsquo hellip but how
do I know it was really created by A
128530
128519
128564
copy2015 Couchbase Inc lsaquorsaquo
P2P Authentication Is A Hard Problem
With no server accountshow do you prove who you are
With no server to trusthow do you know whether data is valid
copy2015 Couchbase Inc lsaquorsaquo
This Is Not A Typical Auth Problem
SSL doesnrsquot helpHTTP authentication (ArArrB or BrArrC) doesnrsquot helpOnly authenticating the data helps
copy2015 Couchbase Inc lsaquorsaquo
Digital Signatures
Every user or device generates a key-pairEvery revision is signed by the party who created
itTo validate a revisionMake sure the signature is validLook up the authorrsquos public keyCompare signing key with authorrsquos key
copy2015 Couchbase Inc lsaquorsaquo
Key Distribution
Traditional StyleTrusted authority (server) signs key into a
certificateServer distributes certificate
P2P StyleDevice uses raw key or self-signed certificateUsers lsquopairrsquo devices in person
trading keys over a secure channel
Implementing Peer-to-PeerPart 3
Manual 11 Pairing
Pasin Suriyentrakorn
copy2015 Couchbase Inc lsaquorsaquo
PhotoDrop
Receiver ndash Presenting the QR Code and Receiving Photos
Sender ndash Selecting Photos Sender ndash Scanning a QR Code and Sending Photos
copy2015 Couchbase Inc lsaquorsaquo
ImplementationUses a QR code for peer discoveryUses one-time push replication to transfer photosUses digest authenticationGenerates one-time user credentialsSupports multiple platforms (eg iOS and
Android)
copy2015 Couchbase Inc lsaquorsaquo
StoryboardViewController SendViewController
ReceiveViewController
QR Code Scanner
Presents a QR code
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 1 Start a listener
listener = CBLListener(manager CBLManagersharedInstance() port 0)
listenerrequiresAuth = truelet username = secureGenerateKey(NSCharacterSetURLUserAllowedCharacterSet())let password = secureGenerateKey(NSCharacterSetURLPasswordAllowedCharacterSet())listenersetPasswords([username password])
var success = listenerstart(amperror)if (success)
syncUrl = genearteSyncURL(listenerURL username username password password dbName databasename)
startObserveDatabaseChange()
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Observe database changes
func startObserveDatabaseChange() NSNotificationCenterdefaultCenter()addObserverForName(kCBLDatabaseChangeNotification object database queue nil) (notification) -gt Void
in if let changes = notificationuserInfo[changes] as [CBLDatabaseChange] for change in changes
dispatch_async(dispatch_get_main_queue() selfsaveImageFromDocument(changedocumentID) )
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Generate and display a QR code
httpuserpasswordltlistener hostgtltportgtdb
Uses the iOS Core Image filter
copy2015 Couchbase Inc lsaquorsaquo
SendViewControllerStep 1 Scan a QR code
Uses the iOS class AVCaptureSession with the output type AVMetadataObjectTypeQRCode
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Create documents
var docIds [String] = []for asset in sharedAssets
var data = NSData(bytesNoCopy imageBytes length buffered freeWhenDone true)
let doc = databasecreateDocument()let rev = docnewRevision()revsetAttachmentNamed(photo withContentType applicationoctet-stream
content data)let saved = revsave(amperror)
if saved = nil docIdsappend(docdocumentID)
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Replicate documents
replicator = databasecreatePushReplication(url)replicatordocumentIDs = docIds
NSNotificationCenterdefaultCenter()addObserverForName(kCBLReplicationChangeNotification object replicator queue nil) (notification) -gt Void in
if selfreplicatorlastError == nil var totalCount = selfreplicatorchangesCountvar completedCount = selfreplicatorcompletedChangesCountif completedCount gt 0 ampamp completedCount == totalCount
selfstatusLabeltext = Sending Completedrdquo
else selfstatusLabeltext = Sending Abort
replicatorstart()
copy2015 Couchbase Inc lsaquorsaquo
Source Code
httpsgithubcomcouchbaselabsphoto-drop
Demo 2PhotoDrop App
The End mdash Any Questions
copy2015 Couchbase Inc lsaquorsaquo
Couchbase Mobile Replication
Based on CouchDB architectureDesigned from the start for arbitrary topologies
Not the same as Couchbase Serverrsquos XDCR
Replicator
REST API
Active Passive
copy2015 Couchbase Inc lsaquorsaquo
Star Topology
copy2015 Couchbase Inc lsaquorsaquo
Cluster Topology
ldquoCluster Of Unreliable Cheap Hardwarerdquo
copy2015 Couchbase Inc lsaquorsaquo
P2P Mesh Topology
copy2015 Couchbase Inc lsaquorsaquoReplicating Documents amp Revisions
doc1
3-a9ff
doc1
2-c31b
B ldquoWhatrsquos new since last we spokerdquoA ldquoI added rev 3-a9ff of doc1rdquoB ldquoThatrsquos new to merdquoA ldquoIrsquoll send it overhelliprdquo
A
B
copy2015 Couchbase Inc lsaquorsaquo
P2P Mesh Topology
copy2015 Couchbase Inc lsaquorsaquo
The Problem With Naiumlve Meshes
O(n2) connections is badReal mesh networks limit connectionsSpanning treesGossip protocols
Implementing Peer-to-PeerPart 1
Allowing Connections
copy2015 Couchbase Inc lsaquorsaquo
Allowing Peer Connections
Link Couchbase Lite Listener component into appStart listenerCongratulations You are now a replication
ldquoserverrdquo
Datastore
CBL API
App
ReplicatorCBL API
App
Datastore
REST API
copy2015 Couchbase Inc lsaquorsaquo
Allowing Peer Connections
listener = CBLListener(manager databasemanager port 55555) listenerreadOnly = true
For SecurityPrevents peers from pushing Docs to you
Or port 0 to allow the OS to choose a random open port
but a fixed port is more optimal for the peerrsquos replicator
Implementing Peer-to-PeerPart 2
Automatic Peer Discovery
copy2015 Couchbase Inc lsaquorsaquo
Automatic Peer Discovery
ldquoWhorsquos running this serviceapp [on this LAN]rdquoAdvertise your own serviceTypeNameAddress + portSmall metadata (timestamphellip)
Browse for same service typeNotified as peers go onoffline
copy2015 Couchbase Inc lsaquorsaquo
Multicast DNS (mDNS) DNS Service Discovery (DNS-SD)
aka Bonjourtrade ZeroConf Avahi Network Service Discovery
RFC 6762 RFC 6763iOS Mac OS X Android (41+) LinuxWindows apps can integrate Applersquos
mDNSResponderdeveloperapplecomlibrarymacdocumentation
NetworkingConceptualNSNetServiceProgGuidedeveloperandroidcomtrainingconnect-devices-
wirelessly
copy2015 Couchbase Inc lsaquorsaquo
Advertising Your Service
listener = CBLListener(manager databasemanager port 55555) listenerreadOnly = true listenersetBonjourName(userNickname type _myapp_tcp)
Note setBonjourName isnrsquot available in CBL on Android yet Instead use NsdServiceInfo directly
Service name might be altered (number appended) to disambiguate it
copy2015 Couchbase Inc lsaquorsaquo
Browsing For Peers (iOS)
browser = NSNetServiceBrowsernew() browserincludesPeerToPeer = true browserdelegate = self browsersearchForServicesOfType(_myapp_tcp inDomain local)
public func netServiceBrowser(sender NSNetServiceBrowser didFindService service NSNetService moreComing Bool) hellip
public func netServiceBrowser(sender NSNetServiceBrowser didRemoveService service NSNetService moreComing Bool) hellip
copy2015 Couchbase Inc lsaquorsaquo
Connecting To A Peer (iOS)
Start async resolve to find servicersquos hostname servicedelegate = self serviceresolveWithTimeout(50)
NSNetService delegate callback public func netServiceDidResolveAddress(service NSNetService) Construct the remote DB URL var components = NSURLComponents() componentsscheme = http Or https if peer uses SSL componentshost = servicehostName componentsport = serviceport componentspath = + remoteDatabaseName let url = componentsURL
Start replication pull = localDBcreatePullReplication(url) pullstart()
copy2015 Couchbase Inc lsaquorsaquo
Using Bonjour To Replicate
Advertise a UUID as part of your service namePublish my dblatestSequence in service
metadataRemember UUID latestSequence of each lsquopairedrsquo
peerWhen peerrsquos latestSequence changes start a
pull replication
DEMO IPeerSync App
Q Whatrsquos Wrong With That DemoA No authentication
copy2015 Couchbase Inc lsaquorsaquo
C
Forging Documents or Revisions
docByA
B
A
B is sending me lsquodocByArsquo hellip but how
do I know it was really created by A
128530
128519
128564
copy2015 Couchbase Inc lsaquorsaquo
P2P Authentication Is A Hard Problem
With no server accountshow do you prove who you are
With no server to trusthow do you know whether data is valid
copy2015 Couchbase Inc lsaquorsaquo
This Is Not A Typical Auth Problem
SSL doesnrsquot helpHTTP authentication (ArArrB or BrArrC) doesnrsquot helpOnly authenticating the data helps
copy2015 Couchbase Inc lsaquorsaquo
Digital Signatures
Every user or device generates a key-pairEvery revision is signed by the party who created
itTo validate a revisionMake sure the signature is validLook up the authorrsquos public keyCompare signing key with authorrsquos key
copy2015 Couchbase Inc lsaquorsaquo
Key Distribution
Traditional StyleTrusted authority (server) signs key into a
certificateServer distributes certificate
P2P StyleDevice uses raw key or self-signed certificateUsers lsquopairrsquo devices in person
trading keys over a secure channel
Implementing Peer-to-PeerPart 3
Manual 11 Pairing
Pasin Suriyentrakorn
copy2015 Couchbase Inc lsaquorsaquo
PhotoDrop
Receiver ndash Presenting the QR Code and Receiving Photos
Sender ndash Selecting Photos Sender ndash Scanning a QR Code and Sending Photos
copy2015 Couchbase Inc lsaquorsaquo
ImplementationUses a QR code for peer discoveryUses one-time push replication to transfer photosUses digest authenticationGenerates one-time user credentialsSupports multiple platforms (eg iOS and
Android)
copy2015 Couchbase Inc lsaquorsaquo
StoryboardViewController SendViewController
ReceiveViewController
QR Code Scanner
Presents a QR code
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 1 Start a listener
listener = CBLListener(manager CBLManagersharedInstance() port 0)
listenerrequiresAuth = truelet username = secureGenerateKey(NSCharacterSetURLUserAllowedCharacterSet())let password = secureGenerateKey(NSCharacterSetURLPasswordAllowedCharacterSet())listenersetPasswords([username password])
var success = listenerstart(amperror)if (success)
syncUrl = genearteSyncURL(listenerURL username username password password dbName databasename)
startObserveDatabaseChange()
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Observe database changes
func startObserveDatabaseChange() NSNotificationCenterdefaultCenter()addObserverForName(kCBLDatabaseChangeNotification object database queue nil) (notification) -gt Void
in if let changes = notificationuserInfo[changes] as [CBLDatabaseChange] for change in changes
dispatch_async(dispatch_get_main_queue() selfsaveImageFromDocument(changedocumentID) )
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Generate and display a QR code
httpuserpasswordltlistener hostgtltportgtdb
Uses the iOS Core Image filter
copy2015 Couchbase Inc lsaquorsaquo
SendViewControllerStep 1 Scan a QR code
Uses the iOS class AVCaptureSession with the output type AVMetadataObjectTypeQRCode
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Create documents
var docIds [String] = []for asset in sharedAssets
var data = NSData(bytesNoCopy imageBytes length buffered freeWhenDone true)
let doc = databasecreateDocument()let rev = docnewRevision()revsetAttachmentNamed(photo withContentType applicationoctet-stream
content data)let saved = revsave(amperror)
if saved = nil docIdsappend(docdocumentID)
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Replicate documents
replicator = databasecreatePushReplication(url)replicatordocumentIDs = docIds
NSNotificationCenterdefaultCenter()addObserverForName(kCBLReplicationChangeNotification object replicator queue nil) (notification) -gt Void in
if selfreplicatorlastError == nil var totalCount = selfreplicatorchangesCountvar completedCount = selfreplicatorcompletedChangesCountif completedCount gt 0 ampamp completedCount == totalCount
selfstatusLabeltext = Sending Completedrdquo
else selfstatusLabeltext = Sending Abort
replicatorstart()
copy2015 Couchbase Inc lsaquorsaquo
Source Code
httpsgithubcomcouchbaselabsphoto-drop
Demo 2PhotoDrop App
The End mdash Any Questions
copy2015 Couchbase Inc lsaquorsaquo
Star Topology
copy2015 Couchbase Inc lsaquorsaquo
Cluster Topology
ldquoCluster Of Unreliable Cheap Hardwarerdquo
copy2015 Couchbase Inc lsaquorsaquo
P2P Mesh Topology
copy2015 Couchbase Inc lsaquorsaquoReplicating Documents amp Revisions
doc1
3-a9ff
doc1
2-c31b
B ldquoWhatrsquos new since last we spokerdquoA ldquoI added rev 3-a9ff of doc1rdquoB ldquoThatrsquos new to merdquoA ldquoIrsquoll send it overhelliprdquo
A
B
copy2015 Couchbase Inc lsaquorsaquo
P2P Mesh Topology
copy2015 Couchbase Inc lsaquorsaquo
The Problem With Naiumlve Meshes
O(n2) connections is badReal mesh networks limit connectionsSpanning treesGossip protocols
Implementing Peer-to-PeerPart 1
Allowing Connections
copy2015 Couchbase Inc lsaquorsaquo
Allowing Peer Connections
Link Couchbase Lite Listener component into appStart listenerCongratulations You are now a replication
ldquoserverrdquo
Datastore
CBL API
App
ReplicatorCBL API
App
Datastore
REST API
copy2015 Couchbase Inc lsaquorsaquo
Allowing Peer Connections
listener = CBLListener(manager databasemanager port 55555) listenerreadOnly = true
For SecurityPrevents peers from pushing Docs to you
Or port 0 to allow the OS to choose a random open port
but a fixed port is more optimal for the peerrsquos replicator
Implementing Peer-to-PeerPart 2
Automatic Peer Discovery
copy2015 Couchbase Inc lsaquorsaquo
Automatic Peer Discovery
ldquoWhorsquos running this serviceapp [on this LAN]rdquoAdvertise your own serviceTypeNameAddress + portSmall metadata (timestamphellip)
Browse for same service typeNotified as peers go onoffline
copy2015 Couchbase Inc lsaquorsaquo
Multicast DNS (mDNS) DNS Service Discovery (DNS-SD)
aka Bonjourtrade ZeroConf Avahi Network Service Discovery
RFC 6762 RFC 6763iOS Mac OS X Android (41+) LinuxWindows apps can integrate Applersquos
mDNSResponderdeveloperapplecomlibrarymacdocumentation
NetworkingConceptualNSNetServiceProgGuidedeveloperandroidcomtrainingconnect-devices-
wirelessly
copy2015 Couchbase Inc lsaquorsaquo
Advertising Your Service
listener = CBLListener(manager databasemanager port 55555) listenerreadOnly = true listenersetBonjourName(userNickname type _myapp_tcp)
Note setBonjourName isnrsquot available in CBL on Android yet Instead use NsdServiceInfo directly
Service name might be altered (number appended) to disambiguate it
copy2015 Couchbase Inc lsaquorsaquo
Browsing For Peers (iOS)
browser = NSNetServiceBrowsernew() browserincludesPeerToPeer = true browserdelegate = self browsersearchForServicesOfType(_myapp_tcp inDomain local)
public func netServiceBrowser(sender NSNetServiceBrowser didFindService service NSNetService moreComing Bool) hellip
public func netServiceBrowser(sender NSNetServiceBrowser didRemoveService service NSNetService moreComing Bool) hellip
copy2015 Couchbase Inc lsaquorsaquo
Connecting To A Peer (iOS)
Start async resolve to find servicersquos hostname servicedelegate = self serviceresolveWithTimeout(50)
NSNetService delegate callback public func netServiceDidResolveAddress(service NSNetService) Construct the remote DB URL var components = NSURLComponents() componentsscheme = http Or https if peer uses SSL componentshost = servicehostName componentsport = serviceport componentspath = + remoteDatabaseName let url = componentsURL
Start replication pull = localDBcreatePullReplication(url) pullstart()
copy2015 Couchbase Inc lsaquorsaquo
Using Bonjour To Replicate
Advertise a UUID as part of your service namePublish my dblatestSequence in service
metadataRemember UUID latestSequence of each lsquopairedrsquo
peerWhen peerrsquos latestSequence changes start a
pull replication
DEMO IPeerSync App
Q Whatrsquos Wrong With That DemoA No authentication
copy2015 Couchbase Inc lsaquorsaquo
C
Forging Documents or Revisions
docByA
B
A
B is sending me lsquodocByArsquo hellip but how
do I know it was really created by A
128530
128519
128564
copy2015 Couchbase Inc lsaquorsaquo
P2P Authentication Is A Hard Problem
With no server accountshow do you prove who you are
With no server to trusthow do you know whether data is valid
copy2015 Couchbase Inc lsaquorsaquo
This Is Not A Typical Auth Problem
SSL doesnrsquot helpHTTP authentication (ArArrB or BrArrC) doesnrsquot helpOnly authenticating the data helps
copy2015 Couchbase Inc lsaquorsaquo
Digital Signatures
Every user or device generates a key-pairEvery revision is signed by the party who created
itTo validate a revisionMake sure the signature is validLook up the authorrsquos public keyCompare signing key with authorrsquos key
copy2015 Couchbase Inc lsaquorsaquo
Key Distribution
Traditional StyleTrusted authority (server) signs key into a
certificateServer distributes certificate
P2P StyleDevice uses raw key or self-signed certificateUsers lsquopairrsquo devices in person
trading keys over a secure channel
Implementing Peer-to-PeerPart 3
Manual 11 Pairing
Pasin Suriyentrakorn
copy2015 Couchbase Inc lsaquorsaquo
PhotoDrop
Receiver ndash Presenting the QR Code and Receiving Photos
Sender ndash Selecting Photos Sender ndash Scanning a QR Code and Sending Photos
copy2015 Couchbase Inc lsaquorsaquo
ImplementationUses a QR code for peer discoveryUses one-time push replication to transfer photosUses digest authenticationGenerates one-time user credentialsSupports multiple platforms (eg iOS and
Android)
copy2015 Couchbase Inc lsaquorsaquo
StoryboardViewController SendViewController
ReceiveViewController
QR Code Scanner
Presents a QR code
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 1 Start a listener
listener = CBLListener(manager CBLManagersharedInstance() port 0)
listenerrequiresAuth = truelet username = secureGenerateKey(NSCharacterSetURLUserAllowedCharacterSet())let password = secureGenerateKey(NSCharacterSetURLPasswordAllowedCharacterSet())listenersetPasswords([username password])
var success = listenerstart(amperror)if (success)
syncUrl = genearteSyncURL(listenerURL username username password password dbName databasename)
startObserveDatabaseChange()
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Observe database changes
func startObserveDatabaseChange() NSNotificationCenterdefaultCenter()addObserverForName(kCBLDatabaseChangeNotification object database queue nil) (notification) -gt Void
in if let changes = notificationuserInfo[changes] as [CBLDatabaseChange] for change in changes
dispatch_async(dispatch_get_main_queue() selfsaveImageFromDocument(changedocumentID) )
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Generate and display a QR code
httpuserpasswordltlistener hostgtltportgtdb
Uses the iOS Core Image filter
copy2015 Couchbase Inc lsaquorsaquo
SendViewControllerStep 1 Scan a QR code
Uses the iOS class AVCaptureSession with the output type AVMetadataObjectTypeQRCode
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Create documents
var docIds [String] = []for asset in sharedAssets
var data = NSData(bytesNoCopy imageBytes length buffered freeWhenDone true)
let doc = databasecreateDocument()let rev = docnewRevision()revsetAttachmentNamed(photo withContentType applicationoctet-stream
content data)let saved = revsave(amperror)
if saved = nil docIdsappend(docdocumentID)
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Replicate documents
replicator = databasecreatePushReplication(url)replicatordocumentIDs = docIds
NSNotificationCenterdefaultCenter()addObserverForName(kCBLReplicationChangeNotification object replicator queue nil) (notification) -gt Void in
if selfreplicatorlastError == nil var totalCount = selfreplicatorchangesCountvar completedCount = selfreplicatorcompletedChangesCountif completedCount gt 0 ampamp completedCount == totalCount
selfstatusLabeltext = Sending Completedrdquo
else selfstatusLabeltext = Sending Abort
replicatorstart()
copy2015 Couchbase Inc lsaquorsaquo
Source Code
httpsgithubcomcouchbaselabsphoto-drop
Demo 2PhotoDrop App
The End mdash Any Questions
copy2015 Couchbase Inc lsaquorsaquo
Cluster Topology
ldquoCluster Of Unreliable Cheap Hardwarerdquo
copy2015 Couchbase Inc lsaquorsaquo
P2P Mesh Topology
copy2015 Couchbase Inc lsaquorsaquoReplicating Documents amp Revisions
doc1
3-a9ff
doc1
2-c31b
B ldquoWhatrsquos new since last we spokerdquoA ldquoI added rev 3-a9ff of doc1rdquoB ldquoThatrsquos new to merdquoA ldquoIrsquoll send it overhelliprdquo
A
B
copy2015 Couchbase Inc lsaquorsaquo
P2P Mesh Topology
copy2015 Couchbase Inc lsaquorsaquo
The Problem With Naiumlve Meshes
O(n2) connections is badReal mesh networks limit connectionsSpanning treesGossip protocols
Implementing Peer-to-PeerPart 1
Allowing Connections
copy2015 Couchbase Inc lsaquorsaquo
Allowing Peer Connections
Link Couchbase Lite Listener component into appStart listenerCongratulations You are now a replication
ldquoserverrdquo
Datastore
CBL API
App
ReplicatorCBL API
App
Datastore
REST API
copy2015 Couchbase Inc lsaquorsaquo
Allowing Peer Connections
listener = CBLListener(manager databasemanager port 55555) listenerreadOnly = true
For SecurityPrevents peers from pushing Docs to you
Or port 0 to allow the OS to choose a random open port
but a fixed port is more optimal for the peerrsquos replicator
Implementing Peer-to-PeerPart 2
Automatic Peer Discovery
copy2015 Couchbase Inc lsaquorsaquo
Automatic Peer Discovery
ldquoWhorsquos running this serviceapp [on this LAN]rdquoAdvertise your own serviceTypeNameAddress + portSmall metadata (timestamphellip)
Browse for same service typeNotified as peers go onoffline
copy2015 Couchbase Inc lsaquorsaquo
Multicast DNS (mDNS) DNS Service Discovery (DNS-SD)
aka Bonjourtrade ZeroConf Avahi Network Service Discovery
RFC 6762 RFC 6763iOS Mac OS X Android (41+) LinuxWindows apps can integrate Applersquos
mDNSResponderdeveloperapplecomlibrarymacdocumentation
NetworkingConceptualNSNetServiceProgGuidedeveloperandroidcomtrainingconnect-devices-
wirelessly
copy2015 Couchbase Inc lsaquorsaquo
Advertising Your Service
listener = CBLListener(manager databasemanager port 55555) listenerreadOnly = true listenersetBonjourName(userNickname type _myapp_tcp)
Note setBonjourName isnrsquot available in CBL on Android yet Instead use NsdServiceInfo directly
Service name might be altered (number appended) to disambiguate it
copy2015 Couchbase Inc lsaquorsaquo
Browsing For Peers (iOS)
browser = NSNetServiceBrowsernew() browserincludesPeerToPeer = true browserdelegate = self browsersearchForServicesOfType(_myapp_tcp inDomain local)
public func netServiceBrowser(sender NSNetServiceBrowser didFindService service NSNetService moreComing Bool) hellip
public func netServiceBrowser(sender NSNetServiceBrowser didRemoveService service NSNetService moreComing Bool) hellip
copy2015 Couchbase Inc lsaquorsaquo
Connecting To A Peer (iOS)
Start async resolve to find servicersquos hostname servicedelegate = self serviceresolveWithTimeout(50)
NSNetService delegate callback public func netServiceDidResolveAddress(service NSNetService) Construct the remote DB URL var components = NSURLComponents() componentsscheme = http Or https if peer uses SSL componentshost = servicehostName componentsport = serviceport componentspath = + remoteDatabaseName let url = componentsURL
Start replication pull = localDBcreatePullReplication(url) pullstart()
copy2015 Couchbase Inc lsaquorsaquo
Using Bonjour To Replicate
Advertise a UUID as part of your service namePublish my dblatestSequence in service
metadataRemember UUID latestSequence of each lsquopairedrsquo
peerWhen peerrsquos latestSequence changes start a
pull replication
DEMO IPeerSync App
Q Whatrsquos Wrong With That DemoA No authentication
copy2015 Couchbase Inc lsaquorsaquo
C
Forging Documents or Revisions
docByA
B
A
B is sending me lsquodocByArsquo hellip but how
do I know it was really created by A
128530
128519
128564
copy2015 Couchbase Inc lsaquorsaquo
P2P Authentication Is A Hard Problem
With no server accountshow do you prove who you are
With no server to trusthow do you know whether data is valid
copy2015 Couchbase Inc lsaquorsaquo
This Is Not A Typical Auth Problem
SSL doesnrsquot helpHTTP authentication (ArArrB or BrArrC) doesnrsquot helpOnly authenticating the data helps
copy2015 Couchbase Inc lsaquorsaquo
Digital Signatures
Every user or device generates a key-pairEvery revision is signed by the party who created
itTo validate a revisionMake sure the signature is validLook up the authorrsquos public keyCompare signing key with authorrsquos key
copy2015 Couchbase Inc lsaquorsaquo
Key Distribution
Traditional StyleTrusted authority (server) signs key into a
certificateServer distributes certificate
P2P StyleDevice uses raw key or self-signed certificateUsers lsquopairrsquo devices in person
trading keys over a secure channel
Implementing Peer-to-PeerPart 3
Manual 11 Pairing
Pasin Suriyentrakorn
copy2015 Couchbase Inc lsaquorsaquo
PhotoDrop
Receiver ndash Presenting the QR Code and Receiving Photos
Sender ndash Selecting Photos Sender ndash Scanning a QR Code and Sending Photos
copy2015 Couchbase Inc lsaquorsaquo
ImplementationUses a QR code for peer discoveryUses one-time push replication to transfer photosUses digest authenticationGenerates one-time user credentialsSupports multiple platforms (eg iOS and
Android)
copy2015 Couchbase Inc lsaquorsaquo
StoryboardViewController SendViewController
ReceiveViewController
QR Code Scanner
Presents a QR code
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 1 Start a listener
listener = CBLListener(manager CBLManagersharedInstance() port 0)
listenerrequiresAuth = truelet username = secureGenerateKey(NSCharacterSetURLUserAllowedCharacterSet())let password = secureGenerateKey(NSCharacterSetURLPasswordAllowedCharacterSet())listenersetPasswords([username password])
var success = listenerstart(amperror)if (success)
syncUrl = genearteSyncURL(listenerURL username username password password dbName databasename)
startObserveDatabaseChange()
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Observe database changes
func startObserveDatabaseChange() NSNotificationCenterdefaultCenter()addObserverForName(kCBLDatabaseChangeNotification object database queue nil) (notification) -gt Void
in if let changes = notificationuserInfo[changes] as [CBLDatabaseChange] for change in changes
dispatch_async(dispatch_get_main_queue() selfsaveImageFromDocument(changedocumentID) )
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Generate and display a QR code
httpuserpasswordltlistener hostgtltportgtdb
Uses the iOS Core Image filter
copy2015 Couchbase Inc lsaquorsaquo
SendViewControllerStep 1 Scan a QR code
Uses the iOS class AVCaptureSession with the output type AVMetadataObjectTypeQRCode
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Create documents
var docIds [String] = []for asset in sharedAssets
var data = NSData(bytesNoCopy imageBytes length buffered freeWhenDone true)
let doc = databasecreateDocument()let rev = docnewRevision()revsetAttachmentNamed(photo withContentType applicationoctet-stream
content data)let saved = revsave(amperror)
if saved = nil docIdsappend(docdocumentID)
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Replicate documents
replicator = databasecreatePushReplication(url)replicatordocumentIDs = docIds
NSNotificationCenterdefaultCenter()addObserverForName(kCBLReplicationChangeNotification object replicator queue nil) (notification) -gt Void in
if selfreplicatorlastError == nil var totalCount = selfreplicatorchangesCountvar completedCount = selfreplicatorcompletedChangesCountif completedCount gt 0 ampamp completedCount == totalCount
selfstatusLabeltext = Sending Completedrdquo
else selfstatusLabeltext = Sending Abort
replicatorstart()
copy2015 Couchbase Inc lsaquorsaquo
Source Code
httpsgithubcomcouchbaselabsphoto-drop
Demo 2PhotoDrop App
The End mdash Any Questions
copy2015 Couchbase Inc lsaquorsaquo
P2P Mesh Topology
copy2015 Couchbase Inc lsaquorsaquoReplicating Documents amp Revisions
doc1
3-a9ff
doc1
2-c31b
B ldquoWhatrsquos new since last we spokerdquoA ldquoI added rev 3-a9ff of doc1rdquoB ldquoThatrsquos new to merdquoA ldquoIrsquoll send it overhelliprdquo
A
B
copy2015 Couchbase Inc lsaquorsaquo
P2P Mesh Topology
copy2015 Couchbase Inc lsaquorsaquo
The Problem With Naiumlve Meshes
O(n2) connections is badReal mesh networks limit connectionsSpanning treesGossip protocols
Implementing Peer-to-PeerPart 1
Allowing Connections
copy2015 Couchbase Inc lsaquorsaquo
Allowing Peer Connections
Link Couchbase Lite Listener component into appStart listenerCongratulations You are now a replication
ldquoserverrdquo
Datastore
CBL API
App
ReplicatorCBL API
App
Datastore
REST API
copy2015 Couchbase Inc lsaquorsaquo
Allowing Peer Connections
listener = CBLListener(manager databasemanager port 55555) listenerreadOnly = true
For SecurityPrevents peers from pushing Docs to you
Or port 0 to allow the OS to choose a random open port
but a fixed port is more optimal for the peerrsquos replicator
Implementing Peer-to-PeerPart 2
Automatic Peer Discovery
copy2015 Couchbase Inc lsaquorsaquo
Automatic Peer Discovery
ldquoWhorsquos running this serviceapp [on this LAN]rdquoAdvertise your own serviceTypeNameAddress + portSmall metadata (timestamphellip)
Browse for same service typeNotified as peers go onoffline
copy2015 Couchbase Inc lsaquorsaquo
Multicast DNS (mDNS) DNS Service Discovery (DNS-SD)
aka Bonjourtrade ZeroConf Avahi Network Service Discovery
RFC 6762 RFC 6763iOS Mac OS X Android (41+) LinuxWindows apps can integrate Applersquos
mDNSResponderdeveloperapplecomlibrarymacdocumentation
NetworkingConceptualNSNetServiceProgGuidedeveloperandroidcomtrainingconnect-devices-
wirelessly
copy2015 Couchbase Inc lsaquorsaquo
Advertising Your Service
listener = CBLListener(manager databasemanager port 55555) listenerreadOnly = true listenersetBonjourName(userNickname type _myapp_tcp)
Note setBonjourName isnrsquot available in CBL on Android yet Instead use NsdServiceInfo directly
Service name might be altered (number appended) to disambiguate it
copy2015 Couchbase Inc lsaquorsaquo
Browsing For Peers (iOS)
browser = NSNetServiceBrowsernew() browserincludesPeerToPeer = true browserdelegate = self browsersearchForServicesOfType(_myapp_tcp inDomain local)
public func netServiceBrowser(sender NSNetServiceBrowser didFindService service NSNetService moreComing Bool) hellip
public func netServiceBrowser(sender NSNetServiceBrowser didRemoveService service NSNetService moreComing Bool) hellip
copy2015 Couchbase Inc lsaquorsaquo
Connecting To A Peer (iOS)
Start async resolve to find servicersquos hostname servicedelegate = self serviceresolveWithTimeout(50)
NSNetService delegate callback public func netServiceDidResolveAddress(service NSNetService) Construct the remote DB URL var components = NSURLComponents() componentsscheme = http Or https if peer uses SSL componentshost = servicehostName componentsport = serviceport componentspath = + remoteDatabaseName let url = componentsURL
Start replication pull = localDBcreatePullReplication(url) pullstart()
copy2015 Couchbase Inc lsaquorsaquo
Using Bonjour To Replicate
Advertise a UUID as part of your service namePublish my dblatestSequence in service
metadataRemember UUID latestSequence of each lsquopairedrsquo
peerWhen peerrsquos latestSequence changes start a
pull replication
DEMO IPeerSync App
Q Whatrsquos Wrong With That DemoA No authentication
copy2015 Couchbase Inc lsaquorsaquo
C
Forging Documents or Revisions
docByA
B
A
B is sending me lsquodocByArsquo hellip but how
do I know it was really created by A
128530
128519
128564
copy2015 Couchbase Inc lsaquorsaquo
P2P Authentication Is A Hard Problem
With no server accountshow do you prove who you are
With no server to trusthow do you know whether data is valid
copy2015 Couchbase Inc lsaquorsaquo
This Is Not A Typical Auth Problem
SSL doesnrsquot helpHTTP authentication (ArArrB or BrArrC) doesnrsquot helpOnly authenticating the data helps
copy2015 Couchbase Inc lsaquorsaquo
Digital Signatures
Every user or device generates a key-pairEvery revision is signed by the party who created
itTo validate a revisionMake sure the signature is validLook up the authorrsquos public keyCompare signing key with authorrsquos key
copy2015 Couchbase Inc lsaquorsaquo
Key Distribution
Traditional StyleTrusted authority (server) signs key into a
certificateServer distributes certificate
P2P StyleDevice uses raw key or self-signed certificateUsers lsquopairrsquo devices in person
trading keys over a secure channel
Implementing Peer-to-PeerPart 3
Manual 11 Pairing
Pasin Suriyentrakorn
copy2015 Couchbase Inc lsaquorsaquo
PhotoDrop
Receiver ndash Presenting the QR Code and Receiving Photos
Sender ndash Selecting Photos Sender ndash Scanning a QR Code and Sending Photos
copy2015 Couchbase Inc lsaquorsaquo
ImplementationUses a QR code for peer discoveryUses one-time push replication to transfer photosUses digest authenticationGenerates one-time user credentialsSupports multiple platforms (eg iOS and
Android)
copy2015 Couchbase Inc lsaquorsaquo
StoryboardViewController SendViewController
ReceiveViewController
QR Code Scanner
Presents a QR code
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 1 Start a listener
listener = CBLListener(manager CBLManagersharedInstance() port 0)
listenerrequiresAuth = truelet username = secureGenerateKey(NSCharacterSetURLUserAllowedCharacterSet())let password = secureGenerateKey(NSCharacterSetURLPasswordAllowedCharacterSet())listenersetPasswords([username password])
var success = listenerstart(amperror)if (success)
syncUrl = genearteSyncURL(listenerURL username username password password dbName databasename)
startObserveDatabaseChange()
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Observe database changes
func startObserveDatabaseChange() NSNotificationCenterdefaultCenter()addObserverForName(kCBLDatabaseChangeNotification object database queue nil) (notification) -gt Void
in if let changes = notificationuserInfo[changes] as [CBLDatabaseChange] for change in changes
dispatch_async(dispatch_get_main_queue() selfsaveImageFromDocument(changedocumentID) )
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Generate and display a QR code
httpuserpasswordltlistener hostgtltportgtdb
Uses the iOS Core Image filter
copy2015 Couchbase Inc lsaquorsaquo
SendViewControllerStep 1 Scan a QR code
Uses the iOS class AVCaptureSession with the output type AVMetadataObjectTypeQRCode
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Create documents
var docIds [String] = []for asset in sharedAssets
var data = NSData(bytesNoCopy imageBytes length buffered freeWhenDone true)
let doc = databasecreateDocument()let rev = docnewRevision()revsetAttachmentNamed(photo withContentType applicationoctet-stream
content data)let saved = revsave(amperror)
if saved = nil docIdsappend(docdocumentID)
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Replicate documents
replicator = databasecreatePushReplication(url)replicatordocumentIDs = docIds
NSNotificationCenterdefaultCenter()addObserverForName(kCBLReplicationChangeNotification object replicator queue nil) (notification) -gt Void in
if selfreplicatorlastError == nil var totalCount = selfreplicatorchangesCountvar completedCount = selfreplicatorcompletedChangesCountif completedCount gt 0 ampamp completedCount == totalCount
selfstatusLabeltext = Sending Completedrdquo
else selfstatusLabeltext = Sending Abort
replicatorstart()
copy2015 Couchbase Inc lsaquorsaquo
Source Code
httpsgithubcomcouchbaselabsphoto-drop
Demo 2PhotoDrop App
The End mdash Any Questions
copy2015 Couchbase Inc lsaquorsaquoReplicating Documents amp Revisions
doc1
3-a9ff
doc1
2-c31b
B ldquoWhatrsquos new since last we spokerdquoA ldquoI added rev 3-a9ff of doc1rdquoB ldquoThatrsquos new to merdquoA ldquoIrsquoll send it overhelliprdquo
A
B
copy2015 Couchbase Inc lsaquorsaquo
P2P Mesh Topology
copy2015 Couchbase Inc lsaquorsaquo
The Problem With Naiumlve Meshes
O(n2) connections is badReal mesh networks limit connectionsSpanning treesGossip protocols
Implementing Peer-to-PeerPart 1
Allowing Connections
copy2015 Couchbase Inc lsaquorsaquo
Allowing Peer Connections
Link Couchbase Lite Listener component into appStart listenerCongratulations You are now a replication
ldquoserverrdquo
Datastore
CBL API
App
ReplicatorCBL API
App
Datastore
REST API
copy2015 Couchbase Inc lsaquorsaquo
Allowing Peer Connections
listener = CBLListener(manager databasemanager port 55555) listenerreadOnly = true
For SecurityPrevents peers from pushing Docs to you
Or port 0 to allow the OS to choose a random open port
but a fixed port is more optimal for the peerrsquos replicator
Implementing Peer-to-PeerPart 2
Automatic Peer Discovery
copy2015 Couchbase Inc lsaquorsaquo
Automatic Peer Discovery
ldquoWhorsquos running this serviceapp [on this LAN]rdquoAdvertise your own serviceTypeNameAddress + portSmall metadata (timestamphellip)
Browse for same service typeNotified as peers go onoffline
copy2015 Couchbase Inc lsaquorsaquo
Multicast DNS (mDNS) DNS Service Discovery (DNS-SD)
aka Bonjourtrade ZeroConf Avahi Network Service Discovery
RFC 6762 RFC 6763iOS Mac OS X Android (41+) LinuxWindows apps can integrate Applersquos
mDNSResponderdeveloperapplecomlibrarymacdocumentation
NetworkingConceptualNSNetServiceProgGuidedeveloperandroidcomtrainingconnect-devices-
wirelessly
copy2015 Couchbase Inc lsaquorsaquo
Advertising Your Service
listener = CBLListener(manager databasemanager port 55555) listenerreadOnly = true listenersetBonjourName(userNickname type _myapp_tcp)
Note setBonjourName isnrsquot available in CBL on Android yet Instead use NsdServiceInfo directly
Service name might be altered (number appended) to disambiguate it
copy2015 Couchbase Inc lsaquorsaquo
Browsing For Peers (iOS)
browser = NSNetServiceBrowsernew() browserincludesPeerToPeer = true browserdelegate = self browsersearchForServicesOfType(_myapp_tcp inDomain local)
public func netServiceBrowser(sender NSNetServiceBrowser didFindService service NSNetService moreComing Bool) hellip
public func netServiceBrowser(sender NSNetServiceBrowser didRemoveService service NSNetService moreComing Bool) hellip
copy2015 Couchbase Inc lsaquorsaquo
Connecting To A Peer (iOS)
Start async resolve to find servicersquos hostname servicedelegate = self serviceresolveWithTimeout(50)
NSNetService delegate callback public func netServiceDidResolveAddress(service NSNetService) Construct the remote DB URL var components = NSURLComponents() componentsscheme = http Or https if peer uses SSL componentshost = servicehostName componentsport = serviceport componentspath = + remoteDatabaseName let url = componentsURL
Start replication pull = localDBcreatePullReplication(url) pullstart()
copy2015 Couchbase Inc lsaquorsaquo
Using Bonjour To Replicate
Advertise a UUID as part of your service namePublish my dblatestSequence in service
metadataRemember UUID latestSequence of each lsquopairedrsquo
peerWhen peerrsquos latestSequence changes start a
pull replication
DEMO IPeerSync App
Q Whatrsquos Wrong With That DemoA No authentication
copy2015 Couchbase Inc lsaquorsaquo
C
Forging Documents or Revisions
docByA
B
A
B is sending me lsquodocByArsquo hellip but how
do I know it was really created by A
128530
128519
128564
copy2015 Couchbase Inc lsaquorsaquo
P2P Authentication Is A Hard Problem
With no server accountshow do you prove who you are
With no server to trusthow do you know whether data is valid
copy2015 Couchbase Inc lsaquorsaquo
This Is Not A Typical Auth Problem
SSL doesnrsquot helpHTTP authentication (ArArrB or BrArrC) doesnrsquot helpOnly authenticating the data helps
copy2015 Couchbase Inc lsaquorsaquo
Digital Signatures
Every user or device generates a key-pairEvery revision is signed by the party who created
itTo validate a revisionMake sure the signature is validLook up the authorrsquos public keyCompare signing key with authorrsquos key
copy2015 Couchbase Inc lsaquorsaquo
Key Distribution
Traditional StyleTrusted authority (server) signs key into a
certificateServer distributes certificate
P2P StyleDevice uses raw key or self-signed certificateUsers lsquopairrsquo devices in person
trading keys over a secure channel
Implementing Peer-to-PeerPart 3
Manual 11 Pairing
Pasin Suriyentrakorn
copy2015 Couchbase Inc lsaquorsaquo
PhotoDrop
Receiver ndash Presenting the QR Code and Receiving Photos
Sender ndash Selecting Photos Sender ndash Scanning a QR Code and Sending Photos
copy2015 Couchbase Inc lsaquorsaquo
ImplementationUses a QR code for peer discoveryUses one-time push replication to transfer photosUses digest authenticationGenerates one-time user credentialsSupports multiple platforms (eg iOS and
Android)
copy2015 Couchbase Inc lsaquorsaquo
StoryboardViewController SendViewController
ReceiveViewController
QR Code Scanner
Presents a QR code
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 1 Start a listener
listener = CBLListener(manager CBLManagersharedInstance() port 0)
listenerrequiresAuth = truelet username = secureGenerateKey(NSCharacterSetURLUserAllowedCharacterSet())let password = secureGenerateKey(NSCharacterSetURLPasswordAllowedCharacterSet())listenersetPasswords([username password])
var success = listenerstart(amperror)if (success)
syncUrl = genearteSyncURL(listenerURL username username password password dbName databasename)
startObserveDatabaseChange()
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Observe database changes
func startObserveDatabaseChange() NSNotificationCenterdefaultCenter()addObserverForName(kCBLDatabaseChangeNotification object database queue nil) (notification) -gt Void
in if let changes = notificationuserInfo[changes] as [CBLDatabaseChange] for change in changes
dispatch_async(dispatch_get_main_queue() selfsaveImageFromDocument(changedocumentID) )
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Generate and display a QR code
httpuserpasswordltlistener hostgtltportgtdb
Uses the iOS Core Image filter
copy2015 Couchbase Inc lsaquorsaquo
SendViewControllerStep 1 Scan a QR code
Uses the iOS class AVCaptureSession with the output type AVMetadataObjectTypeQRCode
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Create documents
var docIds [String] = []for asset in sharedAssets
var data = NSData(bytesNoCopy imageBytes length buffered freeWhenDone true)
let doc = databasecreateDocument()let rev = docnewRevision()revsetAttachmentNamed(photo withContentType applicationoctet-stream
content data)let saved = revsave(amperror)
if saved = nil docIdsappend(docdocumentID)
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Replicate documents
replicator = databasecreatePushReplication(url)replicatordocumentIDs = docIds
NSNotificationCenterdefaultCenter()addObserverForName(kCBLReplicationChangeNotification object replicator queue nil) (notification) -gt Void in
if selfreplicatorlastError == nil var totalCount = selfreplicatorchangesCountvar completedCount = selfreplicatorcompletedChangesCountif completedCount gt 0 ampamp completedCount == totalCount
selfstatusLabeltext = Sending Completedrdquo
else selfstatusLabeltext = Sending Abort
replicatorstart()
copy2015 Couchbase Inc lsaquorsaquo
Source Code
httpsgithubcomcouchbaselabsphoto-drop
Demo 2PhotoDrop App
The End mdash Any Questions
copy2015 Couchbase Inc lsaquorsaquo
P2P Mesh Topology
copy2015 Couchbase Inc lsaquorsaquo
The Problem With Naiumlve Meshes
O(n2) connections is badReal mesh networks limit connectionsSpanning treesGossip protocols
Implementing Peer-to-PeerPart 1
Allowing Connections
copy2015 Couchbase Inc lsaquorsaquo
Allowing Peer Connections
Link Couchbase Lite Listener component into appStart listenerCongratulations You are now a replication
ldquoserverrdquo
Datastore
CBL API
App
ReplicatorCBL API
App
Datastore
REST API
copy2015 Couchbase Inc lsaquorsaquo
Allowing Peer Connections
listener = CBLListener(manager databasemanager port 55555) listenerreadOnly = true
For SecurityPrevents peers from pushing Docs to you
Or port 0 to allow the OS to choose a random open port
but a fixed port is more optimal for the peerrsquos replicator
Implementing Peer-to-PeerPart 2
Automatic Peer Discovery
copy2015 Couchbase Inc lsaquorsaquo
Automatic Peer Discovery
ldquoWhorsquos running this serviceapp [on this LAN]rdquoAdvertise your own serviceTypeNameAddress + portSmall metadata (timestamphellip)
Browse for same service typeNotified as peers go onoffline
copy2015 Couchbase Inc lsaquorsaquo
Multicast DNS (mDNS) DNS Service Discovery (DNS-SD)
aka Bonjourtrade ZeroConf Avahi Network Service Discovery
RFC 6762 RFC 6763iOS Mac OS X Android (41+) LinuxWindows apps can integrate Applersquos
mDNSResponderdeveloperapplecomlibrarymacdocumentation
NetworkingConceptualNSNetServiceProgGuidedeveloperandroidcomtrainingconnect-devices-
wirelessly
copy2015 Couchbase Inc lsaquorsaquo
Advertising Your Service
listener = CBLListener(manager databasemanager port 55555) listenerreadOnly = true listenersetBonjourName(userNickname type _myapp_tcp)
Note setBonjourName isnrsquot available in CBL on Android yet Instead use NsdServiceInfo directly
Service name might be altered (number appended) to disambiguate it
copy2015 Couchbase Inc lsaquorsaquo
Browsing For Peers (iOS)
browser = NSNetServiceBrowsernew() browserincludesPeerToPeer = true browserdelegate = self browsersearchForServicesOfType(_myapp_tcp inDomain local)
public func netServiceBrowser(sender NSNetServiceBrowser didFindService service NSNetService moreComing Bool) hellip
public func netServiceBrowser(sender NSNetServiceBrowser didRemoveService service NSNetService moreComing Bool) hellip
copy2015 Couchbase Inc lsaquorsaquo
Connecting To A Peer (iOS)
Start async resolve to find servicersquos hostname servicedelegate = self serviceresolveWithTimeout(50)
NSNetService delegate callback public func netServiceDidResolveAddress(service NSNetService) Construct the remote DB URL var components = NSURLComponents() componentsscheme = http Or https if peer uses SSL componentshost = servicehostName componentsport = serviceport componentspath = + remoteDatabaseName let url = componentsURL
Start replication pull = localDBcreatePullReplication(url) pullstart()
copy2015 Couchbase Inc lsaquorsaquo
Using Bonjour To Replicate
Advertise a UUID as part of your service namePublish my dblatestSequence in service
metadataRemember UUID latestSequence of each lsquopairedrsquo
peerWhen peerrsquos latestSequence changes start a
pull replication
DEMO IPeerSync App
Q Whatrsquos Wrong With That DemoA No authentication
copy2015 Couchbase Inc lsaquorsaquo
C
Forging Documents or Revisions
docByA
B
A
B is sending me lsquodocByArsquo hellip but how
do I know it was really created by A
128530
128519
128564
copy2015 Couchbase Inc lsaquorsaquo
P2P Authentication Is A Hard Problem
With no server accountshow do you prove who you are
With no server to trusthow do you know whether data is valid
copy2015 Couchbase Inc lsaquorsaquo
This Is Not A Typical Auth Problem
SSL doesnrsquot helpHTTP authentication (ArArrB or BrArrC) doesnrsquot helpOnly authenticating the data helps
copy2015 Couchbase Inc lsaquorsaquo
Digital Signatures
Every user or device generates a key-pairEvery revision is signed by the party who created
itTo validate a revisionMake sure the signature is validLook up the authorrsquos public keyCompare signing key with authorrsquos key
copy2015 Couchbase Inc lsaquorsaquo
Key Distribution
Traditional StyleTrusted authority (server) signs key into a
certificateServer distributes certificate
P2P StyleDevice uses raw key or self-signed certificateUsers lsquopairrsquo devices in person
trading keys over a secure channel
Implementing Peer-to-PeerPart 3
Manual 11 Pairing
Pasin Suriyentrakorn
copy2015 Couchbase Inc lsaquorsaquo
PhotoDrop
Receiver ndash Presenting the QR Code and Receiving Photos
Sender ndash Selecting Photos Sender ndash Scanning a QR Code and Sending Photos
copy2015 Couchbase Inc lsaquorsaquo
ImplementationUses a QR code for peer discoveryUses one-time push replication to transfer photosUses digest authenticationGenerates one-time user credentialsSupports multiple platforms (eg iOS and
Android)
copy2015 Couchbase Inc lsaquorsaquo
StoryboardViewController SendViewController
ReceiveViewController
QR Code Scanner
Presents a QR code
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 1 Start a listener
listener = CBLListener(manager CBLManagersharedInstance() port 0)
listenerrequiresAuth = truelet username = secureGenerateKey(NSCharacterSetURLUserAllowedCharacterSet())let password = secureGenerateKey(NSCharacterSetURLPasswordAllowedCharacterSet())listenersetPasswords([username password])
var success = listenerstart(amperror)if (success)
syncUrl = genearteSyncURL(listenerURL username username password password dbName databasename)
startObserveDatabaseChange()
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Observe database changes
func startObserveDatabaseChange() NSNotificationCenterdefaultCenter()addObserverForName(kCBLDatabaseChangeNotification object database queue nil) (notification) -gt Void
in if let changes = notificationuserInfo[changes] as [CBLDatabaseChange] for change in changes
dispatch_async(dispatch_get_main_queue() selfsaveImageFromDocument(changedocumentID) )
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Generate and display a QR code
httpuserpasswordltlistener hostgtltportgtdb
Uses the iOS Core Image filter
copy2015 Couchbase Inc lsaquorsaquo
SendViewControllerStep 1 Scan a QR code
Uses the iOS class AVCaptureSession with the output type AVMetadataObjectTypeQRCode
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Create documents
var docIds [String] = []for asset in sharedAssets
var data = NSData(bytesNoCopy imageBytes length buffered freeWhenDone true)
let doc = databasecreateDocument()let rev = docnewRevision()revsetAttachmentNamed(photo withContentType applicationoctet-stream
content data)let saved = revsave(amperror)
if saved = nil docIdsappend(docdocumentID)
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Replicate documents
replicator = databasecreatePushReplication(url)replicatordocumentIDs = docIds
NSNotificationCenterdefaultCenter()addObserverForName(kCBLReplicationChangeNotification object replicator queue nil) (notification) -gt Void in
if selfreplicatorlastError == nil var totalCount = selfreplicatorchangesCountvar completedCount = selfreplicatorcompletedChangesCountif completedCount gt 0 ampamp completedCount == totalCount
selfstatusLabeltext = Sending Completedrdquo
else selfstatusLabeltext = Sending Abort
replicatorstart()
copy2015 Couchbase Inc lsaquorsaquo
Source Code
httpsgithubcomcouchbaselabsphoto-drop
Demo 2PhotoDrop App
The End mdash Any Questions
copy2015 Couchbase Inc lsaquorsaquo
The Problem With Naiumlve Meshes
O(n2) connections is badReal mesh networks limit connectionsSpanning treesGossip protocols
Implementing Peer-to-PeerPart 1
Allowing Connections
copy2015 Couchbase Inc lsaquorsaquo
Allowing Peer Connections
Link Couchbase Lite Listener component into appStart listenerCongratulations You are now a replication
ldquoserverrdquo
Datastore
CBL API
App
ReplicatorCBL API
App
Datastore
REST API
copy2015 Couchbase Inc lsaquorsaquo
Allowing Peer Connections
listener = CBLListener(manager databasemanager port 55555) listenerreadOnly = true
For SecurityPrevents peers from pushing Docs to you
Or port 0 to allow the OS to choose a random open port
but a fixed port is more optimal for the peerrsquos replicator
Implementing Peer-to-PeerPart 2
Automatic Peer Discovery
copy2015 Couchbase Inc lsaquorsaquo
Automatic Peer Discovery
ldquoWhorsquos running this serviceapp [on this LAN]rdquoAdvertise your own serviceTypeNameAddress + portSmall metadata (timestamphellip)
Browse for same service typeNotified as peers go onoffline
copy2015 Couchbase Inc lsaquorsaquo
Multicast DNS (mDNS) DNS Service Discovery (DNS-SD)
aka Bonjourtrade ZeroConf Avahi Network Service Discovery
RFC 6762 RFC 6763iOS Mac OS X Android (41+) LinuxWindows apps can integrate Applersquos
mDNSResponderdeveloperapplecomlibrarymacdocumentation
NetworkingConceptualNSNetServiceProgGuidedeveloperandroidcomtrainingconnect-devices-
wirelessly
copy2015 Couchbase Inc lsaquorsaquo
Advertising Your Service
listener = CBLListener(manager databasemanager port 55555) listenerreadOnly = true listenersetBonjourName(userNickname type _myapp_tcp)
Note setBonjourName isnrsquot available in CBL on Android yet Instead use NsdServiceInfo directly
Service name might be altered (number appended) to disambiguate it
copy2015 Couchbase Inc lsaquorsaquo
Browsing For Peers (iOS)
browser = NSNetServiceBrowsernew() browserincludesPeerToPeer = true browserdelegate = self browsersearchForServicesOfType(_myapp_tcp inDomain local)
public func netServiceBrowser(sender NSNetServiceBrowser didFindService service NSNetService moreComing Bool) hellip
public func netServiceBrowser(sender NSNetServiceBrowser didRemoveService service NSNetService moreComing Bool) hellip
copy2015 Couchbase Inc lsaquorsaquo
Connecting To A Peer (iOS)
Start async resolve to find servicersquos hostname servicedelegate = self serviceresolveWithTimeout(50)
NSNetService delegate callback public func netServiceDidResolveAddress(service NSNetService) Construct the remote DB URL var components = NSURLComponents() componentsscheme = http Or https if peer uses SSL componentshost = servicehostName componentsport = serviceport componentspath = + remoteDatabaseName let url = componentsURL
Start replication pull = localDBcreatePullReplication(url) pullstart()
copy2015 Couchbase Inc lsaquorsaquo
Using Bonjour To Replicate
Advertise a UUID as part of your service namePublish my dblatestSequence in service
metadataRemember UUID latestSequence of each lsquopairedrsquo
peerWhen peerrsquos latestSequence changes start a
pull replication
DEMO IPeerSync App
Q Whatrsquos Wrong With That DemoA No authentication
copy2015 Couchbase Inc lsaquorsaquo
C
Forging Documents or Revisions
docByA
B
A
B is sending me lsquodocByArsquo hellip but how
do I know it was really created by A
128530
128519
128564
copy2015 Couchbase Inc lsaquorsaquo
P2P Authentication Is A Hard Problem
With no server accountshow do you prove who you are
With no server to trusthow do you know whether data is valid
copy2015 Couchbase Inc lsaquorsaquo
This Is Not A Typical Auth Problem
SSL doesnrsquot helpHTTP authentication (ArArrB or BrArrC) doesnrsquot helpOnly authenticating the data helps
copy2015 Couchbase Inc lsaquorsaquo
Digital Signatures
Every user or device generates a key-pairEvery revision is signed by the party who created
itTo validate a revisionMake sure the signature is validLook up the authorrsquos public keyCompare signing key with authorrsquos key
copy2015 Couchbase Inc lsaquorsaquo
Key Distribution
Traditional StyleTrusted authority (server) signs key into a
certificateServer distributes certificate
P2P StyleDevice uses raw key or self-signed certificateUsers lsquopairrsquo devices in person
trading keys over a secure channel
Implementing Peer-to-PeerPart 3
Manual 11 Pairing
Pasin Suriyentrakorn
copy2015 Couchbase Inc lsaquorsaquo
PhotoDrop
Receiver ndash Presenting the QR Code and Receiving Photos
Sender ndash Selecting Photos Sender ndash Scanning a QR Code and Sending Photos
copy2015 Couchbase Inc lsaquorsaquo
ImplementationUses a QR code for peer discoveryUses one-time push replication to transfer photosUses digest authenticationGenerates one-time user credentialsSupports multiple platforms (eg iOS and
Android)
copy2015 Couchbase Inc lsaquorsaquo
StoryboardViewController SendViewController
ReceiveViewController
QR Code Scanner
Presents a QR code
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 1 Start a listener
listener = CBLListener(manager CBLManagersharedInstance() port 0)
listenerrequiresAuth = truelet username = secureGenerateKey(NSCharacterSetURLUserAllowedCharacterSet())let password = secureGenerateKey(NSCharacterSetURLPasswordAllowedCharacterSet())listenersetPasswords([username password])
var success = listenerstart(amperror)if (success)
syncUrl = genearteSyncURL(listenerURL username username password password dbName databasename)
startObserveDatabaseChange()
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Observe database changes
func startObserveDatabaseChange() NSNotificationCenterdefaultCenter()addObserverForName(kCBLDatabaseChangeNotification object database queue nil) (notification) -gt Void
in if let changes = notificationuserInfo[changes] as [CBLDatabaseChange] for change in changes
dispatch_async(dispatch_get_main_queue() selfsaveImageFromDocument(changedocumentID) )
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Generate and display a QR code
httpuserpasswordltlistener hostgtltportgtdb
Uses the iOS Core Image filter
copy2015 Couchbase Inc lsaquorsaquo
SendViewControllerStep 1 Scan a QR code
Uses the iOS class AVCaptureSession with the output type AVMetadataObjectTypeQRCode
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Create documents
var docIds [String] = []for asset in sharedAssets
var data = NSData(bytesNoCopy imageBytes length buffered freeWhenDone true)
let doc = databasecreateDocument()let rev = docnewRevision()revsetAttachmentNamed(photo withContentType applicationoctet-stream
content data)let saved = revsave(amperror)
if saved = nil docIdsappend(docdocumentID)
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Replicate documents
replicator = databasecreatePushReplication(url)replicatordocumentIDs = docIds
NSNotificationCenterdefaultCenter()addObserverForName(kCBLReplicationChangeNotification object replicator queue nil) (notification) -gt Void in
if selfreplicatorlastError == nil var totalCount = selfreplicatorchangesCountvar completedCount = selfreplicatorcompletedChangesCountif completedCount gt 0 ampamp completedCount == totalCount
selfstatusLabeltext = Sending Completedrdquo
else selfstatusLabeltext = Sending Abort
replicatorstart()
copy2015 Couchbase Inc lsaquorsaquo
Source Code
httpsgithubcomcouchbaselabsphoto-drop
Demo 2PhotoDrop App
The End mdash Any Questions
Implementing Peer-to-PeerPart 1
Allowing Connections
copy2015 Couchbase Inc lsaquorsaquo
Allowing Peer Connections
Link Couchbase Lite Listener component into appStart listenerCongratulations You are now a replication
ldquoserverrdquo
Datastore
CBL API
App
ReplicatorCBL API
App
Datastore
REST API
copy2015 Couchbase Inc lsaquorsaquo
Allowing Peer Connections
listener = CBLListener(manager databasemanager port 55555) listenerreadOnly = true
For SecurityPrevents peers from pushing Docs to you
Or port 0 to allow the OS to choose a random open port
but a fixed port is more optimal for the peerrsquos replicator
Implementing Peer-to-PeerPart 2
Automatic Peer Discovery
copy2015 Couchbase Inc lsaquorsaquo
Automatic Peer Discovery
ldquoWhorsquos running this serviceapp [on this LAN]rdquoAdvertise your own serviceTypeNameAddress + portSmall metadata (timestamphellip)
Browse for same service typeNotified as peers go onoffline
copy2015 Couchbase Inc lsaquorsaquo
Multicast DNS (mDNS) DNS Service Discovery (DNS-SD)
aka Bonjourtrade ZeroConf Avahi Network Service Discovery
RFC 6762 RFC 6763iOS Mac OS X Android (41+) LinuxWindows apps can integrate Applersquos
mDNSResponderdeveloperapplecomlibrarymacdocumentation
NetworkingConceptualNSNetServiceProgGuidedeveloperandroidcomtrainingconnect-devices-
wirelessly
copy2015 Couchbase Inc lsaquorsaquo
Advertising Your Service
listener = CBLListener(manager databasemanager port 55555) listenerreadOnly = true listenersetBonjourName(userNickname type _myapp_tcp)
Note setBonjourName isnrsquot available in CBL on Android yet Instead use NsdServiceInfo directly
Service name might be altered (number appended) to disambiguate it
copy2015 Couchbase Inc lsaquorsaquo
Browsing For Peers (iOS)
browser = NSNetServiceBrowsernew() browserincludesPeerToPeer = true browserdelegate = self browsersearchForServicesOfType(_myapp_tcp inDomain local)
public func netServiceBrowser(sender NSNetServiceBrowser didFindService service NSNetService moreComing Bool) hellip
public func netServiceBrowser(sender NSNetServiceBrowser didRemoveService service NSNetService moreComing Bool) hellip
copy2015 Couchbase Inc lsaquorsaquo
Connecting To A Peer (iOS)
Start async resolve to find servicersquos hostname servicedelegate = self serviceresolveWithTimeout(50)
NSNetService delegate callback public func netServiceDidResolveAddress(service NSNetService) Construct the remote DB URL var components = NSURLComponents() componentsscheme = http Or https if peer uses SSL componentshost = servicehostName componentsport = serviceport componentspath = + remoteDatabaseName let url = componentsURL
Start replication pull = localDBcreatePullReplication(url) pullstart()
copy2015 Couchbase Inc lsaquorsaquo
Using Bonjour To Replicate
Advertise a UUID as part of your service namePublish my dblatestSequence in service
metadataRemember UUID latestSequence of each lsquopairedrsquo
peerWhen peerrsquos latestSequence changes start a
pull replication
DEMO IPeerSync App
Q Whatrsquos Wrong With That DemoA No authentication
copy2015 Couchbase Inc lsaquorsaquo
C
Forging Documents or Revisions
docByA
B
A
B is sending me lsquodocByArsquo hellip but how
do I know it was really created by A
128530
128519
128564
copy2015 Couchbase Inc lsaquorsaquo
P2P Authentication Is A Hard Problem
With no server accountshow do you prove who you are
With no server to trusthow do you know whether data is valid
copy2015 Couchbase Inc lsaquorsaquo
This Is Not A Typical Auth Problem
SSL doesnrsquot helpHTTP authentication (ArArrB or BrArrC) doesnrsquot helpOnly authenticating the data helps
copy2015 Couchbase Inc lsaquorsaquo
Digital Signatures
Every user or device generates a key-pairEvery revision is signed by the party who created
itTo validate a revisionMake sure the signature is validLook up the authorrsquos public keyCompare signing key with authorrsquos key
copy2015 Couchbase Inc lsaquorsaquo
Key Distribution
Traditional StyleTrusted authority (server) signs key into a
certificateServer distributes certificate
P2P StyleDevice uses raw key or self-signed certificateUsers lsquopairrsquo devices in person
trading keys over a secure channel
Implementing Peer-to-PeerPart 3
Manual 11 Pairing
Pasin Suriyentrakorn
copy2015 Couchbase Inc lsaquorsaquo
PhotoDrop
Receiver ndash Presenting the QR Code and Receiving Photos
Sender ndash Selecting Photos Sender ndash Scanning a QR Code and Sending Photos
copy2015 Couchbase Inc lsaquorsaquo
ImplementationUses a QR code for peer discoveryUses one-time push replication to transfer photosUses digest authenticationGenerates one-time user credentialsSupports multiple platforms (eg iOS and
Android)
copy2015 Couchbase Inc lsaquorsaquo
StoryboardViewController SendViewController
ReceiveViewController
QR Code Scanner
Presents a QR code
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 1 Start a listener
listener = CBLListener(manager CBLManagersharedInstance() port 0)
listenerrequiresAuth = truelet username = secureGenerateKey(NSCharacterSetURLUserAllowedCharacterSet())let password = secureGenerateKey(NSCharacterSetURLPasswordAllowedCharacterSet())listenersetPasswords([username password])
var success = listenerstart(amperror)if (success)
syncUrl = genearteSyncURL(listenerURL username username password password dbName databasename)
startObserveDatabaseChange()
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Observe database changes
func startObserveDatabaseChange() NSNotificationCenterdefaultCenter()addObserverForName(kCBLDatabaseChangeNotification object database queue nil) (notification) -gt Void
in if let changes = notificationuserInfo[changes] as [CBLDatabaseChange] for change in changes
dispatch_async(dispatch_get_main_queue() selfsaveImageFromDocument(changedocumentID) )
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Generate and display a QR code
httpuserpasswordltlistener hostgtltportgtdb
Uses the iOS Core Image filter
copy2015 Couchbase Inc lsaquorsaquo
SendViewControllerStep 1 Scan a QR code
Uses the iOS class AVCaptureSession with the output type AVMetadataObjectTypeQRCode
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Create documents
var docIds [String] = []for asset in sharedAssets
var data = NSData(bytesNoCopy imageBytes length buffered freeWhenDone true)
let doc = databasecreateDocument()let rev = docnewRevision()revsetAttachmentNamed(photo withContentType applicationoctet-stream
content data)let saved = revsave(amperror)
if saved = nil docIdsappend(docdocumentID)
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Replicate documents
replicator = databasecreatePushReplication(url)replicatordocumentIDs = docIds
NSNotificationCenterdefaultCenter()addObserverForName(kCBLReplicationChangeNotification object replicator queue nil) (notification) -gt Void in
if selfreplicatorlastError == nil var totalCount = selfreplicatorchangesCountvar completedCount = selfreplicatorcompletedChangesCountif completedCount gt 0 ampamp completedCount == totalCount
selfstatusLabeltext = Sending Completedrdquo
else selfstatusLabeltext = Sending Abort
replicatorstart()
copy2015 Couchbase Inc lsaquorsaquo
Source Code
httpsgithubcomcouchbaselabsphoto-drop
Demo 2PhotoDrop App
The End mdash Any Questions
copy2015 Couchbase Inc lsaquorsaquo
Allowing Peer Connections
Link Couchbase Lite Listener component into appStart listenerCongratulations You are now a replication
ldquoserverrdquo
Datastore
CBL API
App
ReplicatorCBL API
App
Datastore
REST API
copy2015 Couchbase Inc lsaquorsaquo
Allowing Peer Connections
listener = CBLListener(manager databasemanager port 55555) listenerreadOnly = true
For SecurityPrevents peers from pushing Docs to you
Or port 0 to allow the OS to choose a random open port
but a fixed port is more optimal for the peerrsquos replicator
Implementing Peer-to-PeerPart 2
Automatic Peer Discovery
copy2015 Couchbase Inc lsaquorsaquo
Automatic Peer Discovery
ldquoWhorsquos running this serviceapp [on this LAN]rdquoAdvertise your own serviceTypeNameAddress + portSmall metadata (timestamphellip)
Browse for same service typeNotified as peers go onoffline
copy2015 Couchbase Inc lsaquorsaquo
Multicast DNS (mDNS) DNS Service Discovery (DNS-SD)
aka Bonjourtrade ZeroConf Avahi Network Service Discovery
RFC 6762 RFC 6763iOS Mac OS X Android (41+) LinuxWindows apps can integrate Applersquos
mDNSResponderdeveloperapplecomlibrarymacdocumentation
NetworkingConceptualNSNetServiceProgGuidedeveloperandroidcomtrainingconnect-devices-
wirelessly
copy2015 Couchbase Inc lsaquorsaquo
Advertising Your Service
listener = CBLListener(manager databasemanager port 55555) listenerreadOnly = true listenersetBonjourName(userNickname type _myapp_tcp)
Note setBonjourName isnrsquot available in CBL on Android yet Instead use NsdServiceInfo directly
Service name might be altered (number appended) to disambiguate it
copy2015 Couchbase Inc lsaquorsaquo
Browsing For Peers (iOS)
browser = NSNetServiceBrowsernew() browserincludesPeerToPeer = true browserdelegate = self browsersearchForServicesOfType(_myapp_tcp inDomain local)
public func netServiceBrowser(sender NSNetServiceBrowser didFindService service NSNetService moreComing Bool) hellip
public func netServiceBrowser(sender NSNetServiceBrowser didRemoveService service NSNetService moreComing Bool) hellip
copy2015 Couchbase Inc lsaquorsaquo
Connecting To A Peer (iOS)
Start async resolve to find servicersquos hostname servicedelegate = self serviceresolveWithTimeout(50)
NSNetService delegate callback public func netServiceDidResolveAddress(service NSNetService) Construct the remote DB URL var components = NSURLComponents() componentsscheme = http Or https if peer uses SSL componentshost = servicehostName componentsport = serviceport componentspath = + remoteDatabaseName let url = componentsURL
Start replication pull = localDBcreatePullReplication(url) pullstart()
copy2015 Couchbase Inc lsaquorsaquo
Using Bonjour To Replicate
Advertise a UUID as part of your service namePublish my dblatestSequence in service
metadataRemember UUID latestSequence of each lsquopairedrsquo
peerWhen peerrsquos latestSequence changes start a
pull replication
DEMO IPeerSync App
Q Whatrsquos Wrong With That DemoA No authentication
copy2015 Couchbase Inc lsaquorsaquo
C
Forging Documents or Revisions
docByA
B
A
B is sending me lsquodocByArsquo hellip but how
do I know it was really created by A
128530
128519
128564
copy2015 Couchbase Inc lsaquorsaquo
P2P Authentication Is A Hard Problem
With no server accountshow do you prove who you are
With no server to trusthow do you know whether data is valid
copy2015 Couchbase Inc lsaquorsaquo
This Is Not A Typical Auth Problem
SSL doesnrsquot helpHTTP authentication (ArArrB or BrArrC) doesnrsquot helpOnly authenticating the data helps
copy2015 Couchbase Inc lsaquorsaquo
Digital Signatures
Every user or device generates a key-pairEvery revision is signed by the party who created
itTo validate a revisionMake sure the signature is validLook up the authorrsquos public keyCompare signing key with authorrsquos key
copy2015 Couchbase Inc lsaquorsaquo
Key Distribution
Traditional StyleTrusted authority (server) signs key into a
certificateServer distributes certificate
P2P StyleDevice uses raw key or self-signed certificateUsers lsquopairrsquo devices in person
trading keys over a secure channel
Implementing Peer-to-PeerPart 3
Manual 11 Pairing
Pasin Suriyentrakorn
copy2015 Couchbase Inc lsaquorsaquo
PhotoDrop
Receiver ndash Presenting the QR Code and Receiving Photos
Sender ndash Selecting Photos Sender ndash Scanning a QR Code and Sending Photos
copy2015 Couchbase Inc lsaquorsaquo
ImplementationUses a QR code for peer discoveryUses one-time push replication to transfer photosUses digest authenticationGenerates one-time user credentialsSupports multiple platforms (eg iOS and
Android)
copy2015 Couchbase Inc lsaquorsaquo
StoryboardViewController SendViewController
ReceiveViewController
QR Code Scanner
Presents a QR code
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 1 Start a listener
listener = CBLListener(manager CBLManagersharedInstance() port 0)
listenerrequiresAuth = truelet username = secureGenerateKey(NSCharacterSetURLUserAllowedCharacterSet())let password = secureGenerateKey(NSCharacterSetURLPasswordAllowedCharacterSet())listenersetPasswords([username password])
var success = listenerstart(amperror)if (success)
syncUrl = genearteSyncURL(listenerURL username username password password dbName databasename)
startObserveDatabaseChange()
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Observe database changes
func startObserveDatabaseChange() NSNotificationCenterdefaultCenter()addObserverForName(kCBLDatabaseChangeNotification object database queue nil) (notification) -gt Void
in if let changes = notificationuserInfo[changes] as [CBLDatabaseChange] for change in changes
dispatch_async(dispatch_get_main_queue() selfsaveImageFromDocument(changedocumentID) )
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Generate and display a QR code
httpuserpasswordltlistener hostgtltportgtdb
Uses the iOS Core Image filter
copy2015 Couchbase Inc lsaquorsaquo
SendViewControllerStep 1 Scan a QR code
Uses the iOS class AVCaptureSession with the output type AVMetadataObjectTypeQRCode
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Create documents
var docIds [String] = []for asset in sharedAssets
var data = NSData(bytesNoCopy imageBytes length buffered freeWhenDone true)
let doc = databasecreateDocument()let rev = docnewRevision()revsetAttachmentNamed(photo withContentType applicationoctet-stream
content data)let saved = revsave(amperror)
if saved = nil docIdsappend(docdocumentID)
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Replicate documents
replicator = databasecreatePushReplication(url)replicatordocumentIDs = docIds
NSNotificationCenterdefaultCenter()addObserverForName(kCBLReplicationChangeNotification object replicator queue nil) (notification) -gt Void in
if selfreplicatorlastError == nil var totalCount = selfreplicatorchangesCountvar completedCount = selfreplicatorcompletedChangesCountif completedCount gt 0 ampamp completedCount == totalCount
selfstatusLabeltext = Sending Completedrdquo
else selfstatusLabeltext = Sending Abort
replicatorstart()
copy2015 Couchbase Inc lsaquorsaquo
Source Code
httpsgithubcomcouchbaselabsphoto-drop
Demo 2PhotoDrop App
The End mdash Any Questions
copy2015 Couchbase Inc lsaquorsaquo
Allowing Peer Connections
listener = CBLListener(manager databasemanager port 55555) listenerreadOnly = true
For SecurityPrevents peers from pushing Docs to you
Or port 0 to allow the OS to choose a random open port
but a fixed port is more optimal for the peerrsquos replicator
Implementing Peer-to-PeerPart 2
Automatic Peer Discovery
copy2015 Couchbase Inc lsaquorsaquo
Automatic Peer Discovery
ldquoWhorsquos running this serviceapp [on this LAN]rdquoAdvertise your own serviceTypeNameAddress + portSmall metadata (timestamphellip)
Browse for same service typeNotified as peers go onoffline
copy2015 Couchbase Inc lsaquorsaquo
Multicast DNS (mDNS) DNS Service Discovery (DNS-SD)
aka Bonjourtrade ZeroConf Avahi Network Service Discovery
RFC 6762 RFC 6763iOS Mac OS X Android (41+) LinuxWindows apps can integrate Applersquos
mDNSResponderdeveloperapplecomlibrarymacdocumentation
NetworkingConceptualNSNetServiceProgGuidedeveloperandroidcomtrainingconnect-devices-
wirelessly
copy2015 Couchbase Inc lsaquorsaquo
Advertising Your Service
listener = CBLListener(manager databasemanager port 55555) listenerreadOnly = true listenersetBonjourName(userNickname type _myapp_tcp)
Note setBonjourName isnrsquot available in CBL on Android yet Instead use NsdServiceInfo directly
Service name might be altered (number appended) to disambiguate it
copy2015 Couchbase Inc lsaquorsaquo
Browsing For Peers (iOS)
browser = NSNetServiceBrowsernew() browserincludesPeerToPeer = true browserdelegate = self browsersearchForServicesOfType(_myapp_tcp inDomain local)
public func netServiceBrowser(sender NSNetServiceBrowser didFindService service NSNetService moreComing Bool) hellip
public func netServiceBrowser(sender NSNetServiceBrowser didRemoveService service NSNetService moreComing Bool) hellip
copy2015 Couchbase Inc lsaquorsaquo
Connecting To A Peer (iOS)
Start async resolve to find servicersquos hostname servicedelegate = self serviceresolveWithTimeout(50)
NSNetService delegate callback public func netServiceDidResolveAddress(service NSNetService) Construct the remote DB URL var components = NSURLComponents() componentsscheme = http Or https if peer uses SSL componentshost = servicehostName componentsport = serviceport componentspath = + remoteDatabaseName let url = componentsURL
Start replication pull = localDBcreatePullReplication(url) pullstart()
copy2015 Couchbase Inc lsaquorsaquo
Using Bonjour To Replicate
Advertise a UUID as part of your service namePublish my dblatestSequence in service
metadataRemember UUID latestSequence of each lsquopairedrsquo
peerWhen peerrsquos latestSequence changes start a
pull replication
DEMO IPeerSync App
Q Whatrsquos Wrong With That DemoA No authentication
copy2015 Couchbase Inc lsaquorsaquo
C
Forging Documents or Revisions
docByA
B
A
B is sending me lsquodocByArsquo hellip but how
do I know it was really created by A
128530
128519
128564
copy2015 Couchbase Inc lsaquorsaquo
P2P Authentication Is A Hard Problem
With no server accountshow do you prove who you are
With no server to trusthow do you know whether data is valid
copy2015 Couchbase Inc lsaquorsaquo
This Is Not A Typical Auth Problem
SSL doesnrsquot helpHTTP authentication (ArArrB or BrArrC) doesnrsquot helpOnly authenticating the data helps
copy2015 Couchbase Inc lsaquorsaquo
Digital Signatures
Every user or device generates a key-pairEvery revision is signed by the party who created
itTo validate a revisionMake sure the signature is validLook up the authorrsquos public keyCompare signing key with authorrsquos key
copy2015 Couchbase Inc lsaquorsaquo
Key Distribution
Traditional StyleTrusted authority (server) signs key into a
certificateServer distributes certificate
P2P StyleDevice uses raw key or self-signed certificateUsers lsquopairrsquo devices in person
trading keys over a secure channel
Implementing Peer-to-PeerPart 3
Manual 11 Pairing
Pasin Suriyentrakorn
copy2015 Couchbase Inc lsaquorsaquo
PhotoDrop
Receiver ndash Presenting the QR Code and Receiving Photos
Sender ndash Selecting Photos Sender ndash Scanning a QR Code and Sending Photos
copy2015 Couchbase Inc lsaquorsaquo
ImplementationUses a QR code for peer discoveryUses one-time push replication to transfer photosUses digest authenticationGenerates one-time user credentialsSupports multiple platforms (eg iOS and
Android)
copy2015 Couchbase Inc lsaquorsaquo
StoryboardViewController SendViewController
ReceiveViewController
QR Code Scanner
Presents a QR code
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 1 Start a listener
listener = CBLListener(manager CBLManagersharedInstance() port 0)
listenerrequiresAuth = truelet username = secureGenerateKey(NSCharacterSetURLUserAllowedCharacterSet())let password = secureGenerateKey(NSCharacterSetURLPasswordAllowedCharacterSet())listenersetPasswords([username password])
var success = listenerstart(amperror)if (success)
syncUrl = genearteSyncURL(listenerURL username username password password dbName databasename)
startObserveDatabaseChange()
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Observe database changes
func startObserveDatabaseChange() NSNotificationCenterdefaultCenter()addObserverForName(kCBLDatabaseChangeNotification object database queue nil) (notification) -gt Void
in if let changes = notificationuserInfo[changes] as [CBLDatabaseChange] for change in changes
dispatch_async(dispatch_get_main_queue() selfsaveImageFromDocument(changedocumentID) )
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Generate and display a QR code
httpuserpasswordltlistener hostgtltportgtdb
Uses the iOS Core Image filter
copy2015 Couchbase Inc lsaquorsaquo
SendViewControllerStep 1 Scan a QR code
Uses the iOS class AVCaptureSession with the output type AVMetadataObjectTypeQRCode
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Create documents
var docIds [String] = []for asset in sharedAssets
var data = NSData(bytesNoCopy imageBytes length buffered freeWhenDone true)
let doc = databasecreateDocument()let rev = docnewRevision()revsetAttachmentNamed(photo withContentType applicationoctet-stream
content data)let saved = revsave(amperror)
if saved = nil docIdsappend(docdocumentID)
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Replicate documents
replicator = databasecreatePushReplication(url)replicatordocumentIDs = docIds
NSNotificationCenterdefaultCenter()addObserverForName(kCBLReplicationChangeNotification object replicator queue nil) (notification) -gt Void in
if selfreplicatorlastError == nil var totalCount = selfreplicatorchangesCountvar completedCount = selfreplicatorcompletedChangesCountif completedCount gt 0 ampamp completedCount == totalCount
selfstatusLabeltext = Sending Completedrdquo
else selfstatusLabeltext = Sending Abort
replicatorstart()
copy2015 Couchbase Inc lsaquorsaquo
Source Code
httpsgithubcomcouchbaselabsphoto-drop
Demo 2PhotoDrop App
The End mdash Any Questions
Implementing Peer-to-PeerPart 2
Automatic Peer Discovery
copy2015 Couchbase Inc lsaquorsaquo
Automatic Peer Discovery
ldquoWhorsquos running this serviceapp [on this LAN]rdquoAdvertise your own serviceTypeNameAddress + portSmall metadata (timestamphellip)
Browse for same service typeNotified as peers go onoffline
copy2015 Couchbase Inc lsaquorsaquo
Multicast DNS (mDNS) DNS Service Discovery (DNS-SD)
aka Bonjourtrade ZeroConf Avahi Network Service Discovery
RFC 6762 RFC 6763iOS Mac OS X Android (41+) LinuxWindows apps can integrate Applersquos
mDNSResponderdeveloperapplecomlibrarymacdocumentation
NetworkingConceptualNSNetServiceProgGuidedeveloperandroidcomtrainingconnect-devices-
wirelessly
copy2015 Couchbase Inc lsaquorsaquo
Advertising Your Service
listener = CBLListener(manager databasemanager port 55555) listenerreadOnly = true listenersetBonjourName(userNickname type _myapp_tcp)
Note setBonjourName isnrsquot available in CBL on Android yet Instead use NsdServiceInfo directly
Service name might be altered (number appended) to disambiguate it
copy2015 Couchbase Inc lsaquorsaquo
Browsing For Peers (iOS)
browser = NSNetServiceBrowsernew() browserincludesPeerToPeer = true browserdelegate = self browsersearchForServicesOfType(_myapp_tcp inDomain local)
public func netServiceBrowser(sender NSNetServiceBrowser didFindService service NSNetService moreComing Bool) hellip
public func netServiceBrowser(sender NSNetServiceBrowser didRemoveService service NSNetService moreComing Bool) hellip
copy2015 Couchbase Inc lsaquorsaquo
Connecting To A Peer (iOS)
Start async resolve to find servicersquos hostname servicedelegate = self serviceresolveWithTimeout(50)
NSNetService delegate callback public func netServiceDidResolveAddress(service NSNetService) Construct the remote DB URL var components = NSURLComponents() componentsscheme = http Or https if peer uses SSL componentshost = servicehostName componentsport = serviceport componentspath = + remoteDatabaseName let url = componentsURL
Start replication pull = localDBcreatePullReplication(url) pullstart()
copy2015 Couchbase Inc lsaquorsaquo
Using Bonjour To Replicate
Advertise a UUID as part of your service namePublish my dblatestSequence in service
metadataRemember UUID latestSequence of each lsquopairedrsquo
peerWhen peerrsquos latestSequence changes start a
pull replication
DEMO IPeerSync App
Q Whatrsquos Wrong With That DemoA No authentication
copy2015 Couchbase Inc lsaquorsaquo
C
Forging Documents or Revisions
docByA
B
A
B is sending me lsquodocByArsquo hellip but how
do I know it was really created by A
128530
128519
128564
copy2015 Couchbase Inc lsaquorsaquo
P2P Authentication Is A Hard Problem
With no server accountshow do you prove who you are
With no server to trusthow do you know whether data is valid
copy2015 Couchbase Inc lsaquorsaquo
This Is Not A Typical Auth Problem
SSL doesnrsquot helpHTTP authentication (ArArrB or BrArrC) doesnrsquot helpOnly authenticating the data helps
copy2015 Couchbase Inc lsaquorsaquo
Digital Signatures
Every user or device generates a key-pairEvery revision is signed by the party who created
itTo validate a revisionMake sure the signature is validLook up the authorrsquos public keyCompare signing key with authorrsquos key
copy2015 Couchbase Inc lsaquorsaquo
Key Distribution
Traditional StyleTrusted authority (server) signs key into a
certificateServer distributes certificate
P2P StyleDevice uses raw key or self-signed certificateUsers lsquopairrsquo devices in person
trading keys over a secure channel
Implementing Peer-to-PeerPart 3
Manual 11 Pairing
Pasin Suriyentrakorn
copy2015 Couchbase Inc lsaquorsaquo
PhotoDrop
Receiver ndash Presenting the QR Code and Receiving Photos
Sender ndash Selecting Photos Sender ndash Scanning a QR Code and Sending Photos
copy2015 Couchbase Inc lsaquorsaquo
ImplementationUses a QR code for peer discoveryUses one-time push replication to transfer photosUses digest authenticationGenerates one-time user credentialsSupports multiple platforms (eg iOS and
Android)
copy2015 Couchbase Inc lsaquorsaquo
StoryboardViewController SendViewController
ReceiveViewController
QR Code Scanner
Presents a QR code
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 1 Start a listener
listener = CBLListener(manager CBLManagersharedInstance() port 0)
listenerrequiresAuth = truelet username = secureGenerateKey(NSCharacterSetURLUserAllowedCharacterSet())let password = secureGenerateKey(NSCharacterSetURLPasswordAllowedCharacterSet())listenersetPasswords([username password])
var success = listenerstart(amperror)if (success)
syncUrl = genearteSyncURL(listenerURL username username password password dbName databasename)
startObserveDatabaseChange()
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Observe database changes
func startObserveDatabaseChange() NSNotificationCenterdefaultCenter()addObserverForName(kCBLDatabaseChangeNotification object database queue nil) (notification) -gt Void
in if let changes = notificationuserInfo[changes] as [CBLDatabaseChange] for change in changes
dispatch_async(dispatch_get_main_queue() selfsaveImageFromDocument(changedocumentID) )
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Generate and display a QR code
httpuserpasswordltlistener hostgtltportgtdb
Uses the iOS Core Image filter
copy2015 Couchbase Inc lsaquorsaquo
SendViewControllerStep 1 Scan a QR code
Uses the iOS class AVCaptureSession with the output type AVMetadataObjectTypeQRCode
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Create documents
var docIds [String] = []for asset in sharedAssets
var data = NSData(bytesNoCopy imageBytes length buffered freeWhenDone true)
let doc = databasecreateDocument()let rev = docnewRevision()revsetAttachmentNamed(photo withContentType applicationoctet-stream
content data)let saved = revsave(amperror)
if saved = nil docIdsappend(docdocumentID)
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Replicate documents
replicator = databasecreatePushReplication(url)replicatordocumentIDs = docIds
NSNotificationCenterdefaultCenter()addObserverForName(kCBLReplicationChangeNotification object replicator queue nil) (notification) -gt Void in
if selfreplicatorlastError == nil var totalCount = selfreplicatorchangesCountvar completedCount = selfreplicatorcompletedChangesCountif completedCount gt 0 ampamp completedCount == totalCount
selfstatusLabeltext = Sending Completedrdquo
else selfstatusLabeltext = Sending Abort
replicatorstart()
copy2015 Couchbase Inc lsaquorsaquo
Source Code
httpsgithubcomcouchbaselabsphoto-drop
Demo 2PhotoDrop App
The End mdash Any Questions
copy2015 Couchbase Inc lsaquorsaquo
Automatic Peer Discovery
ldquoWhorsquos running this serviceapp [on this LAN]rdquoAdvertise your own serviceTypeNameAddress + portSmall metadata (timestamphellip)
Browse for same service typeNotified as peers go onoffline
copy2015 Couchbase Inc lsaquorsaquo
Multicast DNS (mDNS) DNS Service Discovery (DNS-SD)
aka Bonjourtrade ZeroConf Avahi Network Service Discovery
RFC 6762 RFC 6763iOS Mac OS X Android (41+) LinuxWindows apps can integrate Applersquos
mDNSResponderdeveloperapplecomlibrarymacdocumentation
NetworkingConceptualNSNetServiceProgGuidedeveloperandroidcomtrainingconnect-devices-
wirelessly
copy2015 Couchbase Inc lsaquorsaquo
Advertising Your Service
listener = CBLListener(manager databasemanager port 55555) listenerreadOnly = true listenersetBonjourName(userNickname type _myapp_tcp)
Note setBonjourName isnrsquot available in CBL on Android yet Instead use NsdServiceInfo directly
Service name might be altered (number appended) to disambiguate it
copy2015 Couchbase Inc lsaquorsaquo
Browsing For Peers (iOS)
browser = NSNetServiceBrowsernew() browserincludesPeerToPeer = true browserdelegate = self browsersearchForServicesOfType(_myapp_tcp inDomain local)
public func netServiceBrowser(sender NSNetServiceBrowser didFindService service NSNetService moreComing Bool) hellip
public func netServiceBrowser(sender NSNetServiceBrowser didRemoveService service NSNetService moreComing Bool) hellip
copy2015 Couchbase Inc lsaquorsaquo
Connecting To A Peer (iOS)
Start async resolve to find servicersquos hostname servicedelegate = self serviceresolveWithTimeout(50)
NSNetService delegate callback public func netServiceDidResolveAddress(service NSNetService) Construct the remote DB URL var components = NSURLComponents() componentsscheme = http Or https if peer uses SSL componentshost = servicehostName componentsport = serviceport componentspath = + remoteDatabaseName let url = componentsURL
Start replication pull = localDBcreatePullReplication(url) pullstart()
copy2015 Couchbase Inc lsaquorsaquo
Using Bonjour To Replicate
Advertise a UUID as part of your service namePublish my dblatestSequence in service
metadataRemember UUID latestSequence of each lsquopairedrsquo
peerWhen peerrsquos latestSequence changes start a
pull replication
DEMO IPeerSync App
Q Whatrsquos Wrong With That DemoA No authentication
copy2015 Couchbase Inc lsaquorsaquo
C
Forging Documents or Revisions
docByA
B
A
B is sending me lsquodocByArsquo hellip but how
do I know it was really created by A
128530
128519
128564
copy2015 Couchbase Inc lsaquorsaquo
P2P Authentication Is A Hard Problem
With no server accountshow do you prove who you are
With no server to trusthow do you know whether data is valid
copy2015 Couchbase Inc lsaquorsaquo
This Is Not A Typical Auth Problem
SSL doesnrsquot helpHTTP authentication (ArArrB or BrArrC) doesnrsquot helpOnly authenticating the data helps
copy2015 Couchbase Inc lsaquorsaquo
Digital Signatures
Every user or device generates a key-pairEvery revision is signed by the party who created
itTo validate a revisionMake sure the signature is validLook up the authorrsquos public keyCompare signing key with authorrsquos key
copy2015 Couchbase Inc lsaquorsaquo
Key Distribution
Traditional StyleTrusted authority (server) signs key into a
certificateServer distributes certificate
P2P StyleDevice uses raw key or self-signed certificateUsers lsquopairrsquo devices in person
trading keys over a secure channel
Implementing Peer-to-PeerPart 3
Manual 11 Pairing
Pasin Suriyentrakorn
copy2015 Couchbase Inc lsaquorsaquo
PhotoDrop
Receiver ndash Presenting the QR Code and Receiving Photos
Sender ndash Selecting Photos Sender ndash Scanning a QR Code and Sending Photos
copy2015 Couchbase Inc lsaquorsaquo
ImplementationUses a QR code for peer discoveryUses one-time push replication to transfer photosUses digest authenticationGenerates one-time user credentialsSupports multiple platforms (eg iOS and
Android)
copy2015 Couchbase Inc lsaquorsaquo
StoryboardViewController SendViewController
ReceiveViewController
QR Code Scanner
Presents a QR code
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 1 Start a listener
listener = CBLListener(manager CBLManagersharedInstance() port 0)
listenerrequiresAuth = truelet username = secureGenerateKey(NSCharacterSetURLUserAllowedCharacterSet())let password = secureGenerateKey(NSCharacterSetURLPasswordAllowedCharacterSet())listenersetPasswords([username password])
var success = listenerstart(amperror)if (success)
syncUrl = genearteSyncURL(listenerURL username username password password dbName databasename)
startObserveDatabaseChange()
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Observe database changes
func startObserveDatabaseChange() NSNotificationCenterdefaultCenter()addObserverForName(kCBLDatabaseChangeNotification object database queue nil) (notification) -gt Void
in if let changes = notificationuserInfo[changes] as [CBLDatabaseChange] for change in changes
dispatch_async(dispatch_get_main_queue() selfsaveImageFromDocument(changedocumentID) )
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Generate and display a QR code
httpuserpasswordltlistener hostgtltportgtdb
Uses the iOS Core Image filter
copy2015 Couchbase Inc lsaquorsaquo
SendViewControllerStep 1 Scan a QR code
Uses the iOS class AVCaptureSession with the output type AVMetadataObjectTypeQRCode
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Create documents
var docIds [String] = []for asset in sharedAssets
var data = NSData(bytesNoCopy imageBytes length buffered freeWhenDone true)
let doc = databasecreateDocument()let rev = docnewRevision()revsetAttachmentNamed(photo withContentType applicationoctet-stream
content data)let saved = revsave(amperror)
if saved = nil docIdsappend(docdocumentID)
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Replicate documents
replicator = databasecreatePushReplication(url)replicatordocumentIDs = docIds
NSNotificationCenterdefaultCenter()addObserverForName(kCBLReplicationChangeNotification object replicator queue nil) (notification) -gt Void in
if selfreplicatorlastError == nil var totalCount = selfreplicatorchangesCountvar completedCount = selfreplicatorcompletedChangesCountif completedCount gt 0 ampamp completedCount == totalCount
selfstatusLabeltext = Sending Completedrdquo
else selfstatusLabeltext = Sending Abort
replicatorstart()
copy2015 Couchbase Inc lsaquorsaquo
Source Code
httpsgithubcomcouchbaselabsphoto-drop
Demo 2PhotoDrop App
The End mdash Any Questions
copy2015 Couchbase Inc lsaquorsaquo
Multicast DNS (mDNS) DNS Service Discovery (DNS-SD)
aka Bonjourtrade ZeroConf Avahi Network Service Discovery
RFC 6762 RFC 6763iOS Mac OS X Android (41+) LinuxWindows apps can integrate Applersquos
mDNSResponderdeveloperapplecomlibrarymacdocumentation
NetworkingConceptualNSNetServiceProgGuidedeveloperandroidcomtrainingconnect-devices-
wirelessly
copy2015 Couchbase Inc lsaquorsaquo
Advertising Your Service
listener = CBLListener(manager databasemanager port 55555) listenerreadOnly = true listenersetBonjourName(userNickname type _myapp_tcp)
Note setBonjourName isnrsquot available in CBL on Android yet Instead use NsdServiceInfo directly
Service name might be altered (number appended) to disambiguate it
copy2015 Couchbase Inc lsaquorsaquo
Browsing For Peers (iOS)
browser = NSNetServiceBrowsernew() browserincludesPeerToPeer = true browserdelegate = self browsersearchForServicesOfType(_myapp_tcp inDomain local)
public func netServiceBrowser(sender NSNetServiceBrowser didFindService service NSNetService moreComing Bool) hellip
public func netServiceBrowser(sender NSNetServiceBrowser didRemoveService service NSNetService moreComing Bool) hellip
copy2015 Couchbase Inc lsaquorsaquo
Connecting To A Peer (iOS)
Start async resolve to find servicersquos hostname servicedelegate = self serviceresolveWithTimeout(50)
NSNetService delegate callback public func netServiceDidResolveAddress(service NSNetService) Construct the remote DB URL var components = NSURLComponents() componentsscheme = http Or https if peer uses SSL componentshost = servicehostName componentsport = serviceport componentspath = + remoteDatabaseName let url = componentsURL
Start replication pull = localDBcreatePullReplication(url) pullstart()
copy2015 Couchbase Inc lsaquorsaquo
Using Bonjour To Replicate
Advertise a UUID as part of your service namePublish my dblatestSequence in service
metadataRemember UUID latestSequence of each lsquopairedrsquo
peerWhen peerrsquos latestSequence changes start a
pull replication
DEMO IPeerSync App
Q Whatrsquos Wrong With That DemoA No authentication
copy2015 Couchbase Inc lsaquorsaquo
C
Forging Documents or Revisions
docByA
B
A
B is sending me lsquodocByArsquo hellip but how
do I know it was really created by A
128530
128519
128564
copy2015 Couchbase Inc lsaquorsaquo
P2P Authentication Is A Hard Problem
With no server accountshow do you prove who you are
With no server to trusthow do you know whether data is valid
copy2015 Couchbase Inc lsaquorsaquo
This Is Not A Typical Auth Problem
SSL doesnrsquot helpHTTP authentication (ArArrB or BrArrC) doesnrsquot helpOnly authenticating the data helps
copy2015 Couchbase Inc lsaquorsaquo
Digital Signatures
Every user or device generates a key-pairEvery revision is signed by the party who created
itTo validate a revisionMake sure the signature is validLook up the authorrsquos public keyCompare signing key with authorrsquos key
copy2015 Couchbase Inc lsaquorsaquo
Key Distribution
Traditional StyleTrusted authority (server) signs key into a
certificateServer distributes certificate
P2P StyleDevice uses raw key or self-signed certificateUsers lsquopairrsquo devices in person
trading keys over a secure channel
Implementing Peer-to-PeerPart 3
Manual 11 Pairing
Pasin Suriyentrakorn
copy2015 Couchbase Inc lsaquorsaquo
PhotoDrop
Receiver ndash Presenting the QR Code and Receiving Photos
Sender ndash Selecting Photos Sender ndash Scanning a QR Code and Sending Photos
copy2015 Couchbase Inc lsaquorsaquo
ImplementationUses a QR code for peer discoveryUses one-time push replication to transfer photosUses digest authenticationGenerates one-time user credentialsSupports multiple platforms (eg iOS and
Android)
copy2015 Couchbase Inc lsaquorsaquo
StoryboardViewController SendViewController
ReceiveViewController
QR Code Scanner
Presents a QR code
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 1 Start a listener
listener = CBLListener(manager CBLManagersharedInstance() port 0)
listenerrequiresAuth = truelet username = secureGenerateKey(NSCharacterSetURLUserAllowedCharacterSet())let password = secureGenerateKey(NSCharacterSetURLPasswordAllowedCharacterSet())listenersetPasswords([username password])
var success = listenerstart(amperror)if (success)
syncUrl = genearteSyncURL(listenerURL username username password password dbName databasename)
startObserveDatabaseChange()
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Observe database changes
func startObserveDatabaseChange() NSNotificationCenterdefaultCenter()addObserverForName(kCBLDatabaseChangeNotification object database queue nil) (notification) -gt Void
in if let changes = notificationuserInfo[changes] as [CBLDatabaseChange] for change in changes
dispatch_async(dispatch_get_main_queue() selfsaveImageFromDocument(changedocumentID) )
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Generate and display a QR code
httpuserpasswordltlistener hostgtltportgtdb
Uses the iOS Core Image filter
copy2015 Couchbase Inc lsaquorsaquo
SendViewControllerStep 1 Scan a QR code
Uses the iOS class AVCaptureSession with the output type AVMetadataObjectTypeQRCode
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Create documents
var docIds [String] = []for asset in sharedAssets
var data = NSData(bytesNoCopy imageBytes length buffered freeWhenDone true)
let doc = databasecreateDocument()let rev = docnewRevision()revsetAttachmentNamed(photo withContentType applicationoctet-stream
content data)let saved = revsave(amperror)
if saved = nil docIdsappend(docdocumentID)
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Replicate documents
replicator = databasecreatePushReplication(url)replicatordocumentIDs = docIds
NSNotificationCenterdefaultCenter()addObserverForName(kCBLReplicationChangeNotification object replicator queue nil) (notification) -gt Void in
if selfreplicatorlastError == nil var totalCount = selfreplicatorchangesCountvar completedCount = selfreplicatorcompletedChangesCountif completedCount gt 0 ampamp completedCount == totalCount
selfstatusLabeltext = Sending Completedrdquo
else selfstatusLabeltext = Sending Abort
replicatorstart()
copy2015 Couchbase Inc lsaquorsaquo
Source Code
httpsgithubcomcouchbaselabsphoto-drop
Demo 2PhotoDrop App
The End mdash Any Questions
copy2015 Couchbase Inc lsaquorsaquo
Advertising Your Service
listener = CBLListener(manager databasemanager port 55555) listenerreadOnly = true listenersetBonjourName(userNickname type _myapp_tcp)
Note setBonjourName isnrsquot available in CBL on Android yet Instead use NsdServiceInfo directly
Service name might be altered (number appended) to disambiguate it
copy2015 Couchbase Inc lsaquorsaquo
Browsing For Peers (iOS)
browser = NSNetServiceBrowsernew() browserincludesPeerToPeer = true browserdelegate = self browsersearchForServicesOfType(_myapp_tcp inDomain local)
public func netServiceBrowser(sender NSNetServiceBrowser didFindService service NSNetService moreComing Bool) hellip
public func netServiceBrowser(sender NSNetServiceBrowser didRemoveService service NSNetService moreComing Bool) hellip
copy2015 Couchbase Inc lsaquorsaquo
Connecting To A Peer (iOS)
Start async resolve to find servicersquos hostname servicedelegate = self serviceresolveWithTimeout(50)
NSNetService delegate callback public func netServiceDidResolveAddress(service NSNetService) Construct the remote DB URL var components = NSURLComponents() componentsscheme = http Or https if peer uses SSL componentshost = servicehostName componentsport = serviceport componentspath = + remoteDatabaseName let url = componentsURL
Start replication pull = localDBcreatePullReplication(url) pullstart()
copy2015 Couchbase Inc lsaquorsaquo
Using Bonjour To Replicate
Advertise a UUID as part of your service namePublish my dblatestSequence in service
metadataRemember UUID latestSequence of each lsquopairedrsquo
peerWhen peerrsquos latestSequence changes start a
pull replication
DEMO IPeerSync App
Q Whatrsquos Wrong With That DemoA No authentication
copy2015 Couchbase Inc lsaquorsaquo
C
Forging Documents or Revisions
docByA
B
A
B is sending me lsquodocByArsquo hellip but how
do I know it was really created by A
128530
128519
128564
copy2015 Couchbase Inc lsaquorsaquo
P2P Authentication Is A Hard Problem
With no server accountshow do you prove who you are
With no server to trusthow do you know whether data is valid
copy2015 Couchbase Inc lsaquorsaquo
This Is Not A Typical Auth Problem
SSL doesnrsquot helpHTTP authentication (ArArrB or BrArrC) doesnrsquot helpOnly authenticating the data helps
copy2015 Couchbase Inc lsaquorsaquo
Digital Signatures
Every user or device generates a key-pairEvery revision is signed by the party who created
itTo validate a revisionMake sure the signature is validLook up the authorrsquos public keyCompare signing key with authorrsquos key
copy2015 Couchbase Inc lsaquorsaquo
Key Distribution
Traditional StyleTrusted authority (server) signs key into a
certificateServer distributes certificate
P2P StyleDevice uses raw key or self-signed certificateUsers lsquopairrsquo devices in person
trading keys over a secure channel
Implementing Peer-to-PeerPart 3
Manual 11 Pairing
Pasin Suriyentrakorn
copy2015 Couchbase Inc lsaquorsaquo
PhotoDrop
Receiver ndash Presenting the QR Code and Receiving Photos
Sender ndash Selecting Photos Sender ndash Scanning a QR Code and Sending Photos
copy2015 Couchbase Inc lsaquorsaquo
ImplementationUses a QR code for peer discoveryUses one-time push replication to transfer photosUses digest authenticationGenerates one-time user credentialsSupports multiple platforms (eg iOS and
Android)
copy2015 Couchbase Inc lsaquorsaquo
StoryboardViewController SendViewController
ReceiveViewController
QR Code Scanner
Presents a QR code
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 1 Start a listener
listener = CBLListener(manager CBLManagersharedInstance() port 0)
listenerrequiresAuth = truelet username = secureGenerateKey(NSCharacterSetURLUserAllowedCharacterSet())let password = secureGenerateKey(NSCharacterSetURLPasswordAllowedCharacterSet())listenersetPasswords([username password])
var success = listenerstart(amperror)if (success)
syncUrl = genearteSyncURL(listenerURL username username password password dbName databasename)
startObserveDatabaseChange()
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Observe database changes
func startObserveDatabaseChange() NSNotificationCenterdefaultCenter()addObserverForName(kCBLDatabaseChangeNotification object database queue nil) (notification) -gt Void
in if let changes = notificationuserInfo[changes] as [CBLDatabaseChange] for change in changes
dispatch_async(dispatch_get_main_queue() selfsaveImageFromDocument(changedocumentID) )
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Generate and display a QR code
httpuserpasswordltlistener hostgtltportgtdb
Uses the iOS Core Image filter
copy2015 Couchbase Inc lsaquorsaquo
SendViewControllerStep 1 Scan a QR code
Uses the iOS class AVCaptureSession with the output type AVMetadataObjectTypeQRCode
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Create documents
var docIds [String] = []for asset in sharedAssets
var data = NSData(bytesNoCopy imageBytes length buffered freeWhenDone true)
let doc = databasecreateDocument()let rev = docnewRevision()revsetAttachmentNamed(photo withContentType applicationoctet-stream
content data)let saved = revsave(amperror)
if saved = nil docIdsappend(docdocumentID)
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Replicate documents
replicator = databasecreatePushReplication(url)replicatordocumentIDs = docIds
NSNotificationCenterdefaultCenter()addObserverForName(kCBLReplicationChangeNotification object replicator queue nil) (notification) -gt Void in
if selfreplicatorlastError == nil var totalCount = selfreplicatorchangesCountvar completedCount = selfreplicatorcompletedChangesCountif completedCount gt 0 ampamp completedCount == totalCount
selfstatusLabeltext = Sending Completedrdquo
else selfstatusLabeltext = Sending Abort
replicatorstart()
copy2015 Couchbase Inc lsaquorsaquo
Source Code
httpsgithubcomcouchbaselabsphoto-drop
Demo 2PhotoDrop App
The End mdash Any Questions
copy2015 Couchbase Inc lsaquorsaquo
Browsing For Peers (iOS)
browser = NSNetServiceBrowsernew() browserincludesPeerToPeer = true browserdelegate = self browsersearchForServicesOfType(_myapp_tcp inDomain local)
public func netServiceBrowser(sender NSNetServiceBrowser didFindService service NSNetService moreComing Bool) hellip
public func netServiceBrowser(sender NSNetServiceBrowser didRemoveService service NSNetService moreComing Bool) hellip
copy2015 Couchbase Inc lsaquorsaquo
Connecting To A Peer (iOS)
Start async resolve to find servicersquos hostname servicedelegate = self serviceresolveWithTimeout(50)
NSNetService delegate callback public func netServiceDidResolveAddress(service NSNetService) Construct the remote DB URL var components = NSURLComponents() componentsscheme = http Or https if peer uses SSL componentshost = servicehostName componentsport = serviceport componentspath = + remoteDatabaseName let url = componentsURL
Start replication pull = localDBcreatePullReplication(url) pullstart()
copy2015 Couchbase Inc lsaquorsaquo
Using Bonjour To Replicate
Advertise a UUID as part of your service namePublish my dblatestSequence in service
metadataRemember UUID latestSequence of each lsquopairedrsquo
peerWhen peerrsquos latestSequence changes start a
pull replication
DEMO IPeerSync App
Q Whatrsquos Wrong With That DemoA No authentication
copy2015 Couchbase Inc lsaquorsaquo
C
Forging Documents or Revisions
docByA
B
A
B is sending me lsquodocByArsquo hellip but how
do I know it was really created by A
128530
128519
128564
copy2015 Couchbase Inc lsaquorsaquo
P2P Authentication Is A Hard Problem
With no server accountshow do you prove who you are
With no server to trusthow do you know whether data is valid
copy2015 Couchbase Inc lsaquorsaquo
This Is Not A Typical Auth Problem
SSL doesnrsquot helpHTTP authentication (ArArrB or BrArrC) doesnrsquot helpOnly authenticating the data helps
copy2015 Couchbase Inc lsaquorsaquo
Digital Signatures
Every user or device generates a key-pairEvery revision is signed by the party who created
itTo validate a revisionMake sure the signature is validLook up the authorrsquos public keyCompare signing key with authorrsquos key
copy2015 Couchbase Inc lsaquorsaquo
Key Distribution
Traditional StyleTrusted authority (server) signs key into a
certificateServer distributes certificate
P2P StyleDevice uses raw key or self-signed certificateUsers lsquopairrsquo devices in person
trading keys over a secure channel
Implementing Peer-to-PeerPart 3
Manual 11 Pairing
Pasin Suriyentrakorn
copy2015 Couchbase Inc lsaquorsaquo
PhotoDrop
Receiver ndash Presenting the QR Code and Receiving Photos
Sender ndash Selecting Photos Sender ndash Scanning a QR Code and Sending Photos
copy2015 Couchbase Inc lsaquorsaquo
ImplementationUses a QR code for peer discoveryUses one-time push replication to transfer photosUses digest authenticationGenerates one-time user credentialsSupports multiple platforms (eg iOS and
Android)
copy2015 Couchbase Inc lsaquorsaquo
StoryboardViewController SendViewController
ReceiveViewController
QR Code Scanner
Presents a QR code
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 1 Start a listener
listener = CBLListener(manager CBLManagersharedInstance() port 0)
listenerrequiresAuth = truelet username = secureGenerateKey(NSCharacterSetURLUserAllowedCharacterSet())let password = secureGenerateKey(NSCharacterSetURLPasswordAllowedCharacterSet())listenersetPasswords([username password])
var success = listenerstart(amperror)if (success)
syncUrl = genearteSyncURL(listenerURL username username password password dbName databasename)
startObserveDatabaseChange()
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Observe database changes
func startObserveDatabaseChange() NSNotificationCenterdefaultCenter()addObserverForName(kCBLDatabaseChangeNotification object database queue nil) (notification) -gt Void
in if let changes = notificationuserInfo[changes] as [CBLDatabaseChange] for change in changes
dispatch_async(dispatch_get_main_queue() selfsaveImageFromDocument(changedocumentID) )
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Generate and display a QR code
httpuserpasswordltlistener hostgtltportgtdb
Uses the iOS Core Image filter
copy2015 Couchbase Inc lsaquorsaquo
SendViewControllerStep 1 Scan a QR code
Uses the iOS class AVCaptureSession with the output type AVMetadataObjectTypeQRCode
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Create documents
var docIds [String] = []for asset in sharedAssets
var data = NSData(bytesNoCopy imageBytes length buffered freeWhenDone true)
let doc = databasecreateDocument()let rev = docnewRevision()revsetAttachmentNamed(photo withContentType applicationoctet-stream
content data)let saved = revsave(amperror)
if saved = nil docIdsappend(docdocumentID)
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Replicate documents
replicator = databasecreatePushReplication(url)replicatordocumentIDs = docIds
NSNotificationCenterdefaultCenter()addObserverForName(kCBLReplicationChangeNotification object replicator queue nil) (notification) -gt Void in
if selfreplicatorlastError == nil var totalCount = selfreplicatorchangesCountvar completedCount = selfreplicatorcompletedChangesCountif completedCount gt 0 ampamp completedCount == totalCount
selfstatusLabeltext = Sending Completedrdquo
else selfstatusLabeltext = Sending Abort
replicatorstart()
copy2015 Couchbase Inc lsaquorsaquo
Source Code
httpsgithubcomcouchbaselabsphoto-drop
Demo 2PhotoDrop App
The End mdash Any Questions
copy2015 Couchbase Inc lsaquorsaquo
Connecting To A Peer (iOS)
Start async resolve to find servicersquos hostname servicedelegate = self serviceresolveWithTimeout(50)
NSNetService delegate callback public func netServiceDidResolveAddress(service NSNetService) Construct the remote DB URL var components = NSURLComponents() componentsscheme = http Or https if peer uses SSL componentshost = servicehostName componentsport = serviceport componentspath = + remoteDatabaseName let url = componentsURL
Start replication pull = localDBcreatePullReplication(url) pullstart()
copy2015 Couchbase Inc lsaquorsaquo
Using Bonjour To Replicate
Advertise a UUID as part of your service namePublish my dblatestSequence in service
metadataRemember UUID latestSequence of each lsquopairedrsquo
peerWhen peerrsquos latestSequence changes start a
pull replication
DEMO IPeerSync App
Q Whatrsquos Wrong With That DemoA No authentication
copy2015 Couchbase Inc lsaquorsaquo
C
Forging Documents or Revisions
docByA
B
A
B is sending me lsquodocByArsquo hellip but how
do I know it was really created by A
128530
128519
128564
copy2015 Couchbase Inc lsaquorsaquo
P2P Authentication Is A Hard Problem
With no server accountshow do you prove who you are
With no server to trusthow do you know whether data is valid
copy2015 Couchbase Inc lsaquorsaquo
This Is Not A Typical Auth Problem
SSL doesnrsquot helpHTTP authentication (ArArrB or BrArrC) doesnrsquot helpOnly authenticating the data helps
copy2015 Couchbase Inc lsaquorsaquo
Digital Signatures
Every user or device generates a key-pairEvery revision is signed by the party who created
itTo validate a revisionMake sure the signature is validLook up the authorrsquos public keyCompare signing key with authorrsquos key
copy2015 Couchbase Inc lsaquorsaquo
Key Distribution
Traditional StyleTrusted authority (server) signs key into a
certificateServer distributes certificate
P2P StyleDevice uses raw key or self-signed certificateUsers lsquopairrsquo devices in person
trading keys over a secure channel
Implementing Peer-to-PeerPart 3
Manual 11 Pairing
Pasin Suriyentrakorn
copy2015 Couchbase Inc lsaquorsaquo
PhotoDrop
Receiver ndash Presenting the QR Code and Receiving Photos
Sender ndash Selecting Photos Sender ndash Scanning a QR Code and Sending Photos
copy2015 Couchbase Inc lsaquorsaquo
ImplementationUses a QR code for peer discoveryUses one-time push replication to transfer photosUses digest authenticationGenerates one-time user credentialsSupports multiple platforms (eg iOS and
Android)
copy2015 Couchbase Inc lsaquorsaquo
StoryboardViewController SendViewController
ReceiveViewController
QR Code Scanner
Presents a QR code
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 1 Start a listener
listener = CBLListener(manager CBLManagersharedInstance() port 0)
listenerrequiresAuth = truelet username = secureGenerateKey(NSCharacterSetURLUserAllowedCharacterSet())let password = secureGenerateKey(NSCharacterSetURLPasswordAllowedCharacterSet())listenersetPasswords([username password])
var success = listenerstart(amperror)if (success)
syncUrl = genearteSyncURL(listenerURL username username password password dbName databasename)
startObserveDatabaseChange()
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Observe database changes
func startObserveDatabaseChange() NSNotificationCenterdefaultCenter()addObserverForName(kCBLDatabaseChangeNotification object database queue nil) (notification) -gt Void
in if let changes = notificationuserInfo[changes] as [CBLDatabaseChange] for change in changes
dispatch_async(dispatch_get_main_queue() selfsaveImageFromDocument(changedocumentID) )
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Generate and display a QR code
httpuserpasswordltlistener hostgtltportgtdb
Uses the iOS Core Image filter
copy2015 Couchbase Inc lsaquorsaquo
SendViewControllerStep 1 Scan a QR code
Uses the iOS class AVCaptureSession with the output type AVMetadataObjectTypeQRCode
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Create documents
var docIds [String] = []for asset in sharedAssets
var data = NSData(bytesNoCopy imageBytes length buffered freeWhenDone true)
let doc = databasecreateDocument()let rev = docnewRevision()revsetAttachmentNamed(photo withContentType applicationoctet-stream
content data)let saved = revsave(amperror)
if saved = nil docIdsappend(docdocumentID)
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Replicate documents
replicator = databasecreatePushReplication(url)replicatordocumentIDs = docIds
NSNotificationCenterdefaultCenter()addObserverForName(kCBLReplicationChangeNotification object replicator queue nil) (notification) -gt Void in
if selfreplicatorlastError == nil var totalCount = selfreplicatorchangesCountvar completedCount = selfreplicatorcompletedChangesCountif completedCount gt 0 ampamp completedCount == totalCount
selfstatusLabeltext = Sending Completedrdquo
else selfstatusLabeltext = Sending Abort
replicatorstart()
copy2015 Couchbase Inc lsaquorsaquo
Source Code
httpsgithubcomcouchbaselabsphoto-drop
Demo 2PhotoDrop App
The End mdash Any Questions
copy2015 Couchbase Inc lsaquorsaquo
Using Bonjour To Replicate
Advertise a UUID as part of your service namePublish my dblatestSequence in service
metadataRemember UUID latestSequence of each lsquopairedrsquo
peerWhen peerrsquos latestSequence changes start a
pull replication
DEMO IPeerSync App
Q Whatrsquos Wrong With That DemoA No authentication
copy2015 Couchbase Inc lsaquorsaquo
C
Forging Documents or Revisions
docByA
B
A
B is sending me lsquodocByArsquo hellip but how
do I know it was really created by A
128530
128519
128564
copy2015 Couchbase Inc lsaquorsaquo
P2P Authentication Is A Hard Problem
With no server accountshow do you prove who you are
With no server to trusthow do you know whether data is valid
copy2015 Couchbase Inc lsaquorsaquo
This Is Not A Typical Auth Problem
SSL doesnrsquot helpHTTP authentication (ArArrB or BrArrC) doesnrsquot helpOnly authenticating the data helps
copy2015 Couchbase Inc lsaquorsaquo
Digital Signatures
Every user or device generates a key-pairEvery revision is signed by the party who created
itTo validate a revisionMake sure the signature is validLook up the authorrsquos public keyCompare signing key with authorrsquos key
copy2015 Couchbase Inc lsaquorsaquo
Key Distribution
Traditional StyleTrusted authority (server) signs key into a
certificateServer distributes certificate
P2P StyleDevice uses raw key or self-signed certificateUsers lsquopairrsquo devices in person
trading keys over a secure channel
Implementing Peer-to-PeerPart 3
Manual 11 Pairing
Pasin Suriyentrakorn
copy2015 Couchbase Inc lsaquorsaquo
PhotoDrop
Receiver ndash Presenting the QR Code and Receiving Photos
Sender ndash Selecting Photos Sender ndash Scanning a QR Code and Sending Photos
copy2015 Couchbase Inc lsaquorsaquo
ImplementationUses a QR code for peer discoveryUses one-time push replication to transfer photosUses digest authenticationGenerates one-time user credentialsSupports multiple platforms (eg iOS and
Android)
copy2015 Couchbase Inc lsaquorsaquo
StoryboardViewController SendViewController
ReceiveViewController
QR Code Scanner
Presents a QR code
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 1 Start a listener
listener = CBLListener(manager CBLManagersharedInstance() port 0)
listenerrequiresAuth = truelet username = secureGenerateKey(NSCharacterSetURLUserAllowedCharacterSet())let password = secureGenerateKey(NSCharacterSetURLPasswordAllowedCharacterSet())listenersetPasswords([username password])
var success = listenerstart(amperror)if (success)
syncUrl = genearteSyncURL(listenerURL username username password password dbName databasename)
startObserveDatabaseChange()
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Observe database changes
func startObserveDatabaseChange() NSNotificationCenterdefaultCenter()addObserverForName(kCBLDatabaseChangeNotification object database queue nil) (notification) -gt Void
in if let changes = notificationuserInfo[changes] as [CBLDatabaseChange] for change in changes
dispatch_async(dispatch_get_main_queue() selfsaveImageFromDocument(changedocumentID) )
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Generate and display a QR code
httpuserpasswordltlistener hostgtltportgtdb
Uses the iOS Core Image filter
copy2015 Couchbase Inc lsaquorsaquo
SendViewControllerStep 1 Scan a QR code
Uses the iOS class AVCaptureSession with the output type AVMetadataObjectTypeQRCode
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Create documents
var docIds [String] = []for asset in sharedAssets
var data = NSData(bytesNoCopy imageBytes length buffered freeWhenDone true)
let doc = databasecreateDocument()let rev = docnewRevision()revsetAttachmentNamed(photo withContentType applicationoctet-stream
content data)let saved = revsave(amperror)
if saved = nil docIdsappend(docdocumentID)
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Replicate documents
replicator = databasecreatePushReplication(url)replicatordocumentIDs = docIds
NSNotificationCenterdefaultCenter()addObserverForName(kCBLReplicationChangeNotification object replicator queue nil) (notification) -gt Void in
if selfreplicatorlastError == nil var totalCount = selfreplicatorchangesCountvar completedCount = selfreplicatorcompletedChangesCountif completedCount gt 0 ampamp completedCount == totalCount
selfstatusLabeltext = Sending Completedrdquo
else selfstatusLabeltext = Sending Abort
replicatorstart()
copy2015 Couchbase Inc lsaquorsaquo
Source Code
httpsgithubcomcouchbaselabsphoto-drop
Demo 2PhotoDrop App
The End mdash Any Questions
DEMO IPeerSync App
Q Whatrsquos Wrong With That DemoA No authentication
copy2015 Couchbase Inc lsaquorsaquo
C
Forging Documents or Revisions
docByA
B
A
B is sending me lsquodocByArsquo hellip but how
do I know it was really created by A
128530
128519
128564
copy2015 Couchbase Inc lsaquorsaquo
P2P Authentication Is A Hard Problem
With no server accountshow do you prove who you are
With no server to trusthow do you know whether data is valid
copy2015 Couchbase Inc lsaquorsaquo
This Is Not A Typical Auth Problem
SSL doesnrsquot helpHTTP authentication (ArArrB or BrArrC) doesnrsquot helpOnly authenticating the data helps
copy2015 Couchbase Inc lsaquorsaquo
Digital Signatures
Every user or device generates a key-pairEvery revision is signed by the party who created
itTo validate a revisionMake sure the signature is validLook up the authorrsquos public keyCompare signing key with authorrsquos key
copy2015 Couchbase Inc lsaquorsaquo
Key Distribution
Traditional StyleTrusted authority (server) signs key into a
certificateServer distributes certificate
P2P StyleDevice uses raw key or self-signed certificateUsers lsquopairrsquo devices in person
trading keys over a secure channel
Implementing Peer-to-PeerPart 3
Manual 11 Pairing
Pasin Suriyentrakorn
copy2015 Couchbase Inc lsaquorsaquo
PhotoDrop
Receiver ndash Presenting the QR Code and Receiving Photos
Sender ndash Selecting Photos Sender ndash Scanning a QR Code and Sending Photos
copy2015 Couchbase Inc lsaquorsaquo
ImplementationUses a QR code for peer discoveryUses one-time push replication to transfer photosUses digest authenticationGenerates one-time user credentialsSupports multiple platforms (eg iOS and
Android)
copy2015 Couchbase Inc lsaquorsaquo
StoryboardViewController SendViewController
ReceiveViewController
QR Code Scanner
Presents a QR code
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 1 Start a listener
listener = CBLListener(manager CBLManagersharedInstance() port 0)
listenerrequiresAuth = truelet username = secureGenerateKey(NSCharacterSetURLUserAllowedCharacterSet())let password = secureGenerateKey(NSCharacterSetURLPasswordAllowedCharacterSet())listenersetPasswords([username password])
var success = listenerstart(amperror)if (success)
syncUrl = genearteSyncURL(listenerURL username username password password dbName databasename)
startObserveDatabaseChange()
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Observe database changes
func startObserveDatabaseChange() NSNotificationCenterdefaultCenter()addObserverForName(kCBLDatabaseChangeNotification object database queue nil) (notification) -gt Void
in if let changes = notificationuserInfo[changes] as [CBLDatabaseChange] for change in changes
dispatch_async(dispatch_get_main_queue() selfsaveImageFromDocument(changedocumentID) )
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Generate and display a QR code
httpuserpasswordltlistener hostgtltportgtdb
Uses the iOS Core Image filter
copy2015 Couchbase Inc lsaquorsaquo
SendViewControllerStep 1 Scan a QR code
Uses the iOS class AVCaptureSession with the output type AVMetadataObjectTypeQRCode
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Create documents
var docIds [String] = []for asset in sharedAssets
var data = NSData(bytesNoCopy imageBytes length buffered freeWhenDone true)
let doc = databasecreateDocument()let rev = docnewRevision()revsetAttachmentNamed(photo withContentType applicationoctet-stream
content data)let saved = revsave(amperror)
if saved = nil docIdsappend(docdocumentID)
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Replicate documents
replicator = databasecreatePushReplication(url)replicatordocumentIDs = docIds
NSNotificationCenterdefaultCenter()addObserverForName(kCBLReplicationChangeNotification object replicator queue nil) (notification) -gt Void in
if selfreplicatorlastError == nil var totalCount = selfreplicatorchangesCountvar completedCount = selfreplicatorcompletedChangesCountif completedCount gt 0 ampamp completedCount == totalCount
selfstatusLabeltext = Sending Completedrdquo
else selfstatusLabeltext = Sending Abort
replicatorstart()
copy2015 Couchbase Inc lsaquorsaquo
Source Code
httpsgithubcomcouchbaselabsphoto-drop
Demo 2PhotoDrop App
The End mdash Any Questions
Q Whatrsquos Wrong With That DemoA No authentication
copy2015 Couchbase Inc lsaquorsaquo
C
Forging Documents or Revisions
docByA
B
A
B is sending me lsquodocByArsquo hellip but how
do I know it was really created by A
128530
128519
128564
copy2015 Couchbase Inc lsaquorsaquo
P2P Authentication Is A Hard Problem
With no server accountshow do you prove who you are
With no server to trusthow do you know whether data is valid
copy2015 Couchbase Inc lsaquorsaquo
This Is Not A Typical Auth Problem
SSL doesnrsquot helpHTTP authentication (ArArrB or BrArrC) doesnrsquot helpOnly authenticating the data helps
copy2015 Couchbase Inc lsaquorsaquo
Digital Signatures
Every user or device generates a key-pairEvery revision is signed by the party who created
itTo validate a revisionMake sure the signature is validLook up the authorrsquos public keyCompare signing key with authorrsquos key
copy2015 Couchbase Inc lsaquorsaquo
Key Distribution
Traditional StyleTrusted authority (server) signs key into a
certificateServer distributes certificate
P2P StyleDevice uses raw key or self-signed certificateUsers lsquopairrsquo devices in person
trading keys over a secure channel
Implementing Peer-to-PeerPart 3
Manual 11 Pairing
Pasin Suriyentrakorn
copy2015 Couchbase Inc lsaquorsaquo
PhotoDrop
Receiver ndash Presenting the QR Code and Receiving Photos
Sender ndash Selecting Photos Sender ndash Scanning a QR Code and Sending Photos
copy2015 Couchbase Inc lsaquorsaquo
ImplementationUses a QR code for peer discoveryUses one-time push replication to transfer photosUses digest authenticationGenerates one-time user credentialsSupports multiple platforms (eg iOS and
Android)
copy2015 Couchbase Inc lsaquorsaquo
StoryboardViewController SendViewController
ReceiveViewController
QR Code Scanner
Presents a QR code
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 1 Start a listener
listener = CBLListener(manager CBLManagersharedInstance() port 0)
listenerrequiresAuth = truelet username = secureGenerateKey(NSCharacterSetURLUserAllowedCharacterSet())let password = secureGenerateKey(NSCharacterSetURLPasswordAllowedCharacterSet())listenersetPasswords([username password])
var success = listenerstart(amperror)if (success)
syncUrl = genearteSyncURL(listenerURL username username password password dbName databasename)
startObserveDatabaseChange()
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Observe database changes
func startObserveDatabaseChange() NSNotificationCenterdefaultCenter()addObserverForName(kCBLDatabaseChangeNotification object database queue nil) (notification) -gt Void
in if let changes = notificationuserInfo[changes] as [CBLDatabaseChange] for change in changes
dispatch_async(dispatch_get_main_queue() selfsaveImageFromDocument(changedocumentID) )
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Generate and display a QR code
httpuserpasswordltlistener hostgtltportgtdb
Uses the iOS Core Image filter
copy2015 Couchbase Inc lsaquorsaquo
SendViewControllerStep 1 Scan a QR code
Uses the iOS class AVCaptureSession with the output type AVMetadataObjectTypeQRCode
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Create documents
var docIds [String] = []for asset in sharedAssets
var data = NSData(bytesNoCopy imageBytes length buffered freeWhenDone true)
let doc = databasecreateDocument()let rev = docnewRevision()revsetAttachmentNamed(photo withContentType applicationoctet-stream
content data)let saved = revsave(amperror)
if saved = nil docIdsappend(docdocumentID)
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Replicate documents
replicator = databasecreatePushReplication(url)replicatordocumentIDs = docIds
NSNotificationCenterdefaultCenter()addObserverForName(kCBLReplicationChangeNotification object replicator queue nil) (notification) -gt Void in
if selfreplicatorlastError == nil var totalCount = selfreplicatorchangesCountvar completedCount = selfreplicatorcompletedChangesCountif completedCount gt 0 ampamp completedCount == totalCount
selfstatusLabeltext = Sending Completedrdquo
else selfstatusLabeltext = Sending Abort
replicatorstart()
copy2015 Couchbase Inc lsaquorsaquo
Source Code
httpsgithubcomcouchbaselabsphoto-drop
Demo 2PhotoDrop App
The End mdash Any Questions
copy2015 Couchbase Inc lsaquorsaquo
C
Forging Documents or Revisions
docByA
B
A
B is sending me lsquodocByArsquo hellip but how
do I know it was really created by A
128530
128519
128564
copy2015 Couchbase Inc lsaquorsaquo
P2P Authentication Is A Hard Problem
With no server accountshow do you prove who you are
With no server to trusthow do you know whether data is valid
copy2015 Couchbase Inc lsaquorsaquo
This Is Not A Typical Auth Problem
SSL doesnrsquot helpHTTP authentication (ArArrB or BrArrC) doesnrsquot helpOnly authenticating the data helps
copy2015 Couchbase Inc lsaquorsaquo
Digital Signatures
Every user or device generates a key-pairEvery revision is signed by the party who created
itTo validate a revisionMake sure the signature is validLook up the authorrsquos public keyCompare signing key with authorrsquos key
copy2015 Couchbase Inc lsaquorsaquo
Key Distribution
Traditional StyleTrusted authority (server) signs key into a
certificateServer distributes certificate
P2P StyleDevice uses raw key or self-signed certificateUsers lsquopairrsquo devices in person
trading keys over a secure channel
Implementing Peer-to-PeerPart 3
Manual 11 Pairing
Pasin Suriyentrakorn
copy2015 Couchbase Inc lsaquorsaquo
PhotoDrop
Receiver ndash Presenting the QR Code and Receiving Photos
Sender ndash Selecting Photos Sender ndash Scanning a QR Code and Sending Photos
copy2015 Couchbase Inc lsaquorsaquo
ImplementationUses a QR code for peer discoveryUses one-time push replication to transfer photosUses digest authenticationGenerates one-time user credentialsSupports multiple platforms (eg iOS and
Android)
copy2015 Couchbase Inc lsaquorsaquo
StoryboardViewController SendViewController
ReceiveViewController
QR Code Scanner
Presents a QR code
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 1 Start a listener
listener = CBLListener(manager CBLManagersharedInstance() port 0)
listenerrequiresAuth = truelet username = secureGenerateKey(NSCharacterSetURLUserAllowedCharacterSet())let password = secureGenerateKey(NSCharacterSetURLPasswordAllowedCharacterSet())listenersetPasswords([username password])
var success = listenerstart(amperror)if (success)
syncUrl = genearteSyncURL(listenerURL username username password password dbName databasename)
startObserveDatabaseChange()
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Observe database changes
func startObserveDatabaseChange() NSNotificationCenterdefaultCenter()addObserverForName(kCBLDatabaseChangeNotification object database queue nil) (notification) -gt Void
in if let changes = notificationuserInfo[changes] as [CBLDatabaseChange] for change in changes
dispatch_async(dispatch_get_main_queue() selfsaveImageFromDocument(changedocumentID) )
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Generate and display a QR code
httpuserpasswordltlistener hostgtltportgtdb
Uses the iOS Core Image filter
copy2015 Couchbase Inc lsaquorsaquo
SendViewControllerStep 1 Scan a QR code
Uses the iOS class AVCaptureSession with the output type AVMetadataObjectTypeQRCode
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Create documents
var docIds [String] = []for asset in sharedAssets
var data = NSData(bytesNoCopy imageBytes length buffered freeWhenDone true)
let doc = databasecreateDocument()let rev = docnewRevision()revsetAttachmentNamed(photo withContentType applicationoctet-stream
content data)let saved = revsave(amperror)
if saved = nil docIdsappend(docdocumentID)
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Replicate documents
replicator = databasecreatePushReplication(url)replicatordocumentIDs = docIds
NSNotificationCenterdefaultCenter()addObserverForName(kCBLReplicationChangeNotification object replicator queue nil) (notification) -gt Void in
if selfreplicatorlastError == nil var totalCount = selfreplicatorchangesCountvar completedCount = selfreplicatorcompletedChangesCountif completedCount gt 0 ampamp completedCount == totalCount
selfstatusLabeltext = Sending Completedrdquo
else selfstatusLabeltext = Sending Abort
replicatorstart()
copy2015 Couchbase Inc lsaquorsaquo
Source Code
httpsgithubcomcouchbaselabsphoto-drop
Demo 2PhotoDrop App
The End mdash Any Questions
copy2015 Couchbase Inc lsaquorsaquo
P2P Authentication Is A Hard Problem
With no server accountshow do you prove who you are
With no server to trusthow do you know whether data is valid
copy2015 Couchbase Inc lsaquorsaquo
This Is Not A Typical Auth Problem
SSL doesnrsquot helpHTTP authentication (ArArrB or BrArrC) doesnrsquot helpOnly authenticating the data helps
copy2015 Couchbase Inc lsaquorsaquo
Digital Signatures
Every user or device generates a key-pairEvery revision is signed by the party who created
itTo validate a revisionMake sure the signature is validLook up the authorrsquos public keyCompare signing key with authorrsquos key
copy2015 Couchbase Inc lsaquorsaquo
Key Distribution
Traditional StyleTrusted authority (server) signs key into a
certificateServer distributes certificate
P2P StyleDevice uses raw key or self-signed certificateUsers lsquopairrsquo devices in person
trading keys over a secure channel
Implementing Peer-to-PeerPart 3
Manual 11 Pairing
Pasin Suriyentrakorn
copy2015 Couchbase Inc lsaquorsaquo
PhotoDrop
Receiver ndash Presenting the QR Code and Receiving Photos
Sender ndash Selecting Photos Sender ndash Scanning a QR Code and Sending Photos
copy2015 Couchbase Inc lsaquorsaquo
ImplementationUses a QR code for peer discoveryUses one-time push replication to transfer photosUses digest authenticationGenerates one-time user credentialsSupports multiple platforms (eg iOS and
Android)
copy2015 Couchbase Inc lsaquorsaquo
StoryboardViewController SendViewController
ReceiveViewController
QR Code Scanner
Presents a QR code
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 1 Start a listener
listener = CBLListener(manager CBLManagersharedInstance() port 0)
listenerrequiresAuth = truelet username = secureGenerateKey(NSCharacterSetURLUserAllowedCharacterSet())let password = secureGenerateKey(NSCharacterSetURLPasswordAllowedCharacterSet())listenersetPasswords([username password])
var success = listenerstart(amperror)if (success)
syncUrl = genearteSyncURL(listenerURL username username password password dbName databasename)
startObserveDatabaseChange()
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Observe database changes
func startObserveDatabaseChange() NSNotificationCenterdefaultCenter()addObserverForName(kCBLDatabaseChangeNotification object database queue nil) (notification) -gt Void
in if let changes = notificationuserInfo[changes] as [CBLDatabaseChange] for change in changes
dispatch_async(dispatch_get_main_queue() selfsaveImageFromDocument(changedocumentID) )
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Generate and display a QR code
httpuserpasswordltlistener hostgtltportgtdb
Uses the iOS Core Image filter
copy2015 Couchbase Inc lsaquorsaquo
SendViewControllerStep 1 Scan a QR code
Uses the iOS class AVCaptureSession with the output type AVMetadataObjectTypeQRCode
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Create documents
var docIds [String] = []for asset in sharedAssets
var data = NSData(bytesNoCopy imageBytes length buffered freeWhenDone true)
let doc = databasecreateDocument()let rev = docnewRevision()revsetAttachmentNamed(photo withContentType applicationoctet-stream
content data)let saved = revsave(amperror)
if saved = nil docIdsappend(docdocumentID)
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Replicate documents
replicator = databasecreatePushReplication(url)replicatordocumentIDs = docIds
NSNotificationCenterdefaultCenter()addObserverForName(kCBLReplicationChangeNotification object replicator queue nil) (notification) -gt Void in
if selfreplicatorlastError == nil var totalCount = selfreplicatorchangesCountvar completedCount = selfreplicatorcompletedChangesCountif completedCount gt 0 ampamp completedCount == totalCount
selfstatusLabeltext = Sending Completedrdquo
else selfstatusLabeltext = Sending Abort
replicatorstart()
copy2015 Couchbase Inc lsaquorsaquo
Source Code
httpsgithubcomcouchbaselabsphoto-drop
Demo 2PhotoDrop App
The End mdash Any Questions
copy2015 Couchbase Inc lsaquorsaquo
This Is Not A Typical Auth Problem
SSL doesnrsquot helpHTTP authentication (ArArrB or BrArrC) doesnrsquot helpOnly authenticating the data helps
copy2015 Couchbase Inc lsaquorsaquo
Digital Signatures
Every user or device generates a key-pairEvery revision is signed by the party who created
itTo validate a revisionMake sure the signature is validLook up the authorrsquos public keyCompare signing key with authorrsquos key
copy2015 Couchbase Inc lsaquorsaquo
Key Distribution
Traditional StyleTrusted authority (server) signs key into a
certificateServer distributes certificate
P2P StyleDevice uses raw key or self-signed certificateUsers lsquopairrsquo devices in person
trading keys over a secure channel
Implementing Peer-to-PeerPart 3
Manual 11 Pairing
Pasin Suriyentrakorn
copy2015 Couchbase Inc lsaquorsaquo
PhotoDrop
Receiver ndash Presenting the QR Code and Receiving Photos
Sender ndash Selecting Photos Sender ndash Scanning a QR Code and Sending Photos
copy2015 Couchbase Inc lsaquorsaquo
ImplementationUses a QR code for peer discoveryUses one-time push replication to transfer photosUses digest authenticationGenerates one-time user credentialsSupports multiple platforms (eg iOS and
Android)
copy2015 Couchbase Inc lsaquorsaquo
StoryboardViewController SendViewController
ReceiveViewController
QR Code Scanner
Presents a QR code
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 1 Start a listener
listener = CBLListener(manager CBLManagersharedInstance() port 0)
listenerrequiresAuth = truelet username = secureGenerateKey(NSCharacterSetURLUserAllowedCharacterSet())let password = secureGenerateKey(NSCharacterSetURLPasswordAllowedCharacterSet())listenersetPasswords([username password])
var success = listenerstart(amperror)if (success)
syncUrl = genearteSyncURL(listenerURL username username password password dbName databasename)
startObserveDatabaseChange()
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Observe database changes
func startObserveDatabaseChange() NSNotificationCenterdefaultCenter()addObserverForName(kCBLDatabaseChangeNotification object database queue nil) (notification) -gt Void
in if let changes = notificationuserInfo[changes] as [CBLDatabaseChange] for change in changes
dispatch_async(dispatch_get_main_queue() selfsaveImageFromDocument(changedocumentID) )
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Generate and display a QR code
httpuserpasswordltlistener hostgtltportgtdb
Uses the iOS Core Image filter
copy2015 Couchbase Inc lsaquorsaquo
SendViewControllerStep 1 Scan a QR code
Uses the iOS class AVCaptureSession with the output type AVMetadataObjectTypeQRCode
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Create documents
var docIds [String] = []for asset in sharedAssets
var data = NSData(bytesNoCopy imageBytes length buffered freeWhenDone true)
let doc = databasecreateDocument()let rev = docnewRevision()revsetAttachmentNamed(photo withContentType applicationoctet-stream
content data)let saved = revsave(amperror)
if saved = nil docIdsappend(docdocumentID)
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Replicate documents
replicator = databasecreatePushReplication(url)replicatordocumentIDs = docIds
NSNotificationCenterdefaultCenter()addObserverForName(kCBLReplicationChangeNotification object replicator queue nil) (notification) -gt Void in
if selfreplicatorlastError == nil var totalCount = selfreplicatorchangesCountvar completedCount = selfreplicatorcompletedChangesCountif completedCount gt 0 ampamp completedCount == totalCount
selfstatusLabeltext = Sending Completedrdquo
else selfstatusLabeltext = Sending Abort
replicatorstart()
copy2015 Couchbase Inc lsaquorsaquo
Source Code
httpsgithubcomcouchbaselabsphoto-drop
Demo 2PhotoDrop App
The End mdash Any Questions
copy2015 Couchbase Inc lsaquorsaquo
Digital Signatures
Every user or device generates a key-pairEvery revision is signed by the party who created
itTo validate a revisionMake sure the signature is validLook up the authorrsquos public keyCompare signing key with authorrsquos key
copy2015 Couchbase Inc lsaquorsaquo
Key Distribution
Traditional StyleTrusted authority (server) signs key into a
certificateServer distributes certificate
P2P StyleDevice uses raw key or self-signed certificateUsers lsquopairrsquo devices in person
trading keys over a secure channel
Implementing Peer-to-PeerPart 3
Manual 11 Pairing
Pasin Suriyentrakorn
copy2015 Couchbase Inc lsaquorsaquo
PhotoDrop
Receiver ndash Presenting the QR Code and Receiving Photos
Sender ndash Selecting Photos Sender ndash Scanning a QR Code and Sending Photos
copy2015 Couchbase Inc lsaquorsaquo
ImplementationUses a QR code for peer discoveryUses one-time push replication to transfer photosUses digest authenticationGenerates one-time user credentialsSupports multiple platforms (eg iOS and
Android)
copy2015 Couchbase Inc lsaquorsaquo
StoryboardViewController SendViewController
ReceiveViewController
QR Code Scanner
Presents a QR code
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 1 Start a listener
listener = CBLListener(manager CBLManagersharedInstance() port 0)
listenerrequiresAuth = truelet username = secureGenerateKey(NSCharacterSetURLUserAllowedCharacterSet())let password = secureGenerateKey(NSCharacterSetURLPasswordAllowedCharacterSet())listenersetPasswords([username password])
var success = listenerstart(amperror)if (success)
syncUrl = genearteSyncURL(listenerURL username username password password dbName databasename)
startObserveDatabaseChange()
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Observe database changes
func startObserveDatabaseChange() NSNotificationCenterdefaultCenter()addObserverForName(kCBLDatabaseChangeNotification object database queue nil) (notification) -gt Void
in if let changes = notificationuserInfo[changes] as [CBLDatabaseChange] for change in changes
dispatch_async(dispatch_get_main_queue() selfsaveImageFromDocument(changedocumentID) )
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Generate and display a QR code
httpuserpasswordltlistener hostgtltportgtdb
Uses the iOS Core Image filter
copy2015 Couchbase Inc lsaquorsaquo
SendViewControllerStep 1 Scan a QR code
Uses the iOS class AVCaptureSession with the output type AVMetadataObjectTypeQRCode
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Create documents
var docIds [String] = []for asset in sharedAssets
var data = NSData(bytesNoCopy imageBytes length buffered freeWhenDone true)
let doc = databasecreateDocument()let rev = docnewRevision()revsetAttachmentNamed(photo withContentType applicationoctet-stream
content data)let saved = revsave(amperror)
if saved = nil docIdsappend(docdocumentID)
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Replicate documents
replicator = databasecreatePushReplication(url)replicatordocumentIDs = docIds
NSNotificationCenterdefaultCenter()addObserverForName(kCBLReplicationChangeNotification object replicator queue nil) (notification) -gt Void in
if selfreplicatorlastError == nil var totalCount = selfreplicatorchangesCountvar completedCount = selfreplicatorcompletedChangesCountif completedCount gt 0 ampamp completedCount == totalCount
selfstatusLabeltext = Sending Completedrdquo
else selfstatusLabeltext = Sending Abort
replicatorstart()
copy2015 Couchbase Inc lsaquorsaquo
Source Code
httpsgithubcomcouchbaselabsphoto-drop
Demo 2PhotoDrop App
The End mdash Any Questions
copy2015 Couchbase Inc lsaquorsaquo
Key Distribution
Traditional StyleTrusted authority (server) signs key into a
certificateServer distributes certificate
P2P StyleDevice uses raw key or self-signed certificateUsers lsquopairrsquo devices in person
trading keys over a secure channel
Implementing Peer-to-PeerPart 3
Manual 11 Pairing
Pasin Suriyentrakorn
copy2015 Couchbase Inc lsaquorsaquo
PhotoDrop
Receiver ndash Presenting the QR Code and Receiving Photos
Sender ndash Selecting Photos Sender ndash Scanning a QR Code and Sending Photos
copy2015 Couchbase Inc lsaquorsaquo
ImplementationUses a QR code for peer discoveryUses one-time push replication to transfer photosUses digest authenticationGenerates one-time user credentialsSupports multiple platforms (eg iOS and
Android)
copy2015 Couchbase Inc lsaquorsaquo
StoryboardViewController SendViewController
ReceiveViewController
QR Code Scanner
Presents a QR code
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 1 Start a listener
listener = CBLListener(manager CBLManagersharedInstance() port 0)
listenerrequiresAuth = truelet username = secureGenerateKey(NSCharacterSetURLUserAllowedCharacterSet())let password = secureGenerateKey(NSCharacterSetURLPasswordAllowedCharacterSet())listenersetPasswords([username password])
var success = listenerstart(amperror)if (success)
syncUrl = genearteSyncURL(listenerURL username username password password dbName databasename)
startObserveDatabaseChange()
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Observe database changes
func startObserveDatabaseChange() NSNotificationCenterdefaultCenter()addObserverForName(kCBLDatabaseChangeNotification object database queue nil) (notification) -gt Void
in if let changes = notificationuserInfo[changes] as [CBLDatabaseChange] for change in changes
dispatch_async(dispatch_get_main_queue() selfsaveImageFromDocument(changedocumentID) )
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Generate and display a QR code
httpuserpasswordltlistener hostgtltportgtdb
Uses the iOS Core Image filter
copy2015 Couchbase Inc lsaquorsaquo
SendViewControllerStep 1 Scan a QR code
Uses the iOS class AVCaptureSession with the output type AVMetadataObjectTypeQRCode
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Create documents
var docIds [String] = []for asset in sharedAssets
var data = NSData(bytesNoCopy imageBytes length buffered freeWhenDone true)
let doc = databasecreateDocument()let rev = docnewRevision()revsetAttachmentNamed(photo withContentType applicationoctet-stream
content data)let saved = revsave(amperror)
if saved = nil docIdsappend(docdocumentID)
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Replicate documents
replicator = databasecreatePushReplication(url)replicatordocumentIDs = docIds
NSNotificationCenterdefaultCenter()addObserverForName(kCBLReplicationChangeNotification object replicator queue nil) (notification) -gt Void in
if selfreplicatorlastError == nil var totalCount = selfreplicatorchangesCountvar completedCount = selfreplicatorcompletedChangesCountif completedCount gt 0 ampamp completedCount == totalCount
selfstatusLabeltext = Sending Completedrdquo
else selfstatusLabeltext = Sending Abort
replicatorstart()
copy2015 Couchbase Inc lsaquorsaquo
Source Code
httpsgithubcomcouchbaselabsphoto-drop
Demo 2PhotoDrop App
The End mdash Any Questions
Implementing Peer-to-PeerPart 3
Manual 11 Pairing
Pasin Suriyentrakorn
copy2015 Couchbase Inc lsaquorsaquo
PhotoDrop
Receiver ndash Presenting the QR Code and Receiving Photos
Sender ndash Selecting Photos Sender ndash Scanning a QR Code and Sending Photos
copy2015 Couchbase Inc lsaquorsaquo
ImplementationUses a QR code for peer discoveryUses one-time push replication to transfer photosUses digest authenticationGenerates one-time user credentialsSupports multiple platforms (eg iOS and
Android)
copy2015 Couchbase Inc lsaquorsaquo
StoryboardViewController SendViewController
ReceiveViewController
QR Code Scanner
Presents a QR code
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 1 Start a listener
listener = CBLListener(manager CBLManagersharedInstance() port 0)
listenerrequiresAuth = truelet username = secureGenerateKey(NSCharacterSetURLUserAllowedCharacterSet())let password = secureGenerateKey(NSCharacterSetURLPasswordAllowedCharacterSet())listenersetPasswords([username password])
var success = listenerstart(amperror)if (success)
syncUrl = genearteSyncURL(listenerURL username username password password dbName databasename)
startObserveDatabaseChange()
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Observe database changes
func startObserveDatabaseChange() NSNotificationCenterdefaultCenter()addObserverForName(kCBLDatabaseChangeNotification object database queue nil) (notification) -gt Void
in if let changes = notificationuserInfo[changes] as [CBLDatabaseChange] for change in changes
dispatch_async(dispatch_get_main_queue() selfsaveImageFromDocument(changedocumentID) )
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Generate and display a QR code
httpuserpasswordltlistener hostgtltportgtdb
Uses the iOS Core Image filter
copy2015 Couchbase Inc lsaquorsaquo
SendViewControllerStep 1 Scan a QR code
Uses the iOS class AVCaptureSession with the output type AVMetadataObjectTypeQRCode
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Create documents
var docIds [String] = []for asset in sharedAssets
var data = NSData(bytesNoCopy imageBytes length buffered freeWhenDone true)
let doc = databasecreateDocument()let rev = docnewRevision()revsetAttachmentNamed(photo withContentType applicationoctet-stream
content data)let saved = revsave(amperror)
if saved = nil docIdsappend(docdocumentID)
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Replicate documents
replicator = databasecreatePushReplication(url)replicatordocumentIDs = docIds
NSNotificationCenterdefaultCenter()addObserverForName(kCBLReplicationChangeNotification object replicator queue nil) (notification) -gt Void in
if selfreplicatorlastError == nil var totalCount = selfreplicatorchangesCountvar completedCount = selfreplicatorcompletedChangesCountif completedCount gt 0 ampamp completedCount == totalCount
selfstatusLabeltext = Sending Completedrdquo
else selfstatusLabeltext = Sending Abort
replicatorstart()
copy2015 Couchbase Inc lsaquorsaquo
Source Code
httpsgithubcomcouchbaselabsphoto-drop
Demo 2PhotoDrop App
The End mdash Any Questions
copy2015 Couchbase Inc lsaquorsaquo
PhotoDrop
Receiver ndash Presenting the QR Code and Receiving Photos
Sender ndash Selecting Photos Sender ndash Scanning a QR Code and Sending Photos
copy2015 Couchbase Inc lsaquorsaquo
ImplementationUses a QR code for peer discoveryUses one-time push replication to transfer photosUses digest authenticationGenerates one-time user credentialsSupports multiple platforms (eg iOS and
Android)
copy2015 Couchbase Inc lsaquorsaquo
StoryboardViewController SendViewController
ReceiveViewController
QR Code Scanner
Presents a QR code
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 1 Start a listener
listener = CBLListener(manager CBLManagersharedInstance() port 0)
listenerrequiresAuth = truelet username = secureGenerateKey(NSCharacterSetURLUserAllowedCharacterSet())let password = secureGenerateKey(NSCharacterSetURLPasswordAllowedCharacterSet())listenersetPasswords([username password])
var success = listenerstart(amperror)if (success)
syncUrl = genearteSyncURL(listenerURL username username password password dbName databasename)
startObserveDatabaseChange()
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Observe database changes
func startObserveDatabaseChange() NSNotificationCenterdefaultCenter()addObserverForName(kCBLDatabaseChangeNotification object database queue nil) (notification) -gt Void
in if let changes = notificationuserInfo[changes] as [CBLDatabaseChange] for change in changes
dispatch_async(dispatch_get_main_queue() selfsaveImageFromDocument(changedocumentID) )
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Generate and display a QR code
httpuserpasswordltlistener hostgtltportgtdb
Uses the iOS Core Image filter
copy2015 Couchbase Inc lsaquorsaquo
SendViewControllerStep 1 Scan a QR code
Uses the iOS class AVCaptureSession with the output type AVMetadataObjectTypeQRCode
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Create documents
var docIds [String] = []for asset in sharedAssets
var data = NSData(bytesNoCopy imageBytes length buffered freeWhenDone true)
let doc = databasecreateDocument()let rev = docnewRevision()revsetAttachmentNamed(photo withContentType applicationoctet-stream
content data)let saved = revsave(amperror)
if saved = nil docIdsappend(docdocumentID)
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Replicate documents
replicator = databasecreatePushReplication(url)replicatordocumentIDs = docIds
NSNotificationCenterdefaultCenter()addObserverForName(kCBLReplicationChangeNotification object replicator queue nil) (notification) -gt Void in
if selfreplicatorlastError == nil var totalCount = selfreplicatorchangesCountvar completedCount = selfreplicatorcompletedChangesCountif completedCount gt 0 ampamp completedCount == totalCount
selfstatusLabeltext = Sending Completedrdquo
else selfstatusLabeltext = Sending Abort
replicatorstart()
copy2015 Couchbase Inc lsaquorsaquo
Source Code
httpsgithubcomcouchbaselabsphoto-drop
Demo 2PhotoDrop App
The End mdash Any Questions
copy2015 Couchbase Inc lsaquorsaquo
ImplementationUses a QR code for peer discoveryUses one-time push replication to transfer photosUses digest authenticationGenerates one-time user credentialsSupports multiple platforms (eg iOS and
Android)
copy2015 Couchbase Inc lsaquorsaquo
StoryboardViewController SendViewController
ReceiveViewController
QR Code Scanner
Presents a QR code
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 1 Start a listener
listener = CBLListener(manager CBLManagersharedInstance() port 0)
listenerrequiresAuth = truelet username = secureGenerateKey(NSCharacterSetURLUserAllowedCharacterSet())let password = secureGenerateKey(NSCharacterSetURLPasswordAllowedCharacterSet())listenersetPasswords([username password])
var success = listenerstart(amperror)if (success)
syncUrl = genearteSyncURL(listenerURL username username password password dbName databasename)
startObserveDatabaseChange()
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Observe database changes
func startObserveDatabaseChange() NSNotificationCenterdefaultCenter()addObserverForName(kCBLDatabaseChangeNotification object database queue nil) (notification) -gt Void
in if let changes = notificationuserInfo[changes] as [CBLDatabaseChange] for change in changes
dispatch_async(dispatch_get_main_queue() selfsaveImageFromDocument(changedocumentID) )
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Generate and display a QR code
httpuserpasswordltlistener hostgtltportgtdb
Uses the iOS Core Image filter
copy2015 Couchbase Inc lsaquorsaquo
SendViewControllerStep 1 Scan a QR code
Uses the iOS class AVCaptureSession with the output type AVMetadataObjectTypeQRCode
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Create documents
var docIds [String] = []for asset in sharedAssets
var data = NSData(bytesNoCopy imageBytes length buffered freeWhenDone true)
let doc = databasecreateDocument()let rev = docnewRevision()revsetAttachmentNamed(photo withContentType applicationoctet-stream
content data)let saved = revsave(amperror)
if saved = nil docIdsappend(docdocumentID)
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Replicate documents
replicator = databasecreatePushReplication(url)replicatordocumentIDs = docIds
NSNotificationCenterdefaultCenter()addObserverForName(kCBLReplicationChangeNotification object replicator queue nil) (notification) -gt Void in
if selfreplicatorlastError == nil var totalCount = selfreplicatorchangesCountvar completedCount = selfreplicatorcompletedChangesCountif completedCount gt 0 ampamp completedCount == totalCount
selfstatusLabeltext = Sending Completedrdquo
else selfstatusLabeltext = Sending Abort
replicatorstart()
copy2015 Couchbase Inc lsaquorsaquo
Source Code
httpsgithubcomcouchbaselabsphoto-drop
Demo 2PhotoDrop App
The End mdash Any Questions
copy2015 Couchbase Inc lsaquorsaquo
StoryboardViewController SendViewController
ReceiveViewController
QR Code Scanner
Presents a QR code
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 1 Start a listener
listener = CBLListener(manager CBLManagersharedInstance() port 0)
listenerrequiresAuth = truelet username = secureGenerateKey(NSCharacterSetURLUserAllowedCharacterSet())let password = secureGenerateKey(NSCharacterSetURLPasswordAllowedCharacterSet())listenersetPasswords([username password])
var success = listenerstart(amperror)if (success)
syncUrl = genearteSyncURL(listenerURL username username password password dbName databasename)
startObserveDatabaseChange()
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Observe database changes
func startObserveDatabaseChange() NSNotificationCenterdefaultCenter()addObserverForName(kCBLDatabaseChangeNotification object database queue nil) (notification) -gt Void
in if let changes = notificationuserInfo[changes] as [CBLDatabaseChange] for change in changes
dispatch_async(dispatch_get_main_queue() selfsaveImageFromDocument(changedocumentID) )
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Generate and display a QR code
httpuserpasswordltlistener hostgtltportgtdb
Uses the iOS Core Image filter
copy2015 Couchbase Inc lsaquorsaquo
SendViewControllerStep 1 Scan a QR code
Uses the iOS class AVCaptureSession with the output type AVMetadataObjectTypeQRCode
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Create documents
var docIds [String] = []for asset in sharedAssets
var data = NSData(bytesNoCopy imageBytes length buffered freeWhenDone true)
let doc = databasecreateDocument()let rev = docnewRevision()revsetAttachmentNamed(photo withContentType applicationoctet-stream
content data)let saved = revsave(amperror)
if saved = nil docIdsappend(docdocumentID)
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Replicate documents
replicator = databasecreatePushReplication(url)replicatordocumentIDs = docIds
NSNotificationCenterdefaultCenter()addObserverForName(kCBLReplicationChangeNotification object replicator queue nil) (notification) -gt Void in
if selfreplicatorlastError == nil var totalCount = selfreplicatorchangesCountvar completedCount = selfreplicatorcompletedChangesCountif completedCount gt 0 ampamp completedCount == totalCount
selfstatusLabeltext = Sending Completedrdquo
else selfstatusLabeltext = Sending Abort
replicatorstart()
copy2015 Couchbase Inc lsaquorsaquo
Source Code
httpsgithubcomcouchbaselabsphoto-drop
Demo 2PhotoDrop App
The End mdash Any Questions
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 1 Start a listener
listener = CBLListener(manager CBLManagersharedInstance() port 0)
listenerrequiresAuth = truelet username = secureGenerateKey(NSCharacterSetURLUserAllowedCharacterSet())let password = secureGenerateKey(NSCharacterSetURLPasswordAllowedCharacterSet())listenersetPasswords([username password])
var success = listenerstart(amperror)if (success)
syncUrl = genearteSyncURL(listenerURL username username password password dbName databasename)
startObserveDatabaseChange()
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Observe database changes
func startObserveDatabaseChange() NSNotificationCenterdefaultCenter()addObserverForName(kCBLDatabaseChangeNotification object database queue nil) (notification) -gt Void
in if let changes = notificationuserInfo[changes] as [CBLDatabaseChange] for change in changes
dispatch_async(dispatch_get_main_queue() selfsaveImageFromDocument(changedocumentID) )
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Generate and display a QR code
httpuserpasswordltlistener hostgtltportgtdb
Uses the iOS Core Image filter
copy2015 Couchbase Inc lsaquorsaquo
SendViewControllerStep 1 Scan a QR code
Uses the iOS class AVCaptureSession with the output type AVMetadataObjectTypeQRCode
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Create documents
var docIds [String] = []for asset in sharedAssets
var data = NSData(bytesNoCopy imageBytes length buffered freeWhenDone true)
let doc = databasecreateDocument()let rev = docnewRevision()revsetAttachmentNamed(photo withContentType applicationoctet-stream
content data)let saved = revsave(amperror)
if saved = nil docIdsappend(docdocumentID)
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Replicate documents
replicator = databasecreatePushReplication(url)replicatordocumentIDs = docIds
NSNotificationCenterdefaultCenter()addObserverForName(kCBLReplicationChangeNotification object replicator queue nil) (notification) -gt Void in
if selfreplicatorlastError == nil var totalCount = selfreplicatorchangesCountvar completedCount = selfreplicatorcompletedChangesCountif completedCount gt 0 ampamp completedCount == totalCount
selfstatusLabeltext = Sending Completedrdquo
else selfstatusLabeltext = Sending Abort
replicatorstart()
copy2015 Couchbase Inc lsaquorsaquo
Source Code
httpsgithubcomcouchbaselabsphoto-drop
Demo 2PhotoDrop App
The End mdash Any Questions
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Observe database changes
func startObserveDatabaseChange() NSNotificationCenterdefaultCenter()addObserverForName(kCBLDatabaseChangeNotification object database queue nil) (notification) -gt Void
in if let changes = notificationuserInfo[changes] as [CBLDatabaseChange] for change in changes
dispatch_async(dispatch_get_main_queue() selfsaveImageFromDocument(changedocumentID) )
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Generate and display a QR code
httpuserpasswordltlistener hostgtltportgtdb
Uses the iOS Core Image filter
copy2015 Couchbase Inc lsaquorsaquo
SendViewControllerStep 1 Scan a QR code
Uses the iOS class AVCaptureSession with the output type AVMetadataObjectTypeQRCode
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Create documents
var docIds [String] = []for asset in sharedAssets
var data = NSData(bytesNoCopy imageBytes length buffered freeWhenDone true)
let doc = databasecreateDocument()let rev = docnewRevision()revsetAttachmentNamed(photo withContentType applicationoctet-stream
content data)let saved = revsave(amperror)
if saved = nil docIdsappend(docdocumentID)
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Replicate documents
replicator = databasecreatePushReplication(url)replicatordocumentIDs = docIds
NSNotificationCenterdefaultCenter()addObserverForName(kCBLReplicationChangeNotification object replicator queue nil) (notification) -gt Void in
if selfreplicatorlastError == nil var totalCount = selfreplicatorchangesCountvar completedCount = selfreplicatorcompletedChangesCountif completedCount gt 0 ampamp completedCount == totalCount
selfstatusLabeltext = Sending Completedrdquo
else selfstatusLabeltext = Sending Abort
replicatorstart()
copy2015 Couchbase Inc lsaquorsaquo
Source Code
httpsgithubcomcouchbaselabsphoto-drop
Demo 2PhotoDrop App
The End mdash Any Questions
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Generate and display a QR code
httpuserpasswordltlistener hostgtltportgtdb
Uses the iOS Core Image filter
copy2015 Couchbase Inc lsaquorsaquo
SendViewControllerStep 1 Scan a QR code
Uses the iOS class AVCaptureSession with the output type AVMetadataObjectTypeQRCode
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Create documents
var docIds [String] = []for asset in sharedAssets
var data = NSData(bytesNoCopy imageBytes length buffered freeWhenDone true)
let doc = databasecreateDocument()let rev = docnewRevision()revsetAttachmentNamed(photo withContentType applicationoctet-stream
content data)let saved = revsave(amperror)
if saved = nil docIdsappend(docdocumentID)
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Replicate documents
replicator = databasecreatePushReplication(url)replicatordocumentIDs = docIds
NSNotificationCenterdefaultCenter()addObserverForName(kCBLReplicationChangeNotification object replicator queue nil) (notification) -gt Void in
if selfreplicatorlastError == nil var totalCount = selfreplicatorchangesCountvar completedCount = selfreplicatorcompletedChangesCountif completedCount gt 0 ampamp completedCount == totalCount
selfstatusLabeltext = Sending Completedrdquo
else selfstatusLabeltext = Sending Abort
replicatorstart()
copy2015 Couchbase Inc lsaquorsaquo
Source Code
httpsgithubcomcouchbaselabsphoto-drop
Demo 2PhotoDrop App
The End mdash Any Questions
copy2015 Couchbase Inc lsaquorsaquo
SendViewControllerStep 1 Scan a QR code
Uses the iOS class AVCaptureSession with the output type AVMetadataObjectTypeQRCode
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Create documents
var docIds [String] = []for asset in sharedAssets
var data = NSData(bytesNoCopy imageBytes length buffered freeWhenDone true)
let doc = databasecreateDocument()let rev = docnewRevision()revsetAttachmentNamed(photo withContentType applicationoctet-stream
content data)let saved = revsave(amperror)
if saved = nil docIdsappend(docdocumentID)
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Replicate documents
replicator = databasecreatePushReplication(url)replicatordocumentIDs = docIds
NSNotificationCenterdefaultCenter()addObserverForName(kCBLReplicationChangeNotification object replicator queue nil) (notification) -gt Void in
if selfreplicatorlastError == nil var totalCount = selfreplicatorchangesCountvar completedCount = selfreplicatorcompletedChangesCountif completedCount gt 0 ampamp completedCount == totalCount
selfstatusLabeltext = Sending Completedrdquo
else selfstatusLabeltext = Sending Abort
replicatorstart()
copy2015 Couchbase Inc lsaquorsaquo
Source Code
httpsgithubcomcouchbaselabsphoto-drop
Demo 2PhotoDrop App
The End mdash Any Questions
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 2 Create documents
var docIds [String] = []for asset in sharedAssets
var data = NSData(bytesNoCopy imageBytes length buffered freeWhenDone true)
let doc = databasecreateDocument()let rev = docnewRevision()revsetAttachmentNamed(photo withContentType applicationoctet-stream
content data)let saved = revsave(amperror)
if saved = nil docIdsappend(docdocumentID)
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Replicate documents
replicator = databasecreatePushReplication(url)replicatordocumentIDs = docIds
NSNotificationCenterdefaultCenter()addObserverForName(kCBLReplicationChangeNotification object replicator queue nil) (notification) -gt Void in
if selfreplicatorlastError == nil var totalCount = selfreplicatorchangesCountvar completedCount = selfreplicatorcompletedChangesCountif completedCount gt 0 ampamp completedCount == totalCount
selfstatusLabeltext = Sending Completedrdquo
else selfstatusLabeltext = Sending Abort
replicatorstart()
copy2015 Couchbase Inc lsaquorsaquo
Source Code
httpsgithubcomcouchbaselabsphoto-drop
Demo 2PhotoDrop App
The End mdash Any Questions
copy2015 Couchbase Inc lsaquorsaquo
ReceiveViewControllerStep 3 Replicate documents
replicator = databasecreatePushReplication(url)replicatordocumentIDs = docIds
NSNotificationCenterdefaultCenter()addObserverForName(kCBLReplicationChangeNotification object replicator queue nil) (notification) -gt Void in
if selfreplicatorlastError == nil var totalCount = selfreplicatorchangesCountvar completedCount = selfreplicatorcompletedChangesCountif completedCount gt 0 ampamp completedCount == totalCount
selfstatusLabeltext = Sending Completedrdquo
else selfstatusLabeltext = Sending Abort
replicatorstart()
copy2015 Couchbase Inc lsaquorsaquo
Source Code
httpsgithubcomcouchbaselabsphoto-drop
Demo 2PhotoDrop App
The End mdash Any Questions
copy2015 Couchbase Inc lsaquorsaquo
Source Code
httpsgithubcomcouchbaselabsphoto-drop
Demo 2PhotoDrop App
The End mdash Any Questions
Demo 2PhotoDrop App
The End mdash Any Questions
The End mdash Any Questions