-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathRealBlockchainInterface.ts
More file actions
383 lines (350 loc) · 11 KB
/
Copy pathRealBlockchainInterface.ts
File metadata and controls
383 lines (350 loc) · 11 KB
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
import bech32_module from 'bech32-buffer';
import * as bech32_buffer from 'bech32-buffer';
import ReconnectingWebSocket from 'reconnecting-websocket';
import { Subject } from 'rxjs';
import { rpc } from '../hooks/JsonRpcContext';
import {
BlockchainReport,
SelectionMessage,
BlockchainInboundAddressResult,
} from '../types/ChiaGaming';
import { WalletBalance } from '../types/WalletBalance';
import { toHexString, toUint8 } from '../util';
import {
blockchainConnector,
BlockchainOutboundRequest,
} from './BlockchainConnector';
import { blockchainDataEmitter } from './BlockchainInfo';
function wsUrl(baseurl: string) {
const url_with_new_method = baseurl.replace('http', 'ws');
return `${url_with_new_method}/ws`;
}
const bech32: any = (bech32_module ? bech32_module : bech32_buffer);
const PUSH_TX_RETRY_TO_LET_UNCOFIRMED_TRANSACTIONS_BE_CONFIRMED = 30000;
export class RealBlockchainInterface {
baseUrl: string;
addressData: BlockchainInboundAddressResult;
fingerprint?: string;
walletId: number;
requestId: number;
requests: any;
peak: number;
at_block: number;
handlingEvent: boolean;
incomingEvents: any[];
publicKey?: string;
observable: Subject<BlockchainReport>;
ws: any | undefined;
constructor(baseUrl: string) {
this.baseUrl = baseUrl;
this.addressData = { address: '', puzzleHash: '' };
this.walletId = 1;
this.requestId = 1;
this.requests = {};
this.handlingEvent = false;
this.peak = 0;
this.at_block = 0;
this.incomingEvents = [];
this.observable = new Subject();
}
async getAddress() {
return this.addressData;
}
startMonitoring() {
if (this.ws) {
return;
}
this.ws = new ReconnectingWebSocket(wsUrl(this.baseUrl));
this.ws?.addEventListener('message', (m: any) => {
const json = JSON.parse(m.data);
console.log('coinset json', json);
if (json.type === 'peak') {
this.peak = json.data.height;
this.pushEvent({ checkPeak: true });
}
});
}
getObservable() {
return this.observable;
}
does_initial_spend() {
return (target: string, amt: number) => {
const targetXch = bech32.encode('xch', toUint8(target), 'bech32m');
return this.push_request({
method: 'create_spendable',
target,
targetXch,
amt,
});
};
}
set_puzzle_hash(_puzzleHash: string) {
// TODO: Implement puzzle hash setting
}
async internalRetrieveBlock(height: number) {
console.log('full node: retrieve block', height);
const br_height = await fetch(
`${this.baseUrl}/get_block_record_by_height`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: JSON.stringify({ height }),
},
).then((r) => r.json());
console.log('br_height', br_height);
this.at_block = br_height.block_record.height + 1;
const header_hash = br_height.block_record.header_hash;
const br_spends = await fetch(`${this.baseUrl}/get_block_spends`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: JSON.stringify({
header_hash: header_hash,
}),
}).then((r) => r.json());
console.log('br_spends', br_spends.block_spends);
this.observable.next({
peak: this.at_block,
block: br_spends.block_spends,
report: undefined,
});
}
async internalCheckPeak() {
if (this.at_block === 0) {
this.at_block = this.peak;
}
if (this.at_block < this.peak) {
this.pushEvent({ retrieveBlock: this.at_block });
}
}
async handleEvent(evt: any) {
if (evt.checkPeak) {
await this.internalCheckPeak();
return;
} else if (evt.retrieveBlock) {
await this.internalRetrieveBlock(evt.retrieveBlock);
return;
}
console.error('useFullNode: unhandled event', evt);
}
async kickEvent() {
console.log('full node: kickEvent');
while (this.incomingEvents.length) {
console.log('incoming events', this.incomingEvents.length);
this.handlingEvent = true;
try {
const event = this.incomingEvents.shift();
console.log('full node: do event', event);
await this.handleEvent(event);
} catch (e) {
console.log('incoming event failed', e);
} finally {
this.handlingEvent = false;
}
}
}
async pushEvent(evt: any) {
this.incomingEvents.push(evt);
if (!this.handlingEvent) {
await this.kickEvent();
}
}
async push_request(req: any): Promise<any> {
console.log('blockchain: push message to parent', req);
const requestId = this.requestId++;
req.requestId = requestId;
window.parent.postMessage(req, '*');
let promise_complete, promise_reject;
const p = new Promise((comp, rej) => {
promise_complete = comp;
promise_reject = rej;
});
this.requests[requestId] = {
complete: promise_complete,
reject: promise_reject,
requestId: requestId,
};
return p;
}
async spend(spend: any): Promise<string> {
console.log('push_tx', spend);
return await fetch(`${this.baseUrl}/push_tx`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: JSON.stringify({ spend_bundle: spend }),
})
.then((r) => r.json())
.then((r) => {
if (r.error && r.error.indexOf('UNKNOWN_UNSPENT') != -1) {
console.log('unknown unspent, retry in 60 seconds');
return new Promise((resolve, reject) => {
setTimeout(() => {
this.spend(spend)
.then((r) => resolve(r))
.catch(reject);
}, 60000);
});
}
return r;
});
}
}
export const realBlockchainInfo: RealBlockchainInterface =
new RealBlockchainInterface('https://api.coinset.org');
export const REAL_BLOCKCHAIN_ID = blockchainDataEmitter.addUpstream(
realBlockchainInfo.getObservable(),
);
let lastRecvAddress = "";
let logRecvAddress = true;
export function connectRealBlockchain(baseUrl: string) {
blockchainConnector.getOutbound().subscribe({
next: async (evt: BlockchainOutboundRequest) => {
let initialSpend = evt.initialSpend;
let transaction = evt.transaction;
let getAddress = evt.getAddress;
let getBalance = evt.getBalance;
let getFee = evt.getFee;
if (initialSpend) {
try {
const currentAddress = await rpc.getCurrentAddress({
walletId: 1,
});
if (currentAddress !== lastRecvAddress) {
console.log('walletconnect recv currentAddress (initialSpend=true):', currentAddress);
lastRecvAddress = currentAddress;
}
const fromPuzzleHash = toHexString(
bech32.decode(currentAddress).data as any,
);
const result = await rpc.sendTransaction({
walletId: 1,
amount: initialSpend.amount,
fee: 0,
address: bech32.encode(
'xch',
toUint8(initialSpend.target),
'bech32m',
),
waitForConfirmation: false,
});
let resultCoin = undefined;
console.log('walletconnect recv spend result:', result);
if (result.transaction) {
result.transaction.additions.forEach((c) => {
console.log('look at coin', initialSpend.target, c);
if (
c.puzzleHash == '0x' + initialSpend.target &&
c.amount.toString() == initialSpend.amount.toString()
) {
resultCoin = c;
}
});
} else {
resultCoin = (result as any).coin;
}
if (!resultCoin) {
blockchainConnector.replyEmitter({
responseId: evt.requestId,
error: `no corresponding coin created in ${JSON.stringify(result)}`,
});
return;
}
blockchainConnector.replyEmitter({
responseId: evt.requestId,
initialSpend: { coin: resultCoin as any, fromPuzzleHash },
});
} catch (e: any) {
console.log('catch from rpc', evt, ':', e);
blockchainConnector.replyEmitter({
responseId: evt.requestId,
error: JSON.stringify(e),
});
}
} else if (transaction) {
while (true) {
const r = await fetch(`${baseUrl}/push_tx`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: JSON.stringify({ spend_bundle: transaction.spendObject }),
});
const j = await r.json();
// Return if the result was not unknown unspent, in which case we
// retry.
if (!j.error || j.error.indexOf('UNKNOWN_UNSPENT') === -1) {
const result = {
responseId: evt.requestId,
transaction: Object.assign({}, j),
};
blockchainConnector.replyEmitter(result);
return;
}
// Wait a while to try the request again.
await new Promise((resolve, _reject) => {
setTimeout(
resolve,
PUSH_TX_RETRY_TO_LET_UNCOFIRMED_TRANSACTIONS_BE_CONFIRMED,
);
});
}
} else if (getAddress) {
rpc
.getCurrentAddress({
walletId: 1,
})
.then((address) => {
if (address !== lastRecvAddress) {
console.log('walletconnect recv currentAddress:', address);
lastRecvAddress = address;
}
const puzzleHash = toHexString(bech32.decode(address).data as any);
const addressData = { address, puzzleHash };
blockchainConnector.replyEmitter({
responseId: evt.requestId,
getAddress: addressData
});
});
} else if (getFee) {
rpc.getFeeEstimate({}).then((feeResult: number) => {
blockchainConnector.replyEmitter({
responseId: evt.requestId,
getFee: feeResult
});
});
} else if (getBalance) {
rpc.getWalletBalance({
walletId: 1
}).then((balanceResult: WalletBalance) => {
blockchainConnector.replyEmitter({
responseId: evt.requestId,
getBalance: balanceResult.spendableBalance
});
});
} else {
console.error(`unknown blockchain request type ${JSON.stringify(evt)}`);
blockchainConnector.replyEmitter({
responseId: evt.requestId,
error: `unknown blockchain request type ${JSON.stringify(evt)}`,
});
}
},
});
}
blockchainDataEmitter.getSelectionObservable().subscribe({
next: (e: SelectionMessage) => {
if (e.selection == REAL_BLOCKCHAIN_ID) {
console.log('real blockchain selected');
realBlockchainInfo.startMonitoring();
}
},
});