-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathFakeBlockchainInterface.ts
More file actions
306 lines (275 loc) · 8.82 KB
/
Copy pathFakeBlockchainInterface.ts
File metadata and controls
306 lines (275 loc) · 8.82 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
import { Subject } from 'rxjs';
// @ts-ignore
import bech32_module from 'bech32-buffer';
// @ts-ignore
import * as bech32_buffer from 'bech32-buffer';
import { toUint8 } from '../util';
import { BLOCKCHAIN_SERVICE_URL } from '../settings';
import {
ExternalBlockchainInterface,
InternalBlockchainInterface,
BlockchainInboundAddressResult,
BlockchainReport,
WatchReport,
SelectionMessage,
} from '../types/ChiaGaming';
import {
blockchainConnector,
BlockchainOutboundRequest,
} from './BlockchainConnector';
import { blockchainDataEmitter } from './BlockchainInfo';
const bech32: any = (bech32_module ? bech32_module : bech32_buffer);
function requestBlockData(forWho: any, block_number: number): Promise<any> {
return fetch(`${forWho.baseUrl}/get_block_data?block=${block_number}`, {
method: 'POST',
})
.then((res) => res.json())
.then((res) => {
if (res === null) {
return new Promise((_resolve, _reject) => {
setTimeout(() => {
requestBlockData(forWho, block_number);
}, 100);
});
}
const converted_res: WatchReport = {
created_watched: res.created,
deleted_watched: res.deleted,
timed_out: res.timed_out,
};
forWho.deliverBlock(block_number, converted_res);
});
}
export class FakeBlockchainInterface implements InternalBlockchainInterface {
baseUrl: string;
addressData: BlockchainInboundAddressResult;
deleted: boolean;
at_block: number;
max_block: number;
handlingEvent: boolean;
incomingEvents: any[];
blockEmitter: (b: BlockchainReport) => void;
observable: Subject<BlockchainReport>;
upstream: ExternalBlockchainInterface;
constructor(baseUrl: string) {
this.baseUrl = baseUrl;
this.addressData = { address: '', puzzleHash: '' };
this.deleted = false;
this.max_block = 0;
this.at_block = 0;
this.handlingEvent = false;
this.incomingEvents = [];
this.upstream = new ExternalBlockchainInterface(baseUrl);
this.observable = new Subject();
this.blockEmitter = (b) => this.observable.next(b);
}
async getAddress() {
return this.addressData;
}
startMonitoring(uniqueId: string) {
console.log('startMonitoring', uniqueId);
return this.upstream.getOrRequestToken(uniqueId).then((puzzleHash) => {
const address = bech32.encode('xch', toUint8(puzzleHash), 'bech32m');
this.addressData = { address, puzzleHash };
fetch(`${this.baseUrl}/get_peak`, { method: 'POST' })
.then((res) => res.json())
.then((peak) => {
this.setNewPeak(peak);
});
});
}
getObservable() {
return this.observable;
}
do_initial_spend(uniqueId: string, target: string, amt: number) {
return this.upstream.getOrRequestToken(uniqueId).then((fromPuzzleHash) => {
return this.upstream.createSpendable(target, amt).then((coin) => {
if (!coin) {
throw new Error('no coin returned.');
}
// Returns the coin string
console.log('set opening coin', coin);
return { coin, fromPuzzleHash };
});
});
}
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 handleEvent(event: any) {
if (event.setNewPeak) {
this.internalSetNewPeak(event.setNewPeak);
} else if (event.deliverBlock) {
this.internalDeliverBlock(
event.deliverBlock.block_number,
event.deliverBlock.block_data,
);
}
}
async internalNextBlock() {
if (this.at_block > this.max_block) {
return fetch(`${this.baseUrl}/wait_block`, {
method: 'POST',
})
.then((res) => res.json())
.then((res) => {
// console.log('wait_block returned', res);
this.setNewPeak(res);
});
} else {
return requestBlockData(this, this.at_block);
}
}
async internalSetNewPeak(peak: number) {
if (this.max_block === 0) {
this.max_block = peak;
this.at_block = peak;
} else if (peak > this.max_block) {
this.max_block = peak;
}
return this.internalNextBlock();
}
setNewPeak(peak: number) {
this.pushEvent({ setNewPeak: peak });
}
deliverBlock(block_number: number, block_data: any[]) {
this.pushEvent({ deliverBlock: { block_number, block_data } });
}
internalDeliverBlock(block_number: number, block_data: any[]) {
// console.log('fake::internalDeliverBlock', block_number, block_data);
this.at_block += 1;
this.blockEmitter({
peak: block_number,
block: [],
report: block_data,
});
return this.internalNextBlock();
}
spend(_convert: (blob: string) => any, spendBlob: string): Promise<string> {
return this.upstream.spend(spendBlob).then((status_array) => {
if (status_array.length < 1) {
throw new Error('status result array was empty');
}
if (status_array[0] != 1) {
if (status_array.length != 2) {
throw new Error(`spend status ${status_array[0]} with no detail`);
}
// Could make additional choices on status_array[1]
throw new Error(`spend error status ${status_array}`);
}
// What to return?
return '';
});
}
getBalance(): Promise<number> {
return this.upstream.getBalance();
}
getFeeEstimate(): Promise<number> {
return this.upstream.getFeeEstimate();
}
}
export const fakeBlockchainInfo = new FakeBlockchainInterface(
BLOCKCHAIN_SERVICE_URL,
);
export const FAKE_BLOCKCHAIN_ID = blockchainDataEmitter.addUpstream(
fakeBlockchainInfo.getObservable(),
);
export function connectSimulatorBlockchain() {
blockchainConnector.getOutbound().subscribe({
next: (evt: BlockchainOutboundRequest) => {
let initialSpend = evt.initialSpend;
let transaction = evt.transaction;
let getAddress = evt.getAddress;
let getBalance = evt.getBalance;
let getFee = evt.getFee;
if (initialSpend) {
return fakeBlockchainInfo
.do_initial_spend(
initialSpend.uniqueId,
initialSpend.target,
initialSpend.amount,
)
.then((result: any) => {
blockchainConnector.replyEmitter({
responseId: evt.requestId,
initialSpend: result,
});
})
.catch((e: any) => {
blockchainConnector.replyEmitter({
responseId: evt.requestId,
error: e.toString(),
});
});
} else if (transaction) {
fakeBlockchainInfo
.spend((_blob: string) => transaction.spendObject, transaction.blob)
.then((response: any) => {
blockchainConnector.replyEmitter({
responseId: evt.requestId,
transaction: response,
});
})
.catch((e: any) => {
blockchainConnector.replyEmitter({
responseId: evt.requestId,
error: e.toString(),
});
});
} else if (getAddress) {
fakeBlockchainInfo.getAddress().then((address) => {
blockchainConnector.replyEmitter({
responseId: evt.requestId,
getAddress: address,
});
});
} else if (getBalance) {
fakeBlockchainInfo.getBalance().then((balance) => {
blockchainConnector.replyEmitter({ responseId: evt.requestId, getBalance: balance });
});
} else if (getFee) {
fakeBlockchainInfo.getFeeEstimate().then((fee) => {
blockchainConnector.replyEmitter({ responseId: evt.requestId, getFee: fee });
});
} else {
console.error(`unknown blockchain request type ${JSON.stringify(evt)}`);
blockchainConnector.replyEmitter({
responseId: evt.requestId,
error: `unknown blockchain request type ${JSON.stringify(evt)}`,
});
}
},
});
}
// Set up to receive information about which blockchain system to use.
// The signal from the blockchainDataEmitter will let the downstream system
// choose and also inform us heore of the choice.
blockchainDataEmitter.getSelectionObservable().subscribe({
next: (e: SelectionMessage) => {
if (e.selection == FAKE_BLOCKCHAIN_ID) {
// Simulator selected
console.log('simulator blockchain selected');
fakeBlockchainInfo.startMonitoring(e.uniqueId);
connectSimulatorBlockchain();
}
},
});