-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathnetwork.js
369 lines (333 loc) · 11.3 KB
/
network.js
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
/* @flow */
const blockstack = require('blockstack');
const Promise = require('bluebird');
const bigi = require('bigi');
const bitcoin = require('bitcoinjs-lib');
Promise.onPossiblyUnhandledRejection(function(error){
throw error;
});
const SATOSHIS_PER_BTC = 1e8
/*
* Adapter class that allows us to use data obtained
* from the CLI.
*/
export class CLINetworkAdapter extends blockstack.network.BlockstackNetwork {
consensusHash: string | null
feeRate: number | null
namespaceBurnAddress: string | null
priceToPay: number | null
priceUnits: string | null
gracePeriod: number | null
constructor(network: blockstack.network.BlockstackNetwork, opts: Object) {
const optsDefault = {
consensusHash: null,
feeRate: null,
namesspaceBurnAddress: null,
priceToPay: null,
priceUnits: null,
receiveFeesPeriod: null,
gracePeriod: null,
altAPIUrl: network.blockstackAPIUrl,
altTransactionBroadcasterUrl: network.broadcastServiceUrl,
nodeAPIUrl: null
}
opts = Object.assign({}, optsDefault, opts);
super(opts.altAPIUrl, opts.altTransactionBroadcasterUrl, network.btc, network.layer1)
this.consensusHash = opts.consensusHash
this.feeRate = opts.feeRate
this.namespaceBurnAddress = opts.namespaceBurnAddress
this.priceToPay = opts.priceToPay
this.priceUnits = opts.priceUnits
this.receiveFeesPeriod = opts.receiveFeesPeriod
this.gracePeriod = opts.gracePeriod
this.nodeAPIUrl = opts.nodeAPIUrl
this.optAlwaysCoerceAddress = false
}
isMainnet() : boolean {
return this.layer1.pubKeyHash === bitcoin.networks.bitcoin.pubKeyHash
}
isTestnet() : boolean {
return this.layer1.pubKeyHash === bitcoin.networks.testnet.pubKeyHash
}
setCoerceMainnetAddress(value: boolean) {
this.optAlwaysCoerceAddress = value
}
coerceMainnetAddress(address: string) : string {
const addressInfo = bitcoin.address.fromBase58Check(address)
const addressHash = addressInfo.hash
const addressVersion = addressInfo.version
let newVersion = 0
if (addressVersion === this.layer1.pubKeyHash) {
newVersion = 0
}
else if (addressVersion === this.layer1.scriptHash) {
newVersion = 5
}
return bitcoin.address.toBase58Check(addressHash, newVersion)
}
getFeeRate() : Promise<number> {
if (this.feeRate) {
// override with CLI option
return Promise.resolve(this.feeRate)
}
if (this.isTestnet()) {
// in regtest mode
return Promise.resolve(Math.floor(0.00001000 * SATOSHIS_PER_BTC))
}
return super.getFeeRate()
}
getConsensusHash() {
// override with CLI option
if (this.consensusHash) {
return new Promise((resolve) => resolve(this.consensusHash))
}
return super.getConsensusHash()
}
getGracePeriod() {
if (this.gracePeriod) {
return this.gracePeriod
}
return super.getGracePeriod()
}
getNamePrice(name: string) {
// override with CLI option
if (this.priceUnits && this.priceToPay) {
return new Promise((resolve) => resolve({
units: String(this.priceUnits),
amount: bigi.fromByteArrayUnsigned(String(this.priceToPay))
}))
}
return super.getNamePrice(name)
.then((priceInfo) => {
// use v2 scheme
if (!priceInfo.units) {
priceInfo = {
units: 'BTC',
amount: bigi.fromByteArrayUnsigned(String(priceInfo))
}
}
return priceInfo;
})
}
getNamespacePrice(namespaceID: string) {
// override with CLI option
if (this.priceUnits && this.priceToPay) {
return new Promise((resolve) => resolve({
units: String(this.priceUnits),
amount: bigi.fromByteArrayUnsigned(String(this.priceToPay))
}))
}
return super.getNamespacePrice(namespaceID)
.then((priceInfo) => {
// use v2 scheme
if (!priceInfo.units) {
priceInfo = {
units: 'BTC',
amount: bigi.fromByteArrayUnsigned(String(priceInfo))
}
}
return priceInfo;
})
}
getNamespaceBurnAddress(namespace: string, useCLI: ?boolean = true) {
// override with CLI option
if (this.namespaceBurnAddress && useCLI) {
return new Promise((resolve) => resolve(this.namespaceBurnAddress))
}
return Promise.all([
fetch(`${this.blockstackAPIUrl}/v1/namespaces/${namespace}`),
this.getBlockHeight()
])
.then(([resp, blockHeight]) => {
if (resp.status === 404) {
throw new Error(`No such namespace '${namespace}'`)
} else if (resp.status !== 200) {
throw new Error(`Bad response status: ${resp.status}`)
} else {
return Promise.all([resp.json(), blockHeight])
}
})
.then(([namespaceInfo, blockHeight]) => {
let address = '1111111111111111111114oLvT2' // default burn address
if (namespaceInfo.version === 2) {
// pay-to-namespace-creator if this namespace is less than $receiveFeesPeriod blocks old
if (namespaceInfo.reveal_block + this.receiveFeesPeriod > blockHeight) {
address = namespaceInfo.address
}
}
return address
})
.then(address => this.coerceAddress(address))
}
getNameInfo(name: string) {
// optionally coerce addresses
return super.getNameInfo(name)
.then((nameInfo) => {
if (this.optAlwaysCoerceAddress) {
nameInfo = Object.assign(nameInfo, {
'address': this.coerceMainnetAddress(nameInfo.address)
})
}
return nameInfo
})
}
getBlockchainNameRecordLegacy(name: string) : Promise<*> {
// legacy code path.
if (!this.nodeAPIUrl) {
throw new Error("No indexer URL given. Pass -I.")
}
// this is EVIL code, and I'm a BAD PERSON for writing it.
// will be removed once the /v1/blockchains/${blockchain}/names/${name} endpoint ships.
const postData = '<?xml version="1.0"?>' +
'<methodCall><methodName>get_name_blockchain_record</methodName>' +
'<params><param><string>' +
`${name}` +
'</string></param></params>' +
'</methodCall>'
// try and guess which node we're talking to
// (reminder: this is EVIL CODE that WILL BE REMOVED as soon as possible)
return fetch(`${this.nodeAPIUrl}/RPC2`,
{ method: 'POST',
body: postData })
.then((resp) => {
if (resp.status >= 200 && resp.status <= 299){
return resp.text();
}
else {
throw new Error(`Bad response code: ${resp.status}`);
}
})
.then((respText) => {
// response is a single string
const start = respText.indexOf('<string>') + '<string>'.length
const stop = respText.indexOf('</string>')
const dataResp = respText.slice(start, stop);
let dataJson = null;
try {
dataJson = JSON.parse(dataResp);
if (!dataJson.record) {
// error response
return dataJson
}
const nameRecord = dataJson.record;
if (nameRecord.hasOwnProperty('history')) {
// don't return history, since this is not expected in the new API
delete nameRecord.history;
}
return nameRecord;
}
catch(e) {
throw new Error('Invalid JSON returned (legacy codepath)');
}
});
}
getBlockchainNameRecord(name: string) : Promise<*> {
// TODO: send to blockstack.js, once we can drop the legacy code path
const url = `${this.blockstackAPIUrl}/v1/blockchains/bitcoin/names/${name}`
return fetch(url)
.then((resp) => {
if (resp.status !== 200) {
return this.getBlockchainNameRecordLegacy(name);
}
else {
return resp.json();
}
})
.then((nameInfo) => {
// coerce all addresses
let fixedAddresses = {}
for (let addrAttr of ['address', 'importer_address', 'recipient_address']) {
if (nameInfo.hasOwnProperty(addrAttr) && nameInfo[addrAttr]) {
fixedAddresses[addrAttr] = this.coerceAddress(nameInfo[addrAttr])
}
}
return Object.assign(nameInfo, fixedAddresses)
})
}
getNameHistory(name: string, page: number) : Promise<*> {
// TODO: send to blockstack.js
const url = `${this.blockstackAPIUrl}/v1/names/${name}/history?page=${page}`
return fetch(url)
.then((resp) => {
if (resp.status !== 200) {
throw new Error(`Bad response status: ${resp.status}`)
}
return resp.json();
})
.then((historyInfo) => {
// coerce all addresses
let fixedHistory = {}
for (let historyBlock of Object.keys(historyInfo)) {
let fixedHistoryList = []
for (let historyEntry of historyInfo[historyBlock]) {
let fixedAddresses = {}
let fixedHistoryEntry = null
for (let addrAttr of ['address', 'importer_address', 'recipient_address']) {
if (historyEntry.hasOwnProperty(addrAttr) && historyEntry[addrAttr]) {
fixedAddresses[addrAttr] = this.coerceAddress(historyEntry[addrAttr])
}
}
fixedHistoryEntry = Object.assign(historyEntry, fixedAddresses)
fixedHistoryList.push(fixedHistoryEntry)
}
fixedHistory[historyBlock] = fixedHistoryList
}
return fixedHistory
})
}
// stub out accounts
getAccountStatus(address: string) : Promise<*> {
if (!super.getAccountStatus) {
throw new Error('Getting an account status is not yet implemented in blockstack.js');
}
return super.getAccountStatus(address);
}
// stub out accounts
getAccountHistoryPage(address: string, page: number): Promise<*> {
if (!super.getAccountHistoryPage) {
return Promise.resolve().then(() => []);
}
return super.getAccountHistoryPage(address, page);
}
// stub out accounts
getAccountBalance(address: string, tokenType: string): Promise<*> {
if (!super.getAccountBalance) {
return Promise.resolve().then(() => bigi.fromByteArrayUnsigned('0'));
}
return super.getAccountBalance(address, tokenType);
}
// stub out accounts
getAccountAt(address: string, blockHeight: number): Promise<*> {
if (!super.getAccountAt) {
return Promise.resolve().then(() => []);
}
return super.getAccountAt(address, blockHeight);
}
// stub out accounts
getAccountTokens(address: string): Promise<*> {
if (!super.getAccountTokens) {
return Promise.resolve().then(() => {
return { tokens: [] };
});
}
return super.getAccountTokens(address);
}
}
/*
* Instantiate a network using settings from the config file.
*/
export function getNetwork(configData: Object, regTest: boolean)
: blockstack.network.BlockstackNetwork {
if (regTest) {
const network = new blockstack.network.LocalRegtest(
configData.blockstackAPIUrl, configData.broadcastServiceUrl,
new blockstack.network.BitcoindAPI(configData.utxoServiceUrl,
{ username: 'blockstack', password: 'blockstacksystem' }))
return network
} else {
const network = new blockstack.network.BlockstackNetwork(
configData.blockstackAPIUrl, configData.broadcastServiceUrl,
new blockstack.network.BlockchainInfoApi(configData.utxoServiceUrl))
return network
}
}