broken wallet but ok

This commit is contained in:
peter
2019-08-17 14:16:00 +02:00
parent 92666ba0c0
commit 8a46c56211
2 changed files with 301 additions and 188 deletions
@@ -1,6 +1,6 @@
import { Component, OnInit, isDevMode } from '@angular/core'; import { Component, OnInit, isDevMode, OnDestroy } from '@angular/core';
import { PluginsComponent } from './btc.component'; import { PluginsComponent } from './btc.component';
import { ClrDatagridStringFilterInterface, ClrDatagridNumericFilterInterface, ClrDropdownModule } from '@clr/angular'; import { ClrDatagridStringFilterInterface, ClrDatagridNumericFilterInterface, ClrDropdownModule } from '@clr/angular';
declare const fb declare const fb
@@ -36,13 +36,13 @@ declare const fb
<clr-dg-row *clrDgItems="let line of regularAddresses"> <clr-dg-row *clrDgItems="let line of regularAddresses">
<clr-dg-cell class="monospace" style="word-break: break-all">{{line.address}}</clr-dg-cell> <clr-dg-cell class="monospace" style="word-break: break-all">{{line.address}}</clr-dg-cell>
<clr-dg-cell class="monospace">{{line.confirmed.balance | number: '1.8-18'}}</clr-dg-cell> <clr-dg-cell class="">{{line.confirmed.balance | number: '1.8-18'}}</clr-dg-cell>
<clr-dg-cell class="monospace"> <clr-dg-cell class="">
<span *ngIf="line.unconfirmed.balance != 0"> <span *ngIf="line.unconfirmed.balance != 0">
{{line.unconfirmed.balance | number: '1.8-18'}} {{line.unconfirmed.balance | number: '1.8-18'}}
</span> </span>
</clr-dg-cell> </clr-dg-cell>
<clr-dg-cell class="monospace">{{line.total.balance | number: '1.8-18'}}</clr-dg-cell> <clr-dg-cell class="">{{line.total.balance | number: '1.8-18'}}</clr-dg-cell>
<clr-dg-row-detail *clrIfExpanded > <clr-dg-row-detail *clrIfExpanded >
<div class="clr-row"> <div class="clr-row">
@@ -101,13 +101,13 @@ declare const fb
<clr-dg-row *clrDgItems="let line of changeAddresses"> <clr-dg-row *clrDgItems="let line of changeAddresses">
<clr-dg-cell class="monospace" style="word-break: break-all">{{line.address}}</clr-dg-cell> <clr-dg-cell class="monospace" style="word-break: break-all">{{line.address}}</clr-dg-cell>
<clr-dg-cell class="monospace">{{line.confirmed.balance | number: '1.8-18'}}</clr-dg-cell> <clr-dg-cell class="">{{line.confirmed.balance | number: '1.8-18'}}</clr-dg-cell>
<clr-dg-cell class="monospace"> <clr-dg-cell class="">
<span *ngIf="line.unconfirmed.balance != 0"> <span *ngIf="line.unconfirmed.balance != 0">
{{line.unconfirmed.balance | number: '1.8-18'}} {{line.unconfirmed.balance | number: '1.8-18'}}
</span> </span>
</clr-dg-cell> </clr-dg-cell>
<clr-dg-cell class="monospace">{{line.total.balance | number: '1.8-18'}}</clr-dg-cell> <clr-dg-cell class="">{{line.total.balance | number: '1.8-18'}}</clr-dg-cell>
<clr-dg-row-detail *clrIfExpanded > <clr-dg-row-detail *clrIfExpanded >
<div class="clr-row"> <div class="clr-row">
@@ -141,7 +141,8 @@ declare const fb
</div> </div>
` `
}) })
export class AddressViewerComponent implements OnInit{ export class AddressViewerComponent implements OnInit, OnDestroy{
balanceFilter = new BalanceFilter() balanceFilter = new BalanceFilter()
otherBalanceFilter = new BalanceFilter() otherBalanceFilter = new BalanceFilter()
regularAddresses = [] regularAddresses = []
@@ -161,6 +162,10 @@ export class AddressViewerComponent implements OnInit{
setChangeAddresses(addresses){ setChangeAddresses(addresses){
this.changeAddresses = addresses this.changeAddresses = addresses
} }
ngOnDestroy(): void {
}
} }
class BalanceFilter implements ClrDatagridNumericFilterInterface<any>{ class BalanceFilter implements ClrDatagridNumericFilterInterface<any>{
@@ -1,12 +1,13 @@
import { Component, OnInit, isDevMode, ViewChild, AfterViewInit } from '@angular/core'; import { Component, OnInit, isDevMode, ViewChild, AfterViewInit, OnDestroy } from '@angular/core';
import { WalletGeneratorComponent } from './wallet-generator.component'; import { WalletGeneratorComponent } from './wallet-generator.component';
import { WalletPickerComponent } from './wallet-picker.component'; import { WalletPickerComponent } from './wallet-picker.component';
import { HDKey } from "btc-hdkey" import { HDKey } from "btc-hdkey"
import { AddressViewerComponent } from './address-viewer.component'; import { AddressViewerComponent } from './address-viewer.component';
const fetch = require("node-fetch") const fetch = require("node-fetch")
const coinselect = require('coinselect/accumulative') const coinselect = require('coinselect')
import { TransactionBuilder, Signer } from 'bitcoinjs-lib' import { TransactionBuilder, Signer } from 'bitcoinjs-lib'
import { networks } from 'bitcoinjs-lib' import { networks } from 'bitcoinjs-lib'
import { SubscriptionResponse, ErrorResponse } from 'frontblock-generic/Types';
let feeRate = 55 // satoshis per byte let feeRate = 55 // satoshis per byte
const hdkey = new HDKey() const hdkey = new HDKey()
@@ -31,7 +32,7 @@ declare const fb
</clr-modal> </clr-modal>
<!-- / loading --> <!-- / loading -->
<!-- row 0 --> <!-- faucets -->
<div *ngIf="mode.net == 'testnet'" class="clr-all-12"> <div *ngIf="mode.net == 'testnet'" class="clr-all-12">
<div class="card"> <div class="card">
@@ -51,6 +52,7 @@ declare const fb
</div> </div>
</div> </div>
<!-- /faucets -->
<!-- row 1 --> <!-- row 1 -->
<div class="clr-all-12"> <div class="clr-all-12">
@@ -137,9 +139,14 @@ declare const fb
</p> </p>
</div> </div>
<div class="card-footer" > <div class="card-footer clr-row" style="margin-left: 2px" >
<button class="btn btn-icon" (click)="reload()"> <clr-icon shape="refresh"></clr-icon> Reload </button> <button *ngIf="!autorefresh" class="btn btn-icon clr-col-4" (click)="reload()"> <clr-icon shape="refresh"></clr-icon> Reload </button>
<clr-toggle-wrapper class="clr-col-auto clr-align-self-center">
<input type="checkbox" clrToggle [(ngModel)]="autorefresh" />
<label>Autorefresh</label>
</clr-toggle-wrapper>
</div> </div>
</div> </div>
<!-- Balance box--> <!-- Balance box-->
@@ -149,18 +156,59 @@ declare const fb
</div> </div>
<!-- /row wallet picker + send box + balance box --> <!-- /row wallet picker + send box + balance box -->
<!-- live-tx -->
<div class="clr-row" *ngIf="apiClientPlugin && transactions.length != 0" >
<div class="clr-col-12">
<div class="clr-all-12" style="padding-left:0px; padding-right: 0px">
<div class="card">
<div class="card-header">
Live Transactions
</div>
<div class="card-block" >
<table class="table table-compact">
<thead>
<tr>
<th>Hash</th>
<th>Amount</th>
<th>Status</th>
<th>To</th>
<th>From</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let line of transactions">
<td style="word-break:break-all">{{line.hash}}</td>
<td>{{line.amount}}</td>
<td>{{line.status}}</td>
<td style="word-break:break-all">{{line.to}}</td>
<td style="word-break:break-all">{{line.from.join(', ')}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<!-- /live-tx -->
<!-- address-viewer -->
<div class="clr-all-12" style="padding-left:0px; padding-right: 0px"> <div class="clr-all-12" style="padding-left:0px; padding-right: 0px">
<address-viewer></address-viewer> <address-viewer></address-viewer>
</div> </div>
<!-- address-viewer -->
</div> </div>
<!-- /row 1 --> <!-- /row 1 -->
` `
}) })
export class PluginsComponent implements AfterViewInit { export class PluginsComponent implements AfterViewInit, OnDestroy {
timerRefresh: NodeJS.Timeout
errors: string[] = [] errors: string[] = []
successes: string[] = [] successes: string[] = []
wallets: WalletStore = {} wallets: WalletStore = {}
txToSend:any
rootkey: bip32Keypair = { publicExtendedKey: "", privateExtendedKey: "" } rootkey: bip32Keypair = { publicExtendedKey: "", privateExtendedKey: "" }
keys: KeyStore = {} keys: KeyStore = {}
regaddresses: AddressLine[] = [] regaddresses: AddressLine[] = []
@@ -181,6 +229,12 @@ export class PluginsComponent implements AfterViewInit {
sendAmount: number sendAmount: number
loading = false loading = false
loadingN = 1 loadingN = 1
autorefresh = false
refreshing = false
apiClientPlugin = false
subscriptions = []
transactions = []
@ViewChild(AddressViewerComponent, { static: false }) @ViewChild(AddressViewerComponent, { static: false })
AddressViewerComponent: AddressViewerComponent AddressViewerComponent: AddressViewerComponent
@@ -195,12 +249,17 @@ export class PluginsComponent implements AfterViewInit {
this.WalletGeneratorComponent.setParent(this) this.WalletGeneratorComponent.setParent(this)
this.WalletPickerComponent.setParent(this) this.WalletPickerComponent.setParent(this)
this.AddressViewerComponent.setParent(this) this.AddressViewerComponent.setParent(this)
this.apiClientPlugin = fb.ApiClient != null
window['btc'] = this window['btc'] = this
this.timerRefresh = setInterval(async () => { if (this.autorefresh && !this.refreshing && !this.loading) this.refresh() }, 30000)
this.loadKey("tprv8cXm1S7PGS2fHuLjZajuDZZsvxerzv4zZJJAhkLAWZzwz5rE7efHm31xsqpzfoGMHBNC8bkRcsjiMdmkSuNn5C1qNqk7rrk1pCuhk4HfVak") this.loadKey("tprv8cXm1S7PGS2fHuLjZajuDZZsvxerzv4zZJJAhkLAWZzwz5rE7efHm31xsqpzfoGMHBNC8bkRcsjiMdmkSuNn5C1qNqk7rrk1pCuhk4HfVak")
} }
ngOnDestroy(): void {
clearInterval(this.timerRefresh)
}
addWallet(wallet) { addWallet(wallet) {
/* store somewhere */ /* store somewhere */
@@ -215,13 +274,10 @@ export class PluginsComponent implements AfterViewInit {
loadKey(key: string) { loadKey(key: string) {
this.wallets = {} this.wallets = {}
this.txToSend = null
this.sendTo = ""
this.regaddresses = [] this.regaddresses = []
const t = hdkey.checkHDKey(key) const t = hdkey.checkHDKey(key)
if (t) { if (t) {
console.log(t)
this.mode = t this.mode = t
} }
@@ -230,29 +286,52 @@ export class PluginsComponent implements AfterViewInit {
} }
async reload(): Promise<void> { async reload(): Promise<void> {
if (this.loading || this.refreshing)
return
this.loading = true this.loading = true
this.loadingN = 1 this.loadingN = 1
this.keys = {} this.keys = {}
this.balanceDisplay.total = 0
this.balanceDisplay.unconfirmed = 0
this.balanceDisplay.confirmed = 0
await this.refresh() await this.refresh()
if (fb.ApiClient) {
const res: (SubscriptionResponse | ErrorResponse)[] = await Promise.all([...this.regaddresses, ...this.changeaddresses].map(async a => await fb.ApiClient.subsume("BTC", { address: a.address }, tx => { console.log(tx); this.transactions.unshift(tx) })))
this.subscriptions.push(res.map(r => {
if (r.result = "Success") {
return r.message
} else {
return
}
}))
}
this.loading = false this.loading = false
} }
async refresh(): Promise<void> { async refresh(): Promise<void> {
if (this.refreshing)
return
this.refreshing = true
let p1 = this.updateChange() let p1 = this.updateChange()
let p2 = this.updateBalance() let p2 = this.updateBalance()
let balances: GrandTotal[] = await Promise.all([p1, p2]) let balances: GrandTotal[] = await Promise.all([p1, p2])
balances.forEach(balance => {
this.balanceDisplay.confirmed += balance.confirmed this.balanceDisplay = balances.reduce((a, o) => {
this.balanceDisplay.total += balance.total a.confirmed += o.confirmed
this.balanceDisplay.unconfirmed += balance.unconfirmed a.total += o.total
a.unconfirmed += o.unconfirmed
return a
}, {
confirmed: 0,
unconfirmed: 0,
total: 0
}) })
this.AddressViewerComponent.setChangeAddresses(this.changeaddresses) this.AddressViewerComponent.setChangeAddresses(this.changeaddresses)
this.AddressViewerComponent.setRegularAddresses(this.regaddresses) this.AddressViewerComponent.setRegularAddresses(this.regaddresses)
this.refreshing = false
} }
getAddresses(rootAddr: string, n = 10, skip = 0, changeAddresses = false): string[] | null { getAddresses(rootAddr: string, n = 10, skip = 0, changeAddresses = false): string[] | null {
@@ -301,6 +380,7 @@ export class PluginsComponent implements AfterViewInit {
} }
/*
async getTxs(address: string, type:networkType){ async getTxs(address: string, type:networkType){
try{ try{
let r = await fetch(api[type]+'/address/'+address, { let r = await fetch(api[type]+'/address/'+address, {
@@ -316,25 +396,40 @@ export class PluginsComponent implements AfterViewInit {
console.warn ("getTxs", e) console.warn ("getTxs", e)
} }
} }
*/
async getUnspentTxs(addresses:string[], type:networkType):Promise<any>{ async getUnspentTxs(addresses: string[], type: networkType): Promise<getUnspentTxsApiResponse> {
let lookupstr = addresses.join(',') let lookupstr = addresses.join(',')
let url = api[type] + '/address/' + lookupstr + '/unspent'
let txs:getUnspentTxsApiResponse['unspent'] = []
while (true) {
try { try {
let r = await fetch(api[type]+'/address/'+lookupstr+'/unspent', {
let resp = await fetch(url, {
'method': 'GET', 'method': 'GET',
'mode': 'cors' 'mode': 'cors'
}) })
if(r.status !== 200){ if (resp.status !== 200) {
return { success: false } return { success: false }
} }
const json: getUnspentTxsApiResponse = await resp.json()
if (!json.success)
break;
return (await r).json() txs = [...txs, ...(json.unspent?json.unspent:[])]
if(!json.paging.next_link)
break;
url = json.paging.next_link
} catch (e) { } catch (e) {
console.warn("getUnspentTxs", e) console.warn("getUnspentTxs", e)
return { success: false } return { success: false }
} }
} }
return {
success: true,
unspent: txs
}
}
getKeyForAddress(keyName) { getKeyForAddress(keyName) {
@@ -445,7 +540,6 @@ They are completely safe and mean no more addresses were found`)
} }
async createAndSendTx(target: string, value: number) { async createAndSendTx(target: string, value: number) {
if (target == null || typeof target !== 'string' || target === '' || value == null || value <= 0) { if (target == null || typeof target !== 'string' || target === '' || value == null || value <= 0) {
this.errors.push('Bad inputs. Expected bitcoin address and number') this.errors.push('Bad inputs. Expected bitcoin address and number')
return return
@@ -469,11 +563,10 @@ They are completely safe and mean no more addresses were found`)
address: t.addresses[0], address: t.addresses[0],
txId: t.txid, txId: t.txid,
vout: t.n, vout: t.n,
value: t.value * 100000000 value: parseFloat(t.value) * 100000000
} }
}) })
let { inputs, outputs, fee } = coinselect(utxos, [{ address: target, value: parseFloat(<any>value) * 100000000 }], feeRate)
let { inputs, outputs, fee } = coinselect(utxos, [{address: target, value: value*100000000}], feeRate)
// .inputs and .outputs will be undefined if no solution was found // .inputs and .outputs will be undefined if no solution was found
if (!inputs || !outputs) { if (!inputs || !outputs) {
@@ -498,13 +591,11 @@ They are completely safe and mean no more addresses were found`)
txb.sign(i, <Signer>this.keys[input.address]) txb.sign(i, <Signer>this.keys[input.address])
}) })
this.txToSend = txb.build() await this.sendTx(txb.build())
this.sendTx()
} }
private async sendTx(){ private async sendTx(tx) {
if(this.txToSend == null){ if (tx == null) {
this.errors.push('No transaction to send!') this.errors.push('No transaction to send!')
return return
} }
@@ -514,17 +605,18 @@ They are completely safe and mean no more addresses were found`)
try { try {
r = await fetch(url, { r = await fetch(url, {
'method': 'POST', 'method': 'POST',
'body': JSON.stringify({'hex': this.txToSend.toHex()}) 'body': JSON.stringify({ 'hex': tx.toHex() })
}) })
} catch (e) { } catch (e) {
console.warn("sendTx", e) console.warn("sendTx", e)
return return
} }
this.txToSend = null
if (r.status === 200) { if (r.status === 200) {
this.errors = [] this.errors = []
this.successes.push("Sent " + this.sendAmount + " to " + this.sendTo) this.successes.push("Sent " + this.sendAmount + " to " + this.sendTo)
this.reload() this.sendTo = ""
this.sendAmount = 0
//this.reload()
} else { } else {
this.errors.push('The API ' + url + ' returned a non-200 error code ' + r.status + ' ' + r.statusText) this.errors.push('The API ' + url + ' returned a non-200 error code ' + r.status + ' ' + r.statusText)
} }
@@ -559,7 +651,23 @@ type GrandTotal = {
total: number total: number
} }
type bip32Keypair = { publicExtendedKey: string, privateExtendedKey: string } type bip32Keypair = { publicExtendedKey: string, privateExtendedKey: string }
type getUnspentTxsApiResponse = {
success: boolean,
paging?: {
next_link: string | null
}
unspent?: {
addresses: string[],
confirmations: number,
id: number, n: number,
req_sigs: number,
script_pub_key: any,
txid: string,
type: string,
value: string,
value_int: number
}[]
}
const api = { const api = {
testnet: 'https://testnet-api.smartbit.com.au/v1/blockchain', testnet: 'https://testnet-api.smartbit.com.au/v1/blockchain',
mainnet: 'https://api.smartbit.com.au/v1/blockchain' mainnet: 'https://api.smartbit.com.au/v1/blockchain'