Skip to content

Commit 484d14a

Browse files
andreasgriffinrustaceanrob
authored andcommitted
test: add python custom persistence
Here we check that an arbitrary persister can persist and load a wallet correctly. The test applies two unconfirmed transactions and asserts that a first wallet that persists the changes and a second wallet that loads from these changes will have the same values.
1 parent e1db09f commit 484d14a

File tree

1 file changed

+327
-0
lines changed

1 file changed

+327
-0
lines changed
Lines changed: 327 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,327 @@
1+
2+
import binascii
3+
import json
4+
import unittest
5+
from typing import Any, Dict, List, Optional
6+
7+
import bdkpython as bdk
8+
9+
initial_txs = [
10+
"0200000000010101d7eb881ab8cac7d6adc6a7f9aa13e694813d95330c7299cee3623e5d14bd590000000000fdffffff02c5e6c1010000000016001407103a1cccf6a1ea654bee964a4020d20c41fb055c819725010000001600146337ec04bf42015e5d077b90cae05c06925c491a0247304402206aae2bf32da4c3b71cb95e6633c22f9f5a4a4f459975965c0c39b0ab439737b702200c4b16d2029383190965b07adeb87e6d634c68c70d2742f25e456874e8dc273a012103930326d6d72f8663340ce4341d0d3bdb1a1c0734d46e5df8a3003ab6bb50073b00000000",
11+
"02000000000101b0db431cffebeeeeec19ee8a09a2ae4755722ea73232dbb99b8e754eaad6ac300100000000fdffffff024ad24201000000001600146a7b71a68b261b0b7c79e5bb00f0f3d65d5ae4a285ae542401000000160014e43ff61232ca20061ef1d241e73f322a149a23d902473044022059f4b2fa8b9da34dbb57e491f3d5b8a47a623d7e6ebc1b6adfe6d2be744c9640022073cfc8311c49a8d48d69076466d32be591d3c0092b965828cfbcaca69fd409c90121027aa62d03db46272fa31bc1a6cb095bb66bc5409dd74b25e88e3099d84a17a3e469000000",
12+
]
13+
descriptor: bdk.Descriptor = bdk.Descriptor(
14+
"wpkh([44250c36/84'/1'/0']tpubDCrUjjHLB1fxk1oRveETjw62z8jsUuqx7JkBUW44VBszGmcY3Eun3apwVcE5X2bfF5MsM3uvuQDed6Do33ZN8GiWcnj2QPqVDspFT1AyZJ9/0/*)",
15+
bdk.Network.REGTEST,
16+
)
17+
change_descriptor: bdk.Descriptor = bdk.Descriptor(
18+
"wpkh([44250c36/84'/1'/0']tpubDCrUjjHLB1fxk1oRveETjw62z8jsUuqx7JkBUW44VBszGmcY3Eun3apwVcE5X2bfF5MsM3uvuQDed6Do33ZN8GiWcnj2QPqVDspFT1AyZJ9/1/*)",
19+
bdk.Network.REGTEST,
20+
)
21+
22+
23+
serialized_persistence = """{"descriptor": "wpkh([44250c36/84'/1'/0']tpubDCrUjjHLB1fxk1oRveETjw62z8jsUuqx7JkBUW44VBszGmcY3Eun3apwVcE5X2bfF5MsM3uvuQDed6Do33ZN8GiWcnj2QPqVDspFT1AyZJ9/0/*)#9q4e992d", "change_descriptor": "wpkh([44250c36/84'/1'/0']tpubDCrUjjHLB1fxk1oRveETjw62z8jsUuqx7JkBUW44VBszGmcY3Eun3apwVcE5X2bfF5MsM3uvuQDed6Do33ZN8GiWcnj2QPqVDspFT1AyZJ9/1/*)#55sccs64", "network": "REGTEST", "local_chain": {"changes": [{"height": 0, "hash": "06226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910f"}]}, "tx_graph": {"txs": ["0200000000010101d7eb881ab8cac7d6adc6a7f9aa13e694813d95330c7299cee3623e5d14bd590000000000fdffffff02c5e6c1010000000016001407103a1cccf6a1ea654bee964a4020d20c41fb055c819725010000001600146337ec04bf42015e5d077b90cae05c06925c491a0247304402206aae2bf32da4c3b71cb95e6633c22f9f5a4a4f459975965c0c39b0ab439737b702200c4b16d2029383190965b07adeb87e6d634c68c70d2742f25e456874e8dc273a012103930326d6d72f8663340ce4341d0d3bdb1a1c0734d46e5df8a3003ab6bb50073b00000000", "02000000000101b0db431cffebeeeeec19ee8a09a2ae4755722ea73232dbb99b8e754eaad6ac300100000000fdffffff024ad24201000000001600146a7b71a68b261b0b7c79e5bb00f0f3d65d5ae4a285ae542401000000160014e43ff61232ca20061ef1d241e73f322a149a23d902473044022059f4b2fa8b9da34dbb57e491f3d5b8a47a623d7e6ebc1b6adfe6d2be744c9640022073cfc8311c49a8d48d69076466d32be591d3c0092b965828cfbcaca69fd409c90121027aa62d03db46272fa31bc1a6cb095bb66bc5409dd74b25e88e3099d84a17a3e469000000"], "txouts": {}, "anchors": [], "last_seen": {"2d2f7cedc21b4272bf57e3eaaeec241959d15bfa7b710ae984ec1ef2b804c1c0": 0, "b0db431cffebeeeeec19ee8a09a2ae4755722ea73232dbb99b8e754eaad6ac30": 0}}, "indexer": {"last_revealed": {"d29ab90c8fe23b5f43f94462e9128ae15368e83d628a466108d64a08c4abd41f": 8}}}"""
24+
25+
26+
class ChangeSetConverter:
27+
@staticmethod
28+
def to_dict(changeset: bdk.ChangeSet) -> Dict:
29+
"""
30+
Serialize a bdk.ChangeSet into a JSON string.
31+
"""
32+
33+
def _serialize_descriptor(descriptor: Optional[bdk.Descriptor]) -> Optional[str]:
34+
if descriptor is None:
35+
return None
36+
return str(descriptor)
37+
38+
def _serialize_blockhash(bh: Optional[bdk.BlockHash]) -> Optional[str]:
39+
if bh is None:
40+
return None
41+
return bh.serialize().hex()
42+
43+
def _serialize_chainchange(cc: bdk.ChainChange) -> Dict[str, Any]:
44+
return {"height": cc.height, "hash": _serialize_blockhash(cc.hash)}
45+
46+
def _serialize_local_chain(local_chain: bdk.LocalChainChangeSet) -> Dict[str, Any]:
47+
return {"changes": [_serialize_chainchange(cc) for cc in local_chain.changes]}
48+
49+
def _serialize_tx(tx: bdk.Transaction) -> str:
50+
return tx.serialize().hex()
51+
52+
def _serialize_outpoint(hop: bdk.HashableOutPoint) -> Dict[str, Any]:
53+
op = hop.outpoint()
54+
txid_hex = op.txid.serialize().hex()
55+
return {"txid": txid_hex, "vout": op.vout}
56+
57+
def _serialize_txout(txout: bdk.TxOut) -> Dict[str, Any]:
58+
# TxOut.script_pubkey is a bdk.Script instance
59+
script_obj: bdk.Script = txout.script_pubkey
60+
script_bytes = script_obj.to_bytes()
61+
return {"value": txout.value, "script_pubkey": script_bytes.hex()}
62+
63+
def _serialize_tx_graph(tx_graph: bdk.TxGraphChangeSet) -> Dict[str, Any]:
64+
txs_list = [_serialize_tx(tx) for tx in tx_graph.txs]
65+
66+
txouts_dict: Dict[str, Dict[str, Any]] = {}
67+
for hop, txout in tx_graph.txouts.items():
68+
key = json.dumps(_serialize_outpoint(hop))
69+
txouts_dict[key] = _serialize_txout(txout)
70+
71+
anchors_list: List[Dict[str, Any]] = []
72+
for anchor in tx_graph.anchors:
73+
cbt = anchor.confirmation_block_time
74+
# Serialize BlockId inside ConfirmationBlockTime
75+
block_id = cbt.block_id
76+
bh_hex = _serialize_blockhash(block_id.hash)
77+
block_id_obj = {"height": block_id.height, "hash": bh_hex}
78+
cbt_obj = {"block_id": block_id_obj, "confirmation_time": cbt.confirmation_time}
79+
try:
80+
txid_hex = anchor.txid.serialize().hex()
81+
except AttributeError:
82+
txid_hex = str(anchor.txid)
83+
anchors_list.append({"confirmation_block_time": cbt_obj, "txid": txid_hex})
84+
85+
last_seen_dict: Dict[str, int] = {}
86+
for txid_obj, height in tx_graph.last_seen.items():
87+
try:
88+
txid_hex = txid_obj.serialize().hex()
89+
except AttributeError:
90+
txid_hex = str(txid_obj)
91+
last_seen_dict[txid_hex] = height
92+
93+
return {
94+
"txs": txs_list,
95+
"txouts": txouts_dict,
96+
"anchors": anchors_list,
97+
"last_seen": last_seen_dict,
98+
}
99+
100+
def _serialize_indexer(indexer: bdk.IndexerChangeSet) -> Dict[str, Any]:
101+
lr: Dict[str, int] = {}
102+
for did_obj, idx in indexer.last_revealed.items():
103+
did_hex = did_obj.serialize().hex()
104+
lr[did_hex] = idx
105+
return {"last_revealed": lr}
106+
107+
out: Dict[str, Any] = {}
108+
out["descriptor"] = _serialize_descriptor(changeset.descriptor())
109+
out["change_descriptor"] = _serialize_descriptor(changeset.change_descriptor())
110+
111+
network = changeset.network()
112+
if network is None:
113+
out["network"] = None
114+
else:
115+
out["network"] = network.name
116+
117+
out["local_chain"] = _serialize_local_chain(changeset.localchain_changeset())
118+
out["tx_graph"] = _serialize_tx_graph(changeset.tx_graph_changeset())
119+
out["indexer"] = _serialize_indexer(changeset.indexer_changeset())
120+
121+
return out
122+
123+
@staticmethod
124+
def from_dict(parsed_json: Dict) -> bdk.ChangeSet:
125+
"""
126+
Deserialize a JSON string back into a bdk.ChangeSet.
127+
"""
128+
129+
def _deserialize_descriptor(
130+
descriptor_str: Optional[str], network: Optional[bdk.Network]
131+
) -> Optional[bdk.Descriptor]:
132+
if descriptor_str is None:
133+
return None
134+
return bdk.Descriptor(descriptor_str, network)
135+
136+
def _deserialize_blockhash(hexstr: Optional[str]) -> Optional[bdk.BlockHash]:
137+
if hexstr is None:
138+
return None
139+
raw = binascii.unhexlify(hexstr)
140+
return bdk.BlockHash.from_bytes(raw)
141+
142+
def _deserialize_chainchange(data: Dict[str, Any]) -> bdk.ChainChange:
143+
height = data["height"]
144+
hash_hex = data["hash"]
145+
bh = _deserialize_blockhash(hash_hex)
146+
return bdk.ChainChange(height=height, hash=bh)
147+
148+
def _deserialize_local_chain(data: Dict[str, Any]) -> bdk.LocalChainChangeSet:
149+
changes_list = data.get("changes", [])
150+
cc_objs: List[bdk.ChainChange] = [_deserialize_chainchange(cc) for cc in changes_list]
151+
return bdk.LocalChainChangeSet(changes=cc_objs)
152+
153+
def _deserialize_tx(hexstr: str) -> bdk.Transaction:
154+
raw = binascii.unhexlify(hexstr)
155+
return bdk.Transaction(raw)
156+
157+
def _deserialize_outpoint(key_str: str) -> bdk.HashableOutPoint:
158+
obj = json.loads(key_str)
159+
txid_hex = obj["txid"]
160+
vout = obj["vout"]
161+
try:
162+
txid_bytes = binascii.unhexlify(txid_hex)
163+
txid_obj = bdk.Txid.from_bytes(txid_bytes)
164+
except Exception:
165+
txid_obj = bdk.Txid(txid_hex)
166+
outpoint = bdk.OutPoint(txid=txid_obj, vout=vout)
167+
return bdk.HashableOutPoint(outpoint=outpoint)
168+
169+
def _deserialize_txout(data: Dict[str, Any]) -> bdk.TxOut:
170+
value = data["value"]
171+
script_hex = data["script_pubkey"]
172+
script_bytes = binascii.unhexlify(script_hex)
173+
script_obj = bdk.Script(raw_output_script=script_bytes)
174+
return bdk.TxOut(value=value, script_pubkey=script_obj)
175+
176+
def _deserialize_tx_graph(data: Dict[str, Any]) -> bdk.TxGraphChangeSet:
177+
tx_hex_list = data.get("txs", [])
178+
tx_objs: List[bdk.Transaction] = [_deserialize_tx(h) for h in tx_hex_list]
179+
180+
txouts_data = data.get("txouts", {})
181+
txouts_dict: Dict[bdk.HashableOutPoint, bdk.TxOut] = {}
182+
for key_str, txout_data in txouts_data.items():
183+
hop = _deserialize_outpoint(key_str)
184+
txout_obj = _deserialize_txout(txout_data)
185+
txouts_dict[hop] = txout_obj
186+
187+
anchors_list: List[bdk.Anchor] = []
188+
for anc in data.get("anchors", []):
189+
cbt_data = anc["confirmation_block_time"]
190+
block_id_data = cbt_data["block_id"]
191+
height = block_id_data["height"]
192+
hash_hex = block_id_data["hash"]
193+
bh = _deserialize_blockhash(hash_hex)
194+
block_id_obj = bdk.BlockId(height=height, hash=bh)
195+
196+
confirmation_time = cbt_data["confirmation_time"]
197+
cbt_obj = bdk.ConfirmationBlockTime(
198+
block_id=block_id_obj, confirmation_time=confirmation_time
199+
)
200+
201+
txid_hex = anc["txid"]
202+
try:
203+
txid_bytes = binascii.unhexlify(txid_hex)
204+
txid_obj = bdk.Txid.from_bytes(txid_bytes)
205+
except Exception:
206+
txid_obj = bdk.Txid(txid_hex)
207+
208+
anchors_list.append(bdk.Anchor(confirmation_block_time=cbt_obj, txid=txid_obj))
209+
210+
last_seen_data = data.get("last_seen", {})
211+
last_seen_dict: Dict[bdk.Txid, int] = {}
212+
for txid_hex, height in sorted(last_seen_data.items()):
213+
try:
214+
txid_obj = bdk.Txid.from_bytes(binascii.unhexlify(txid_hex))
215+
except Exception:
216+
txid_obj = bdk.Txid(txid_hex)
217+
last_seen_dict[txid_obj] = height
218+
219+
return bdk.TxGraphChangeSet(
220+
txs=tx_objs, txouts=txouts_dict, anchors=anchors_list, last_seen=last_seen_dict
221+
)
222+
223+
def _deserialize_indexer(data: Dict[str, Any]) -> bdk.IndexerChangeSet:
224+
lr_data = data.get("last_revealed", {})
225+
lr_dict: Dict[bdk.DescriptorId, int] = {}
226+
for did_hex, idx in lr_data.items():
227+
did_bytes = binascii.unhexlify(did_hex)
228+
did_obj = bdk.DescriptorId.from_bytes(did_bytes)
229+
lr_dict[did_obj] = idx
230+
return bdk.IndexerChangeSet(last_revealed=lr_dict)
231+
232+
net = parsed_json.get("network")
233+
if net is None:
234+
network_obj = None
235+
else:
236+
network_obj = getattr(bdk.Network, net)
237+
238+
descr = _deserialize_descriptor(parsed_json.get("descriptor"), network_obj)
239+
change_descr = _deserialize_descriptor(parsed_json.get("change_descriptor"), network_obj)
240+
local_chain_obj = _deserialize_local_chain(parsed_json["local_chain"])
241+
tx_graph_obj = _deserialize_tx_graph(parsed_json["tx_graph"])
242+
indexer_obj = _deserialize_indexer(parsed_json["indexer"])
243+
244+
changeset = bdk.ChangeSet.from_descriptor_and_network(
245+
descriptor=descr,
246+
change_descriptor=change_descr,
247+
network=network_obj,
248+
)
249+
changeset = bdk.ChangeSet.from_merge(
250+
changeset, bdk.ChangeSet.from_local_chain_changes(local_chain_changes=local_chain_obj)
251+
)
252+
changeset = bdk.ChangeSet.from_merge(
253+
changeset, bdk.ChangeSet.from_tx_graph_changeset(tx_graph_changeset=tx_graph_obj)
254+
)
255+
changeset = bdk.ChangeSet.from_merge(
256+
changeset, bdk.ChangeSet.from_indexer_changeset(indexer_changes=indexer_obj)
257+
)
258+
return changeset
259+
260+
261+
class MyPersistence(bdk.Persistence):
262+
def __init__(self):
263+
self.memory = []
264+
265+
def merge_all(self) -> bdk.ChangeSet:
266+
total_changeset = bdk.ChangeSet()
267+
for changeset_dict in self.memory:
268+
total_changeset = bdk.ChangeSet.from_merge(total_changeset, changeset_dict)
269+
return total_changeset
270+
271+
def initialize(self) -> bdk.ChangeSet:
272+
return self.merge_all()
273+
274+
def persist(self, changeset: bdk.ChangeSet):
275+
self.memory.append(changeset)
276+
277+
278+
class PersistenceTest(unittest.TestCase):
279+
280+
def test_synced_transactions(self):
281+
282+
myp = MyPersistence()
283+
persister = bdk.Persister.custom(myp)
284+
285+
wallet: bdk.Wallet = bdk.Wallet(descriptor, change_descriptor, bdk.Network.REGTEST, persister)
286+
287+
wallet.apply_unconfirmed_txs(
288+
[bdk.UnconfirmedTx(tx=bdk.Transaction(bytes.fromhex(tx)), last_seen=0) for tx in initial_txs]
289+
)
290+
291+
wallet.persist(persister=persister)
292+
293+
# initialize new wallet with memory of myp
294+
myp2 = MyPersistence()
295+
myp2.memory = [ChangeSetConverter.from_dict(json.loads(serialized_persistence))]
296+
persister2 = bdk.Persister.custom(myp2)
297+
298+
wallet2 = bdk.Wallet.load(
299+
descriptor=descriptor,
300+
change_descriptor=change_descriptor,
301+
persister=persister2,
302+
)
303+
304+
# check for equality
305+
outputs = wallet.list_output()
306+
outputs2 = wallet2.list_output()
307+
assert len(outputs) == len(outputs2)
308+
for o, o2 in zip(outputs, outputs2):
309+
assert o.outpoint.txid == o2.outpoint.txid
310+
assert o.outpoint.vout == o2.outpoint.vout
311+
312+
txs = wallet.transactions()
313+
txs2 = wallet2.transactions()
314+
assert txs, "Sync error"
315+
assert len(txs) == len(txs2)
316+
for tx, tx2 in zip(txs, txs2):
317+
assert tx.transaction.compute_txid().serialize() == tx2.transaction.compute_txid().serialize()
318+
319+
assert wallet.balance().total.to_sat() == 50641167
320+
321+
assert json.dumps(ChangeSetConverter.to_dict(myp.initialize())) == json.dumps(
322+
ChangeSetConverter.to_dict(myp2.initialize())
323+
)
324+
325+
326+
if __name__ == "__main__":
327+
unittest.main()

0 commit comments

Comments
 (0)