def __init__(self, prefixstr): self.handle = CCN() #XXX: temporary, until we allow fetching key from key storage self.key = self.handle.getDefaultKey() self.keylocator = KeyLocator(self.key) self.prefix = Name(prefixstr)
def __init__(self, *args, **kwargs): ''' Creates a socket. As of now, we try to get the ccnx key from the default location ''' super(CcnxSocket, self).__init__() self.ccnx_key = CCN.getDefaultKey() self.ccnx_key_locator = pyccn.KeyLocator(self.ccnx_key) self.ccnx_handle = CCN() self.event_loop = CcnxLoop(self.ccnx_handle)
def __init__(self, configFileName): self.appConfigFileName = configFileName self.loadConfigFile() self.handle = CCN() self.getApplicationKey() #nameCrypto self.state = NameCrypto.new_state() self.cryptoKey = NameCrypto.generate_application_key(self.cfg.fixtureKey, self.cfg.appName)
def __init__(self, prefixstr ): self.handle = CCN() #XXX: temporary, until we allow fetching key from key storage self.key = self.handle.getDefaultKey() self.keylocator = KeyLocator(self.key) self.prefix = Name(prefixstr)
def __init__(self, base_name, callback, handle=CCN.CCN(), version=None, latest=True): # some constants self.version_marker = '\xfd' self.first_version_marker = self.version_marker self.last_version_marker = '\xfe\x00\x00\x00\x00\x00\x00' self.base_name = Name.Name(base_name) self.callback = callback self.handle = handle self.latest_version = version if version else self.first_version_marker self.start_with_latest = latest
class sequencer(Closure): #ensure singleton _instance = None def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = super(sequencer, cls).__new__(cls, *args, **kwargs) return cls._instance def __init__(self, configFileName): self.appConfigFileName = configFileName self.loadConfigFile() self.handle = CCN() self.getApplicationKey() #nameCrypto self.state = NameCrypto.new_state() self.cryptoKey = NameCrypto.generate_application_key(self.cfg.fixtureKey, self.cfg.appName) def loadConfigFile(self): command = "import "+self.appConfigFileName+" as appCfg" exec(command) self.appCfg = appCfg; self.cfg = appCfg; def getApplicationKey(self): print("getting application key for "+self.appCfg.appName) key = Key() keyFile = self.appCfg.keyFile key.fromPEM(filename=keyFile) self.appKey = key self.key = key def start(self): print "starting "+self.cfg.appName #self.allWhite() #self.allBlack() #self.spazz() def spazz(self): for i in range(1,500000): self.allWhite() self.allBlack() def allWhite(self): for d in self.cfg.names: if d['name'] != "incandescent": print d['name'] self.buildAndSendInterest(d['name'],255,255,255) def allBlack(self): for d in self.cfg.names: if d['name'] != "incandescent": print d['name'] self.buildAndSendInterest(d['name'],0,0,0) def sendAllLights(self,r,g,b): for d in self.cfg.names: if d['name'] != "incandescent": self.buildAndSendInterest(d['name'],r,g,b) return def hx(self, inum): num = hex(inum)[2:] if (len(num) == 1): num = '0'+num #print num return str(num) def buildAndSendInterest(self,device,r,g,b): rx = self.hx(r) gx = self.hx(g) bx = self.hx(b) CLI = device+"/setRGB/"+rx+gx+bx #print CLI self.sendSignedInterest(CLI) def sendInterest(self,command): n = Name.Name(self.cfg.appPrefix) print("\nInterest espressing for "+str(n)) n += command i = Interest.Interest() print("Interest sending to "+str(n)) co = self.handle.get(n,i,20) if not not co: #if co is not empty, print result for debugging print("content: "+str(co.content)) pass def sendSignedInterest(self,command): fullURI = self.cfg.appPrefix + command #print fullURI i = Interest() #build keyLocator to append to interest for NameCrypto on upcall keyLoc = pyccn.KeyLocator(self.key) keyLocStr = _pyccn.dump_charbuf(keyLoc.ccn_data) nameAndKeyLoc = Name(str(fullURI)) #print("there are "+str(len(nameAndKeyLoc))+" components") nameAndKeyLoc += keyLocStr #print("there are "+str(len(nameAndKeyLoc))+" components after adding keyLocStr") t0 = time() authName = NameCrypto.authenticate_command(self.state, nameAndKeyLoc, self.cfg.appName, self.cryptoKey) t1 = time() #print "elapsed sign", t1-t0 #print authName.components t0 = time() co = self.handle.expressInterest(authName,self) t1 = time()
class TyzxServer(Closure): def __init__(self, prefixstr): self.handle = CCN() #XXX: temporary, until we allow fetching key from key storage self.key = self.handle.getDefaultKey() self.keylocator = KeyLocator(self.key) self.prefix = Name(prefixstr) # member_name = Name.Name(self.members_uri) # member_name.appendKeyID(fix_digest(self.key.publicKeyID)) # self.member_message = self.publish(member_name, nick) def listen(self): #listen to requests in namespace self.handle.setInterestFilter(self.prefix, self) self.handle.run(-1) def publish(self, name, content): # Name #print name # SignedInfo si = pyccn.SignedInfo() #si.type = pyccn.CCN_CONTENT_DATA si.type = 0x0C04C0 # content type si.finalBlockID = b'\x00' si.publisherPublicKeyDigest = self.key.publicKeyID si.keyLocator = self.keylocator si.freshnessSeconds = FRESHNESS_SECONDS # ContentObject co = ContentObject() co.content = content co.name = name co.signedInfo = si co.sign(self.key) return co def upcall(self, kind, upcallInfo): global lasttime if lasttime is None: # can't answer yet return pyccn.RESULT_OK if len(tyzxObjs.objs) < 1: return pyccn.RESULT_OK interest = upcallInfo.Interest #print "Interest", interest.name, time.time() # CALL content matches interest to check exclusion on versions # #print interest.exclude name = interest.name #print name if name == self.prefix: # root #print "Request for root: %s" % str(name) if interest.exclude is None: freshids = tyzxObjs.objs.keys()[0:1] else: if len(interest.exclude.components) > 0: ids = set(tyzxObjs.objs.keys()) # new stuff we have suffixes = set( [int(str(s)[1:]) for s in interest.exclude.components]) freshids = list(ids.difference( suffixes)) # do we need this conversion? #print "ids", ids #print "suffixes", suffixes #print "freshids", freshids else: freshids = tyzxObjs.objs.keys()[0:1] if len(freshids) > 0: child = freshids[0] else: return pyccn.RESULT_OK # no new content else: # should check what we're receiving! take next component child = int( name.components[-1:][0]) # why not be able to do this on name? #print "Request for child: %s" % child, time.time() #print "child - ", child if tyzxObjs.objs.has_key(child): O = tyzxObjs.objs[child] else: # Don't want to respond with a nonexistent. NDN way is to not answer interest. # If we've just started, we may not even know what the content store knows. # But, we do want to answer "exits" that we know about. #print "child", child, "is not present" if tyzxObjs.objExits.has_key(child): #print "child", child, "is exited" O = tyzxObjs.objExits[child] else: return pyccn.RESULT_OK #O = CompositeObject(BaseObject()) #O.time = lasttime.time #O.id = int(child) #O.status = "nonexistent" msgname = Name(self.prefix) msgname += str(child) msgname.components.append(versionFromTime( O.time)) # should have msgname.append #msgname.ccn_data_dirty=True - now handled within PyCCN # need binary add component self.message = self.publish(msgname, O.toJSON()) #print "Publishing", msgname, O.toJSON() #print "Present:", tyzxObjs.objs.keys(), time.time() self.handle.put(self.message) return pyccn.RESULT_INTEREST_CONSUMED return pyccn.RESULT_OK
locator1 = _pyccn.KeyLocator_to_ccn(name=ccn_name1) print(locator1) locator1_obj = _pyccn.KeyLocator_obj_from_ccn(locator1) print(locator1_obj) print(locator1_obj.keyName) name2 = _pyccn.name_comps_from_ccn(locator1_obj.keyName.ccn_data) print(name2) for comp1, comp2 in zip(name1, name2): if comp1 != comp2: raise AssertionError("Got a different output: '%s' != '%s'" % (comp1, comp2)) key1 = CCN.getDefaultKey() locator2 = _pyccn.KeyLocator_to_ccn(key=key1.ccn_data_public) print(locator2) locator2_obj = _pyccn.KeyLocator_obj_from_ccn(locator2) key2 = locator2_obj.key print(key2) print(key1.ccn_data_public) print(key2.ccn_data_public) assert(key1.publicToDER() == key2.publicToDER()) del key2 key2 = _pyccn.Key_obj_from_ccn(key1.ccn_data_private)
from pyccn import CCN, Name, Interest, Closure from time import sleep worked = False class MyClosure(Closure): def upcall(self, kind, upcallInfo): global worked print("Got response") print(kind) print(upcallInfo) worked = True n = Name("ccnx:/ccnx/ping") i = Interest() closure = MyClosure() c = CCN() res = c.expressInterest(n, closure, i) print(res) #causes crashes c.run(10) print("Ha!") assert(worked)
class sequencer(Closure): def __init__(self, configFileName): self.appConfigFileName = configFileName self.loadConfigFile() self.handle = CCN() self.getApplicationKey() #nameCrypto self.state = NameCrypto.new_state() self.cryptoKey = NameCrypto.generate_application_key(self.cfg.fixtureKey, self.cfg.appName) self.count = 0 def loadConfigFile(self): command = "import "+self.appConfigFileName+" as appCfg" exec(command) self.appCfg = appCfg; self.cfg = appCfg; def getApplicationKey(self): #print("getting application key for "+self.appCfg.appName) key = Key() keyFile = self.appCfg.keyFile key.fromPEM(filename=keyFile) self.appKey = key self.key = key def start(self): #print "starting "+self.cfg.appName self.startTime = time.time() #self.play() #self.send() #self.discoProfile() #self.disco() #self.mobileDisco() #self.discoArt() #self.allWhite() self.allBlack() #self.spazz() def spazz(self): for i in range(1,500000): self.allWhite() self.allBlack() def allWhite(self): for d in self.cfg.names: if d['name'] != "incandescent": print d['name'] self.buildAndSendInterest(d['name'],255,255,255) def allBlack(self): for d in self.cfg.names: if d['name'] != "incandescent": print d['name'] self.buildAndSendInterest(d['name'],0,0,0) self.buildAndSendArtInterest('incandescent',0,) def disco(self): print "fading..." for d in self.cfg.names: if d['name'] != "incandescent": print d['name'] r = b = g = 0 #red for i in range(0,85): r=i self.buildAndSendInterest(d['name'],r*3,g*3,b*3) for i in range(0,85): r=0 g=i self.buildAndSendInterest(d['name'],r*3,g*3,b*3) for i in range(0,85): g=0 b=i self.buildAndSendInterest(d['name'],r*3,g*3,b*3) self.buildAndSendInterest(d['name'],0,0,0) self.buildAndSendInterest(d['name'],255,255,255) self.buildAndSendInterest(d['name'],0,0,0) self.buildAndSendInterest(d['name'],255,255,255) self.buildAndSendInterest(d['name'],0,0,0) self.buildAndSendInterest(d['name'],0,0,0) return def discoProfile(self): print "fading..." for d in self.cfg.names: if d['name'] != "incandescent": print d['name'] r = b = g = 0 #red for i in range(0,85): r=i self.buildAndSendInterest(d['name'],r*3,g*3,b*3) for i in range(0,85): r=0 g=i self.buildAndSendInterest(d['name'],r*3,g*3,b*3) for i in range(0,85): g=0 b=i self.buildAndSendInterest(d['name'],r*3,g*3,b*3) self.buildAndSendInterest(d['name'],0,0,0) self.buildAndSendInterest(d['name'],255,255,255) self.buildAndSendInterest(d['name'],0,0,0) self.buildAndSendInterest(d['name'],255,255,255) self.buildAndSendInterest(d['name'],0,0,0) self.buildAndSendInterest(d['name'],0,0,0) print "DONE" self.sendSignedInterest("whatever/profileStop/000000") self.endTime = time.time() print "total time is ",(self.endTime - self.startTime) print "number of interests is ",self.count print "average time per interest is ",((self.endTime - self.startTime)/self.count) return def mobileDisco(self): print "fading around" for i in range(0,85): r = b = g = 0 #red for i in range(0,85): r=i self.sendValToAllLights(r*3,g*3,b*3) for i in range(0,85): r=0 g=i self.sendValToAllLights(r*3,g*3,b*3) for i in range(0,85): g=0 b=i self.sendValToAllLights(r*3,g*3,b*3) self.sendValToAllLights(0,0,0) self.sendValToAllLights(255,255,255) self.sendValToAllLights(0,0,0) self.sendValToAllLights(255,255,255) self.sendValToAllLights(0,0,0) sys.exit() def sendValToAllLights(self,r,g,b): for d in self.cfg.names: self.buildAndSendInterest(d['name'],r,g,b) def discoArt(self): print "fading..." for d in self.cfg.names: if d['name'] == "incandescent": print d['name'] r = b = g = 0 #red for i in range(0,250): r=i self.buildAndSendArtInterest(d['name'],r) self.discoArt() def hx(self, inum): num = hex(inum)[2:] if (len(num) == 1): num = '0'+num #print num return str(num) def buildAndSendInterest(self,device,r,g,b): #rx = hex(r)[2:] #gx = hex(g)[2:] #bx = hex(b)[2:] rx = self.hx(r) gx = self.hx(g) bx = self.hx(b) #CLI = self.cfg.interestPrefix+device+"/rgb-8bit-hex/"+rx+gx+bx CLI = device+"/setRGB/"+rx+gx+bx #print CLI self.sendSignedInterest(CLI) #living-room-right-wall/rgb-8bit-hex/d2741d #interestPrefix #ccnx:/ndn/ucla.edu/apps/lighting/TV1/fixture/living-room-right-wall/rgb-8bit-hex/d2741d def buildAndSendArtInterest(self,device,r): rx = self.hx(r) #gx = hex(g)[2:] #bx = hex(b)[2:] #rx = self.hx(r) #CLI = self.cfg.interestPrefix+device+"/rgb-8bit-hex/"+rx+gx+bx CLI = device+"/setBrightness/"+rx #print CLI self.sendSignedInterest(CLI) #living-room-right-wall/rgb-8bit-hex/d2741d #interestPrefix #ccnx:/ndn/ucla.edu/apps/lighting/TV1/fixture/living-room-right-wall/rgb-8bit-hex/d2741d def sendInterest(self,command): n = Name(self.cfg.appPrefix) print("\nInterest espressing for "+str(n)) n += command #fullURI = self.cfg.interestPrefix + command #print fullURI i = Interest.Interest() #n = Name.Name([fullURI]) #this does not parse correctly #n = Name.Name(fullURI) print("Interest sending to "+str(n)) co = self.handle.get(n,i,200) if not not co: #if co is not empty, print result for debugging print("content: "+str(co.content)) def sendSignedInterest(self,command): self.count = self.count +1 time.sleep(self.cfg.refreshInterval) fullURI = self.cfg.appPrefix + command #print fullURI i = Interest() #self.state = NameCrypto.new_state() #build keyLocator to append to interest for NameCrypto on upcall keyLoc = pyccn.KeyLocator(self.key) keyLocStr = _pyccn.dump_charbuf(keyLoc.ccn_data) nameAndKeyLoc = Name(str(fullURI)) #print("there are "+str(len(nameAndKeyLoc))+" components") nameAndKeyLoc += keyLocStr #print("there are "+str(len(nameAndKeyLoc))+" components after adding keyLocStr") #symmetric authName = NameCrypto.authenticate_command(self.state, nameAndKeyLoc, self.cfg.appName, self.cryptoKey) #asymmetric #authName = NameCrypto.authenticate_command_sig(self.state, nameAndKeyLoc, self.cfg.appName, self.key) #print authName.components co = self.handle.expressInterest(authName,self)
class TyzxServer(Closure): def __init__(self, prefixstr ): self.handle = CCN() #XXX: temporary, until we allow fetching key from key storage self.key = self.handle.getDefaultKey() self.keylocator = KeyLocator(self.key) self.prefix = Name(prefixstr) # member_name = Name.Name(self.members_uri) # member_name.appendKeyID(fix_digest(self.key.publicKeyID)) # self.member_message = self.publish(member_name, nick) def listen(self): #listen to requests in namespace self.handle.setInterestFilter(self.prefix, self) self.handle.run(-1) def publish(self, name, content): # Name #print name # SignedInfo si = pyccn.SignedInfo() #si.type = pyccn.CCN_CONTENT_DATA si.type = 0x0C04C0 # content type si.finalBlockID = b'\x00' si.publisherPublicKeyDigest = self.key.publicKeyID si.keyLocator = self.keylocator si.freshnessSeconds = FRESHNESS_SECONDS # ContentObject co = ContentObject() co.content = content co.name = name co.signedInfo = si co.sign(self.key) return co def upcall(self, kind, upcallInfo): global lasttime if lasttime is None: # can't answer yet return pyccn.RESULT_OK if len(tyzxObjs.objs)<1: return pyccn.RESULT_OK interest = upcallInfo.Interest #print "Interest", interest.name, time.time() # CALL content matches interest to check exclusion on versions # #print interest.exclude name = interest.name #print name if name==self.prefix: # root #print "Request for root: %s" % str(name) if interest.exclude is None: freshids = tyzxObjs.objs.keys()[0:1] else: if len(interest.exclude.components) > 0: ids = set(tyzxObjs.objs.keys())# new stuff we have suffixes = set([int(str(s)[1:]) for s in interest.exclude.components]) freshids = list(ids.difference(suffixes)) # do we need this conversion? #print "ids", ids #print "suffixes", suffixes #print "freshids", freshids else: freshids = tyzxObjs.objs.keys()[0:1] if len(freshids)>0: child = freshids[0] else: return pyccn.RESULT_OK # no new content else: # should check what we're receiving! take next component child = int(name.components[-1:][0]) # why not be able to do this on name? #print "Request for child: %s" % child, time.time() #print "child - ", child if tyzxObjs.objs.has_key(child): O = tyzxObjs.objs[child] else: # Don't want to respond with a nonexistent. NDN way is to not answer interest. # If we've just started, we may not even know what the content store knows. # But, we do want to answer "exits" that we know about. #print "child", child, "is not present" if tyzxObjs.objExits.has_key(child): #print "child", child, "is exited" O = tyzxObjs.objExits[child] else: return pyccn.RESULT_OK #O = CompositeObject(BaseObject()) #O.time = lasttime.time #O.id = int(child) #O.status = "nonexistent" msgname = Name(self.prefix) msgname += str(child) msgname.components.append(versionFromTime (O.time)) # should have msgname.append #msgname.ccn_data_dirty=True - now handled within PyCCN # need binary add component self.message = self.publish(msgname, O.toJSON()) #print "Publishing", msgname, O.toJSON() #print "Present:", tyzxObjs.objs.keys(), time.time() self.handle.put(self.message) return pyccn.RESULT_INTEREST_CONSUMED return pyccn.RESULT_OK
from pyccn import CCN c = CCN() k = c.getDefaultKey()
class CcnxSocket(object): ''' A socket like handler for ccnx operations. Runs a simple event loop and handles set interest filter, send interest, and publish data. Current only one ccnx handle is used, we can use multiple handles if needed, but there is no such need as of now. ''' __logger = Logger.get_logger('CcnxSocket') def __init__(self, *args, **kwargs): ''' Creates a socket. As of now, we try to get the ccnx key from the default location ''' super(CcnxSocket, self).__init__() self.ccnx_key = CCN.getDefaultKey() self.ccnx_key_locator = pyccn.KeyLocator(self.ccnx_key) self.ccnx_handle = CCN() self.event_loop = CcnxLoop(self.ccnx_handle) def get_signed_info(self, freshness): ''' Get signed info to be included in the Content Object Args: freshness (int): the freshness of the Content Object in seconds Returns: a PyCCN.SignedInfo object ''' si = pyccn.SignedInfo() si.publisherPublicKeyDigest = self.ccnx_key.publicKeyID si.type = pyccn.CONTENT_DATA si.freshnessSeconds = freshness si.keyLocator = self.ccnx_key_locator return si def get_pyccn_name(self, name): '''Get a valid name for PyCCN. This is useful when the name string is encoded as unicode, as is the usual case in Python. However, PyCCN has problem handling unicode names, raising TypeError as a result. Args: name (str): the name string Returns: An ascii encoded name string ''' if isinstance(name, unicode): return Name(name.encode('ascii', 'ignore')) else: return Name(name) def publish_content(self, name, content, freshness=5): '''Publish the data as a Content Object Args: name (str): the name string content (bytes): the data bytes Kwargs: freshness (int): the freshness in seconds for the Content Object ''' co = ContentObject() co.name = self.get_pyccn_name(name) co.content = content si = self.get_signed_info(freshness) co.signedInfo = si co.sign(self.ccnx_key) self.ccnx_handle.put(co) def send_interest(self, name, closure, template=None): '''Send Interest Args: name (str): the name string closure (PyCCN.Closure): the closure that includes the callbacks to be used by PyCCN for this Interest Kwargs: template (PyCCN.Interest): the template for the additional field to be carried in the Interest, such as ChildSelector, Lifetime, AnswerOrigin, etc.. ''' n = self.get_pyccn_name(name) self.ccnx_handle.expressInterest(n, closure, template) def register_prefix(self, prefix, closure): '''Register the prefix under which the user wishes to receive Interests Args: prefix (str): the prefix name string closure (PyCCN.Closure): the closure that includes the callbacks to be used by PyCCN when an Interest with such prefix comes ''' p = self.get_pyccn_name(prefix) self.ccnx_handle.setInterestFilter(p, closure) def start(self): '''Start the CcnxLoop ''' start_new_thread(self.event_loop.run, ()) def stop(self): '''Stop the CcnxLoop ''' self.event_loop.stop()
from pyccn import CCN, _pyccn from threading import Timer from datetime import datetime handle = _pyccn.create() try: _pyccn.run(handle, 100) except _pyccn.CCNError: pass else: raise AssertionError("ccn_run() should fail when not connected") del handle c = CCN() c.run(0) def change_timeout(): print("Changing timeout!") c.setRunTimeout(1000) t = Timer(0.1, change_timeout) t.start() org_start = datetime.now() while True: if (datetime.now() - org_start).seconds > 3: raise AssertionError("setRunTimeout() failed")
si.finalBlockID = last_segment si.publisherPublicKeyDigest = key.publicKeyID si.keyLocator = Key.KeyLocator(key) # ContentObject co = ContentObject.ContentObject() co.content = content co.name = co_name co.signedInfo = si co.sign(key) return co name = Name.Name('/repo/upload/test') name_v = Name.Name(name) name_v.appendVersion() handle = CCN.CCN() key = handle.getDefaultKey() last_seg = segment(9) content = [] for i in range(10): name_s = Name.Name(name_v) name_s += segment(i) co = publish(key, name_s, last_seg, "Segment: %d\n" % i) content.append(co) upload = RepoUpload(handle, name_v, content) upload.start()
from pyccn import Interest, Name, Key, CCN, _pyccn import datetime k = CCN.getDefaultKey() i = Interest() i.name = Name('/hello/world') i.minSuffixComponents = 2 i.maxSuffixComponents = 4 i.publisherPublicKeyDigest = k.publicKeyID i.exclude = None i.childSelector = 1 i.answerOriginKind = 4 i.scope = 2 i.interestLifetime = 30.0 i.nonce = b'abababa' print(i) print(i.ccn_data) i2 = _pyccn.Interest_obj_from_ccn(i.ccn_data) print(i2) assert (i.name == i2.name) assert (i.minSuffixComponents == i2.minSuffixComponents) assert (i.maxSuffixComponents == i2.maxSuffixComponents) assert (i.publisherPublicKeyDigest == i2.publisherPublicKeyDigest) assert (i.exclude == i2.exclude) assert (i.childSelector == i2.childSelector) assert (i.scope == i2.scope) assert (i.interestLifetime == i2.interestLifetime)
from pyccn import CCN, Name, Interest, Closure from time import sleep worked = False class MyClosure(Closure): def upcall(self, kind, upcallInfo): global worked print("Got response") print(kind) print(upcallInfo) worked = True n = Name("ccnx:/ccnx/ping") i = Interest() closure = MyClosure() c = CCN() res = c.expressInterest(n, closure, i) print(res) #causes crashes c.run(10) print("Ha!") assert (worked)
from pyccn import CCN, Name c = CCN() print(c) n = Name() print(n) n = Name("ccnx:/ccnx/ping") print(n) co = c.get(n) print(co) #this shouldn't cause segfault print(n) n = Name("ccnx:/ccnx/some_nonexisting_name") co = c.get(n, None, 100) #this shouldn't cause segfault! print(co)
from pyccn import CCN, _pyccn handle = _pyccn.create() #this should fail try: _pyccn.disconnect(handle) except _pyccn.CCNError: pass else: raise AssertionError("Closing an unopened connection should fail") _pyccn.connect(handle) _pyccn.disconnect(handle) try: _pyccn.disconnect(handle) except _pyccn.CCNError: pass else: raise AssertionError("Closing handle twice shouldn't work") del handle c = CCN() _pyccn.disconnect(c.ccn_data) del c
#block_size = 1048576 #block_size = 128 * 4096 #fi = open(file, "r") #fi.seek(100*1024*1024) #def block(): # global fi, position, block_size # data = fi.read(block_size) # return data import struct, vlc_access from pyccn import * h = CCN.CCN() #base = Name.Name('/movie/%FD%04%E0%ACL%97%60') base = Name.Name('/testmovie') def segment(segment): return b'\x00' + struct.pack('!Q', segment).lstrip('\x00') def getSegment(seg): global h, base name = Name.Name(base) name += segment(seg) print "Requesting: %s" % name co = None
import pyccn from pyccn import CCN, Name, Interest, ContentObject, SignedInfo, Key, KeyLocator, Closure #from threading import Timer k = CCN.getDefaultKey() kl = KeyLocator(k) n = Name("/forty/two") class SenderClosure(Closure): def upcall(self, kind, upcallInfo): global sender_handle, n, k, kl print("Sender closure:") print(upcallInfo) co = ContentObject() co.name = Name(n) co.content = "Frou" si = SignedInfo() si.publisherPublicKeyDigest = k.publicKeyID si.type = pyccn.CONTENT_DATA si.freshnessSeconds = 5 si.keyLocator = kl co.signedInfo = si co.sign(k) r = sender_handle.put(co) print("put(co) = ", r)
class CcnxSocket(object): ''' A socket like handler for ccnx operations. Runs a simple event loop and handles set interest filter, send interest, and publish data. Current only one ccnx handle is used, we can use multiple handles if needed, but there is no such need as of now. ''' __logger = Logger.get_logger('CcnxSocket') def __init__(self, *args, **kwargs): ''' Creates a socket. As of now, we try to get the ccnx key from the default location ''' super(CcnxSocket, self).__init__() self.ccnx_key = CCN.getDefaultKey() self.ccnx_key_locator = pyccn.KeyLocator(self.ccnx_key) self.ccnx_handle = CCN() self.event_loop = CcnxLoop(self.ccnx_handle) def get_signed_info(self, freshness): ''' Get signed info to be included in the Content Object Args: freshness (int): the freshness of the Content Object in seconds Returns: a PyCCN.SignedInfo object ''' si = pyccn.SignedInfo() si.publisherPublicKeyDigest = self.ccnx_key.publicKeyID si.type = pyccn.CONTENT_DATA si.freshnessSeconds = freshness si.keyLocator = self.ccnx_key_locator return si def get_pyccn_name(self, name): '''Get a valid name for PyCCN. This is useful when the name string is encoded as unicode, as is the usual case in Python. However, PyCCN has problem handling unicode names, raising TypeError as a result. Args: name (str): the name string Returns: An ascii encoded name string ''' if isinstance(name, unicode): return Name(name.encode('ascii', 'ignore')) else: return Name(name) def publish_content(self, name, content, freshness = 5): '''Publish the data as a Content Object Args: name (str): the name string content (bytes): the data bytes Kwargs: freshness (int): the freshness in seconds for the Content Object ''' co = ContentObject() co.name = self.get_pyccn_name(name) co.content = content si = self.get_signed_info(freshness) co.signedInfo = si co.sign(self.ccnx_key) self.ccnx_handle.put(co) def send_interest(self, name, closure, template = None): '''Send Interest Args: name (str): the name string closure (PyCCN.Closure): the closure that includes the callbacks to be used by PyCCN for this Interest Kwargs: template (PyCCN.Interest): the template for the additional field to be carried in the Interest, such as ChildSelector, Lifetime, AnswerOrigin, etc.. ''' n = self.get_pyccn_name(name) self.ccnx_handle.expressInterest(n, closure, template) def register_prefix(self, prefix, closure): '''Register the prefix under which the user wishes to receive Interests Args: prefix (str): the prefix name string closure (PyCCN.Closure): the closure that includes the callbacks to be used by PyCCN when an Interest with such prefix comes ''' p = self.get_pyccn_name(prefix) self.ccnx_handle.setInterestFilter(p, closure) def start(self): '''Start the CcnxLoop ''' start_new_thread(self.event_loop.run, ()) def stop(self): '''Stop the CcnxLoop ''' self.event_loop.stop()
import time, struct import pyccn from pyccn import CCN, Name, Interest, Key, ContentObject, Closure, KeyLocator, ExclusionFilter from Tyzx import CompositeObject, BaseObject prefix = "ccnx:/ndn/ucla.edu/apps/tv1/occupants" DISCOVER_INTEREST_PERIOD = 0.250 # How often UPDATE_INTEREST_PERIOD = 0.250 CCN_WAIT_TIME_MS = 1 tyzxObjects = {} oldObjects = set() # still may be in the content store ccn = CCN() interestDiscover = Interest() interestDiscover.name = Name(prefix) interestDiscover.minSuffixComponents = 2 # occupant id + the implicit digest at a minimum interestUpdate = Interest() interestUpdate.minSuffixComponents = 2 # time (version) + the implicit digest interestUpdate.childSelector = 1 # rightmost child #interestUpdate.interestLifetime = ???? lastdiscovertime = 0 def versionFromTime(t): bintime = struct.pack("!Q", int(t * 4096 + 0.5)) version = bintime.lstrip(b'\x00')
print(os.getcwd()) root = os.path.join("tmp") private_pem1 = os.path.join(root, 'private1.pem') public_pem1 = os.path.join(root, 'public1.pem') private_pem2 = os.path.join(root, 'private2.pem') public_pem2 = os.path.join(root, 'public2.pem') def rm_files(*list): for file in list: if os.path.exists(file): os.remove(file) rm_files(private_pem1, public_pem1, private_pem2, public_pem2) k = CCN.getDefaultKey() k.privateToPEM(filename=private_pem1) k.publicToPEM(filename=public_pem1) k2 = Key() k2.fromPEM(filename=private_pem1) k2.privateToPEM(filename=private_pem2) k2.publicToPEM(filename=public_pem2) assert(filecmp.cmp(private_pem1, private_pem2)) assert(filecmp.cmp(public_pem1, public_pem2)) print(b64encode(k.publicKeyID)) print(b64encode(k2.publicKeyID)) assert(k.publicKeyID == k2.publicKeyID)
import time, struct import pyccn from pyccn import CCN, Name, Interest, Key, ContentObject, Closure, KeyLocator, ExclusionFilter from Tyzx import CompositeObject, BaseObject prefix = "ccnx:/ndn/ucla.edu/apps/tv1/occupants" DISCOVER_INTEREST_PERIOD = 0.250 # How often UPDATE_INTEREST_PERIOD = 0.250 CCN_WAIT_TIME_MS = 1 tyzxObjects = {} oldObjects = set() # still may be in the content store ccn = CCN() interestDiscover = Interest() interestDiscover.name = Name(prefix) interestDiscover.minSuffixComponents = 2 # occupant id + the implicit digest at a minimum interestUpdate = Interest() interestUpdate.minSuffixComponents = 2 # time (version) + the implicit digest interestUpdate.childSelector = 1 # rightmost child #interestUpdate.interestLifetime = ???? lastdiscovertime = 0 def versionFromTime(t): bintime = struct.pack("!Q", int(t * 4096 + 0.5)) version = bintime.lstrip(b'\x00') return b'\xfd' + version