-
Notifications
You must be signed in to change notification settings - Fork 0
/
nakcache.py
160 lines (149 loc) · 6.71 KB
/
nakcache.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
# Copyright (c) 2016, Joseph deBlaquiere <jadeblaquiere@yahoo.com>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of ciphrtxt nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import ctcoin.rpc
import binascii
from ctcoin.core.script import *
from ciphrtxt.nak import NAK
import plyvel
import json
import logging
config = {}
config['rpchost'] = '127.0.0.1'
config['rpcport'] = 7765
config['minconf'] = 6
config['dbdir'] = 'nakdb/'
config['maxgap'] = 64
config['paranoid'] = True
_config_key = binascii.unhexlify('000000000000000000000000000000000000000000000000000000000000000000')
class NAKCache(object):
def __init__(self, dbdir=config['dbdir'], host=config['rpchost'],
port=config['rpcport'], rpcuser=None, rpcpass=None,
minconf=config['minconf']):
self.blockcount = 0
rpcstr = ''
if rpcuser is not None and rpcpass is not None:
rpcstr = rpcuser + ':' + rpcpass + '@'
url = 'https://' + rpcstr + host + ':' + str(port) + '/'
self.proxy = ctcoin.rpc.Proxy(service_url=url, service_port=str(port))
#try:
# current = self.proxy.getblockcount()
#except:
# raise ValueError('Cannot connect to RPC Host')
self.minconf = minconf
self.db = plyvel.DB(dbdir, create_if_missing=True)
statusj = self.db.get(_config_key)
if statusj is not None:
self.status = json.loads(statusj.decode('UTF-8'))
self.blockcount = self.status['blockcount']
logging.info('read blockcount as %d' % self.blockcount)
logging.info('status = %s' % str(self.status))
else:
self.status = {}
self.status['blockcount'] = 0
def sync(self):
try:
current = self.proxy.getblockcount()
except:
logging.info('Connection to RPC host failed')
return False
if self.blockcount >= current - self.minconf:
return False
#print('sync from height %d to %d' % (self.blockcount, current-self.minconf))
head = self.blockcount
while head < current - self.minconf:
if head + config['maxgap'] <= current - self.minconf:
blocklist = []
i = head + config['maxgap'] - 1
h = self.proxy.getblockhash(i)
while i >= head:
b = self.proxy.getblock(h)
blocklist.insert(0,b)
h = b.hashPrevBlock
i -= 1
if config['paranoid']:
if head > 0:
hh = self.proxy.getblockhash(head-1)
assert h == hh
head += config['maxgap']
else:
blocklist = []
h = self.proxy.getblockhash(head)
b = self.proxy.getblock(h)
blocklist.append(b)
head += 1
i = self.blockcount
for b in blocklist:
for j in range (0,len(b.vtx)):
tx = b.vtx[j]
#print('vout len = %d' % len(tx.vout))
for k in range(0,len(tx.vout)):
out = tx.vout[k]
s = out.scriptPubKey
if s[0] != OP_REGISTERACCESSKEY:
continue
if s[1] == OP_PUSHDATA1:
size = int(binascii.hexlify(s[2:3]), 16)
base = 3
elif s[1] == OP_PUSHDATA2:
size = int(binascii.hexlify(s[2:4]), 16)
base = 4
elif s[1] == OP_PUSHDATA4:
size = int(binascii.hexlify(s[2:6]), 16)
base = 6
else:
continue
#print('size =%d' % size)
if size != 101:
continue
nak = NAK.deserialize(s[base:base+101])
if nak is not None:
logging.info('inserting NAK = ' + str(nak))
with self.db.write_batch() as wb:
nkey = binascii.unhexlify(nak.pubkey.compress())
wb.put(nkey, nak.dumpjson().encode('UTF-8'))
self.status['blockcount'] = i
self.blockcount = i
wb.put(_config_key, json.dumps(self.status).encode('UTF-8'))
i += 1
logging.info('checkpointing NAK cache to block %d' % head)
self.status['blockcount'] = head
self.db.put(_config_key, json.dumps(self.status).encode('UTF-8'))
self.status['blockcount'] = current-self.minconf
self.blockcount = current-self.minconf
self.db.put(_config_key, json.dumps(self.status).encode('UTF-8'))
def get_nak(self,keyval):
nakjson = self.db.get(binascii.unhexlify(keyval))
if nakjson is None:
return None
return NAK.loadjson(nakjson.decode('UTF-8'))
if __name__ == "__main__":
ncache = NAKCache(rpcuser='theboss', rpcpass='springst33n')
ncache.sync()
with ncache.db.iterator() as it:
for k,v in it:
print('\nkey = %s' % binascii.hexlify(k))
print('val = %s' % v)