forked from kokjo/pycoin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
blockchain.py
58 lines (54 loc) · 1.53 KB
/
blockchain.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
from utils import *
import genesisblock
import msgs
import jserialize as js
import bserialize as bs
class BlockAux(js.Entity, bs.Entity):
fields = {
"block":msgs.Block,
"txs":js.List(js.Hash),
"number":js.Int,
"totaldiff":js.Int,
"succ": js.Hash,
}
bfields = [
("block", msgs.Block),
("txs", bs.VarList(bs.Hash)),
("number", bs.structfmt("<Q")),
("totaldiff", bs.structfmt("<Q")),
("succ", bs.Hash),
]
@property
def hash(self):
return self.block.hash
@constructor
def make(self, blockmsg):
self.block, self.txs, self.number = blockmsg.block, [tx.hash for tx in blockmsg.txs], 2**64-1
self.totaldiff = 0
self.succ = nullhash
class BlockList(js.Entity, bs.Entity):
fields = {
"blocks":js.List(js.Hash),
}
bfields = [
("blocks", bs.VarList(bs.Hash)),
]
class BlockChain:
def __init__(self, db, server, txdb):
self._db
self.server = server
self.txdb = txdb
try:
self.mainchain = self._db["mainchain"]
except:
self.add(genesisblock.blockmsg)
def put_aux(aux):
self._db[aux.hash] = aux.tobinary()
def add(self, blockmsg):
if blockmsg.block.hash in self._db:
return
aux = BlockAux.make(blockmsg)
if blockmsg.block.prev == nullhash:
aux.number = 1
aux.totaldiff = bits_to_diff(aux.block.bits)
self.put_aux(aux)