def __init__(s, root=None): s.k, s.o, s.b, s.root = ecc.ecdsa(), ecc.ecdsa(), BASE, root s.k.generate() s.p = s.k.compress(s.k.pt) s.i = s.p[:8] s.c = root.k.sign(s.i) if root else None s.tp, s.tn, s.com, s.un = {}, [], {s.i: s}, {}
def transaction(e, d): """ """ k = ecc.ecdsa() src, dst, dat, lat, mnt, ref = e[:8], e[8:16], e[16:20], e[20:28], e[28:32], e[32:40] msg, sig, now = e[:-96], e[-96:], ecc.datint() if src not in d.keys() or dst not in d.keys() or src == dst: return b'Error database' dls, dld = d[src][4:], d[dst][4:] zx, zd = ecc.b2h(src), ecc.b2h(dst) if zx not in d.keys(): return b'Error public key' k.pt = k.uncompress(ecc.h2b(zx + d[zx])) if not k.verify(sig, msg): return b'Error signature' val, bals, bald = ecc.b2i(mnt), balance(src, d), balance(dst, d) if val <= 0 or bals - val < -MAXBAL or bald + val > MAXBAL: return b'Error value' os, od = ecc.b2i(d[src][:4]), ecc.b2i(d[dst][:4]) ns, nd = os + 1, od + 1 nhs = ecc.z10 if os == 0 else d[src + ecc.i2b(os, 4)][-10:] nhd = ecc.z10 if od == 0 else d[dst + ecc.i2b(od, 4)][-10:] lst_tot, lst_wlt = ecc.b2i(d[ecc.v1][:8]), ecc.b2i(d[ecc.v1][8:]) if ecc.b2i(dls) <= now or ecc.b2i(dld) <= now or ecc.b2i(dat) > now: return b'Error deadline' if os > 0: dx = src + ecc.i2b(os, 4) if len(d[dx]) == NS: dx = d[dx][:12] if ecc.b2i(d[dx][8:12]) >= ecc.b2i(dat): return b'Wait a minute !' nws, nwd = ecc.s2b(bals - val, 4), ecc.s2b(bald + val, 4) sm, dm = dst + ecc.i2b(nd, 4) + nws, src + dat + lat + mnt + ref + sig + nwd # BEGIN WRITE SECTION d[src] = ecc.i2b(ns, 4) + dls d[src + ecc.i2b(ns, 4)] = sm + hashlib.sha1(src + sm + nhs).digest()[:10] d[dst] = ecc.i2b(nd, 4) + dld d[dst + ecc.i2b(nd, 4)] = dm + hashlib.sha1(dst + dm + nhd).digest()[:10] d[ecc.v1] = ecc.i2b(lst_tot + 1, 8) + ecc.i2b(lst_wlt + val, 8) # END WRITE SECTION return b'TRANSACTION from ' + zx + b' to ' + zd
def object(db, ip): "" k, t = ecc.ecdsa(), socket.socket(socket.AF_INET, socket.SOCK_DGRAM) print ('Intelligent Object (socket open)') with dbm.open(db, 'c') as d: if len(d.keys()) == 0: k.generate() sk, pk = ecc.i2b(k.privkey, 48), k.compress(k.pt) d[b'KEYS'] = pk + sk t.bind((ip, PORT2)) while True: (data, addr) = t.recvfrom(1024) with open('server_pk') as f: pk = f.read() k.pt = k.uncompress(ecc.z85decode(pk.encode('UTF-8'))) if len(data)>130: sig, msg = ecc.z85decode(data[:120]), data[120:] if k.verify(sig, msg): cod = random.randrange(10000) t.sendto(b'start counting (code:%04d)' % cod, addr) dat = time.time() else: t.sendto(b'error on signature', addr) elif len(data) == 4: with dbm.open(db, 'c') as d: print (' %d secondes' % int(time.time()-dat)) pk, sk = d[b'KEYS'][:48], d[b'KEYS'][48:] k.pt, k.privkey = k.uncompress(pk), ecc.b2i(sk) msg = b'invoice for %d secondes' % int(time.time()-dat) cmd = ecc.z85encode(k.sign(msg)) + msg t.sendto(cmd, addr) else: t.sendto(b'error', addr)
def server(db, ip): """ """ k = ecc.ecdsa() s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind((ip, PORT1)) print ('IO-server on %s' % ip) with dbm.open(db, 'c') as d: if len(d.keys()) == 0: k.generate() sk, pk = ecc.i2b(k.privkey, 48), k.compress(k.pt) d[b'SERVER'] = pk + sk d[ecc.v1] = ecc.z8 + ecc.z8 with open('server_pk', 'w') as f: f.write(ecc.z85encode(pk).decode('UTF-8')) print ('Server Public ID: ' + server_id(d).decode('UTF-8')) if ecc.v1 in d.keys(): print ('Wealth: %d [%d operations]' % (ecc.b2i(d[ecc.v1][8:]),ecc.b2i(d[ecc.v1][:8]) )) while True: (data, addr), o = s.recvfrom(1024), b'' with dbm.open(db, 'c') as d: if len(data) == 1: if data == b'v': o = b'Error %02X' % verif(d) elif data == b'l': o = list_humans(d) elif data == b's': o = server_id(d) elif len(data) == 8: o = proof (data, d) elif len(data) == 16: o = history (data, d) elif len(data) == 93: o = candidate (data, d) elif len(data) == 136: o = transaction(data, d) elif len(data) == 142: o = certificate(data, d) elif len(data) >= 144 and len(data) <= 256: o = invoice(data, d) else: o = b'command not found!' s.sendto(o, addr)
def __init__(self, name, age=18): " Name is not required for the real app " self.name, self.age, self.hist, self.bal, self.eco = name, age, [], 0, 0 self.root = PREFIX + secrets.token_bytes(12) + b'\0' * 3 self.ids, self.cts, self.risk, self.note, self.refe = [], {}, 0, {}, {} self.coef, self.k = (14, 1, 60, 1.2, 100), ecc.ecdsa() self.k.generate() self.pk = self.k.compress(self.k.pt)
def readsync(s): with dbm.open(s.n) as b: g0, g1, k = ecc.z2, ecc.i2b(1, 2), ecc.ecdsa() msg = b[g0] + ecc.z4 if g1 in b: msg += b[g1] + b[b'_'+g1] k.privkey = s.getsk() sgn = k.sign(msg) return msg + sgn
def manage_post(s, d): k = ecc.ecdsa() s.response('application/octet-stream') if len(d) != RLEN: return False if s.nod.me not in s.nod.tid: return False if not s.nod.check(s.nod.tid[s.nod.me], ecc.b2i(d[10:13])): return False k.pt = k.uncompress(s.nod.tid[s.nod.me] + s.nod.tpk[s.nod.tid[s.nod.me]]) if not k.verify(d[16:], d[:16]): return False return s.nod.manage(d)
def sync(s, m): with dbm.open(s.n, 'c') as b: g0, g1, k = ecc.z2, ecc.i2b(1, 2), ecc.ecdsa() k.pt = k.uncompress(s.tid['PUB'] + s.tpk[s.tid['PUB']]) if k.verify(m[-96:], m[:-96]): if ecc.b2i(b[g0]) < ecc.b2i(m[:6]): b[g0] = m[:6] if len(m) == 116 and g1 in b: if ecc.b2i(b[g1]) < ecc.b2i(m[10:16]): b[g1] = m[10:16] if ecc.b2i(b[b'_'+g1]) < ecc.b2i(m[16:]): b[b'_'+g1] = m[16:20]
def genkey(mel, unik, d): if len(d.keys()) > 0 and unik: print ('key already defined') return b'' k = ecc.ecdsa() k.generate() sk, pk = ecc.i2b(k.privkey, 48), k.compress(k.pt) d[pk[:8]] = pk[8:] + sk return pk + b'%45s' % mel
def proof(x, d): "" if b'SERVER' in d.keys(): k = ecc.ecdsa() pk, sk = d[b'SERVER'][:48], d[b'SERVER'][48:] k.pt, k.privkey = k.uncompress(pk), ecc.b2i(sk) dat = ecc.datdecode(ecc.datencode()).encode('UTF-8') msg = b'%s %d %s' % (ecc.b2h(x), balance(x, d), dat) return ecc.z85encode(k.sign(msg)) + msg if not verif(d) else b'error' return b''
def gene(bmy, dst, pld, d): "" if bmy in d.keys(): k = ecc.ecdsa() pk, sk = bmy + d[bmy][:40], d[bmy][40:] k.pt, k.privkey = k.uncompress(pk), ecc.b2i(sk) msg = pk[:8] + dst + ecc.datencode() + ecc.z8 + pld + ecc.z8 return msg + k.sign(msg) else: print ('you do not own that key') return b''
def reset(s): with dbm.open(s.n, 'c') as b: for x in b.keys(): del b[x] k = ecc.ecdsa() k.generate() s.pk = k.compress(k.pt) # My Public key b[b'&'] = ecc.i2b(k.privkey, 48) # My Private key #if s.n == 'PUB': b[ecc.z2], b[b'_'+ecc.z2] = ecc.z6, ecc.z4 b[s.pk[:5]] = ecc.z6 # Types b[ecc.i2b(0)] = ecc.i2b(15, 3) # Type0=G0:15% b[ecc.i2b(1)] = ecc.i2b(13, 3) + ecc.i2b(0x100+80, 3) # Type1=G0:13%G1:80%
def commit(s, r): t, k = socket.socket(socket.AF_INET, socket.SOCK_DGRAM), ecc.ecdsa() isn, val, rcp = (r.v.group(1) != 'PUB'), int(r.v.group(2)), r.v.group(3).upper() assert s.check(s.tid[s.n], val) assert rcp in s.tid and s.n != rcp and s.n != 'PUB' assert s.bal(s.tid['PUB']) == 0 and s.time(s.tid['PUB']) == 0 msg = s.tid[s.n] + s.tid[rcp] + ecc.i2b(val, 3) + ecc.z1 + s.pos(s.tid[s.n] + s.tid[rcp]) k.privkey = s.getsk() sgn = k.sign(msg) s.add(msg + sgn) # add src if rcp in s.tbl: if isn: t.sendto(msg + sgn, (HOST, s.tbl[rcp])) t.sendto(msg + sgn, (HOST, s.tbl['PUB'])) s.sync(t.recvfrom(1024)[0]) else: print ('iphone') # iphone case t.sendto(msg + sgn, (HOST, s.tbl['PUB']))
def manage(s, m, a=None): t, k = socket.socket(socket.AF_INET, socket.SOCK_DGRAM), ecc.ecdsa() k.pt, dst = k.uncompress(m[:5] + s.tpk[m[:5]]), s.rvs[m[5:10]] if s.n != 'PUB' and m[5:10] != s.tid[s.n] : return False if not k.verify(m[MLEN:RLEN], m[:MLEN]) : return False if len(m) > RLEN: s.sync(m[RLEN:]) if s.pos(m[:10]) == m[14:16]: if s.n == 'PUB' and not s.check(m[:5], ecc.b2i(m[10:13])): return False s.add(m) # add dst or PUB if s.n == 'PUB' and a: t.sendto(s.readsync(), a) if dst in s.tbl: t.sendto(m + s.readsync(), (HOST, s.tbl[dst])) else: print ('record for iphone') s.pending(m[:RLEN]) print (s.bals()) return True else: return ecc.b2i(s.pos(m[:10])) == ecc.b2i(m[14:16]) + 1
def certificate(e, d): """ A(green) if first B->A if A(green)B(red) then B(orange) A->B if A(green)B(orange) then B(green) """ k = ecc.ecdsa() src, dst, dat, lat, pld, ref = e[:8], e[8:16], e[16:20], e[20:28], e[28:38], e[38:46] msg, sig, now = e[:-96], e[-96:], ecc.datint() if ecc.b2i(dat) > now: return b'future date' if src not in d.keys() or dst not in d.keys() or src == dst: return b'Error database' zx = ecc.b2h(src) if zx not in d.keys(): return b'Error public key' k.pt = k.uncompress(ecc.h2b(zx + d[zx])) if not k.verify(sig, msg): return b'Error signature' green, orang, red = ecc.add1year(ecc.datencode()), ecc.datencode(), ecc.z4 os, od = ecc.b2i(d[src][:4]), ecc.b2i(d[dst][:4]) ns, nd = os + 1, od + 1 nhs = ecc.z10 if os == 0 else d[src + ecc.i2b(os, 4)][-10:] if os > 0: dx = src + ecc.i2b(os, 4) if len(d[dx]) == NS: dx = d[dx][:12] if ecc.b2i(d[dx][8:12]) >= ecc.b2i(dat): return b'Wait a minute !' nws = ecc.s2b(balance(src, d), 4) sm = dst + dat + lat + pld + ref + sig + nws # START WRITING if ecc.b2i(d[dst][4:]) > ecc.datint() and d[src][4:] == red: d[src] = ecc.i2b(ns, 4) + orang d[src + ecc.i2b(ns, 4)] = sm + hashlib.sha1(src + sm + nhs).digest()[:10] d[ecc.v1] = ecc.i2b(ecc.b2i(d[ecc.v1][:8]) + 1, 8) + d[ecc.v1][8:] return b'REQUEST by ' + zx if ecc.b2i(d[src][4:]) > ecc.datint() and d[dst][4:] != red: d[dst] = d[dst][:4] + green d[src] = ecc.i2b(ns, 4) + d[src][4:] d[src + ecc.i2b(ns, 4)] = sm + hashlib.sha1(src + sm + nhs).digest()[:10] d[ecc.v1] = ecc.i2b(ecc.b2i(d[ecc.v1][:8]) + 1, 8) + d[ecc.v1][8:16] return b'CERTIFICATION by ' + zx # STOP WRITING else: return b'Error request'
def test(self, u): for x in u: x.pretest(self) self.tax, k, tab = sum([ecc.b2i(x[-1:]) // 5 for x in self.hse[0]]), ecc.ecdsa(), {} for x in u: x.test(self) assert operator.eq(self.hse[0].keys(), self.hse[1].keys()) # VERIF 1: no leaks assert sum([x.bal for x in u]) + self.tax == 0 # VERIF 2: sum balances null for x in self.hse[0]: for z in [y for y in self.pks if y[:8] == self.hse[0][x][0]]: k.pt = k.uncompress(z) assert k.verify(self.hse[0][x][1], x) # VERIF 3: Transaction signature ok for x in self.hse[0]: y, pr = self.hse[0][x][0], ecc.b2i(x[-1:]) tab[y] = tab[y] + pr if y in tab else pr for z in [x for x in self.hse[1] if self.hse[1][x] in tab]: tab[self.hse[1][z]] -= ecc.b2i(z[-1:]) for t in tab: assert tab[t] < MAXDEBT # VERIF 4: all debt under limit
def verif(d): """ check certification ! """ print ('run check!') k = ecc.ecdsa() if len(d.keys()) > 0 and ecc.v1 not in d: return 0x01 # head does not exists wc, wr, tc, tr, al = 0, 0, 0, 0, 0 lo = [] for i in [x for x in d.keys() if len(x) == 16]: x = ecc.h2b(i) if ecc.b2i(d[x][4:]) > ecc.datint(): lo.append(x) #print (lo) #find the root for x in d.keys(): # Length lk, lv = len(x), len(d[x]) if lk == 1: wr, tr = ecc.b2i(d[x][8:16]), ecc.b2i(d[x][:8]) if lk == 1 and lv != 16: return 0x02 # bad length head if lk == 5 and lv != 96: return 0x03 # bad length server id if lk == 8 and lv != 8: return 0x04 # bad length id head if lk == 12 and lv not in (NS, ND, NC): return 0x05 # bad length operation if lk == 16 and lv != 80: return 0x06 # bad length pub key # Public keys if lk == 12: if ecc.b2h(x[:8]) not in d: return 0x07 # src id unknown if ecc.b2h(d[x][:8]) not in d: return 0x08 # dst id unknown if lk == 8: # Money supply al += balance(x, d) # Dates dat = ecc.z8 for i in range(ecc.b2i(d[x][:4])): dx = x + ecc.i2b(i+1, 4) if len(d[dx]) in (ND, NC): if d[dx][8:12] <= dat: return 0x09 # bad date increase dat = d[dx][8:12] if len(d[dx]) == ND: if dat > d[x][4:]: return 0x0A # invalid date/dead line # Signatures for i in range(ecc.b2i(d[x][:4])): dx = x + ecc.i2b(i+1, 4) if len(d[dx]) == NC: src, dst = x, d[dx][:8] if len(d[dx]) == ND: src, dst = d[dx][:8], dx[:8] if len(d[dx]) in (NC, ND): zx = ecc.b2h(src) if zx not in d.keys(): return 0x0B # Error public key msg, sig = src + dst + d[dx][8:-110], d[dx][-110:-14] k = ecc.ecdsa() k.pt = k.uncompress(ecc.h2b(zx + d[zx])) if not k.verify(sig, msg): return 0x0C # bad signature # Hash h = ecc.z10 for i in range(ecc.b2i(d[x][:4])): dx = x + ecc.i2b(i+1, 4) h = hashlib.sha1(x + d[dx][:-10] + h).digest()[:10] if h != d[dx][-10:]: return 0x0D # bad hash # Wealth for i in range(ecc.b2i(d[x][:4])): dx = x + ecc.i2b(i+1, 4) if len(d[dx]) == ND: wc += ecc.b2i(d[dx][20:24]) # Operations counter for i in range(ecc.b2i(d[x][:4])): dx = x + ecc.i2b(i+1, 4) if len(d[dx]) in (ND, NC): tc += 1 # Balances b = 0 for i in range(ecc.b2i(d[x][:4])): dx = x + ecc.i2b(i+1, 4) if dx not in d: return 0x0E # missing transaction if len(d[dx]) == ND: b += ecc.b2i(d[x + ecc.i2b(i+1, 4)][20:24]) elif len(d[dx]) == NS: b -= ecc.b2i(d[d[dx][:12]][20:24]) if b != ecc.b2s(d[dx][-14:-10], 4): return 0x0F # bad balance if b < -MAXBAL or b > MAXBAL: return 0x10 # Out of bounds if wc != wr: return 0x11 # bad wealth if tc != tr: return 0x12 # bad counter if al != 0: return 0x13 # bad money supply return 0 # Everythink ok !
class beacon: ear, say, cts, go, current, k, price, balance = {}, {}, {}, False, None, ecc.ecdsa(), 0, 0 def __init__(s, arg): s.p = int(arg) if not ecc.os.path.exists('db%d'%s.p): ecc.os.makedirs('db%d'%s.p) threading.Thread(target=s.server).start() threading.Thread(target=s.client).start() s.k.generate() while (True): c = input() if c == "u": s.update() # -> download from backend elif c == "g": s.stopgo() # -> stop/go elif c == "s" and s.go == False: print(s.status()) # -> display status if stop elif reg(re.match('^(\d\d)$', c)): s.pay(c) elif len(c) > 24 and len(c) < 90: s.update(c) # -> try upload to backend else: print('command not valid') def pay(s, c): s.price = int(c) print ('PAY:%d' % s.price) def status(s): exposed = {} print ('Balance %d' % s.balance) if ecc.os.path.isfile('db%d/exposed'%s.p): with dbm.open('db%d/exposed'%s.p) as b: for x in b.keys(): exposed[x] = (datdecode(b[x][:4]), ecc.b2i(b[x][-1:])) with dbm.open('db%d/hear'%s.p) as b: for x in [y for y in b.keys() if y in exposed]: return 'risk level %s %d' % (exposed[x][0], exposed[x][1]) return 'ok' def stopgo(s): print ("go/stop") s.go = not s.go def getid(s, phone, dest): if s.price>0: print ('PAYED %d to %s' % (s.price, dest)) s.balance -= s.price return ecc.i2b(phone%256) + secrets.token_bytes(10) + dest + ecc.i2b(s.price) def client(s): m, n, i = s.getid(s.p, ecc.i2b(0, 4)), now(), 0 t = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) with dbm.open('db%d/say'%s.p, 'c') as b: # said ids while (True): if s.go and (now() - n >= TICK): n, i = now(), i + 1 if s.price > 0: i = 0 if not i % EPOC: dest = ecc.i2b(0, 4) if s.current in s.cts: dest = s.cts[s.current][1:5] m = s.getid(s.p, dest) s.price = 0 s.dump(b) z = s.say[m]+1 if m in s.say else 0 # lattitude/longitude if captured (data stay on the phone!) lt, lo = ecc.i2b(random.randint(0, 100), 2), ecc.i2b(random.randint(0, 100), 2) s.say[m], b[m] = z, ecc.i2b(n, 4) + ecc.i2b(z, 4) + lt + lo s.current = m for x in [y for y in range(MAXC) if s.p!=BASP+y]: t.sendto(m, (HOST, BASP+x)) def dump(s, b): f = open('db%d/dump'%s.p, 'bw') for i in b.keys(): f.write(i) # contacts for c in s.cts: f.write(c[:-1] + ecc.i2b(ecc.b2i(c[-1:]) + 0x10)) # contacts-contacts f.close() def short(s, m): if m and len(m)>6: return m[:2] + m[-4:] return m def server(s): t, n, buf, sdest = socket.socket(socket.AF_INET, socket.SOCK_DGRAM), now(), {}, ecc.i2b(0, 4) t.bind((HOST, s.p)) while (True): m = t.recvfrom(1024)[0] if now() - n <= 4: buf[m] = True else: n, buf = now(), {} z, dest, price = s.ear[m]+1 if m in s.ear else 0, m[-5:-1], ecc.b2i(m[-1:]) if s.current: s.cts[s.current] = m print (len(s.cts), s.short(m), z, len(buf), s.short(s.current)) if price > 0 and sdest != dest: print ('RECEIVE %d' % price) s.balance += price sdest = dest with dbm.open('db%d/hear'%s.p, 'c') as b: # heard ids s.ear[m], b[m] = z, ecc.i2b(now(), 4) + ecc.i2b(z, 4) def update(s, c=''): if c == '': print ('Update from backend') r = requests.post(URLB) else: print ('Try to upload to backend with code\n%s' %c) r = requests.post(URLB, files = {'file': open("db%d/dump"%s.p, "rb")}, data = {'c': c}) with open('db%d/exposed'%s.p, 'wb') as f: for chk in r.iter_content(chunk_size=1024): if chk: f.write(chk)