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 { ClrDatagridStringFilterInterface, ClrDatagridNumericFilterInterface, ClrDropdownModule } from '@clr/angular';
declare const fb
@@ -36,13 +36,13 @@ declare const fb
<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">{{line.confirmed.balance | number: '1.8-18'}}</clr-dg-cell>
<clr-dg-cell class="monospace">
<clr-dg-cell class="">{{line.confirmed.balance | number: '1.8-18'}}</clr-dg-cell>
<clr-dg-cell class="">
<span *ngIf="line.unconfirmed.balance != 0">
{{line.unconfirmed.balance | number: '1.8-18'}}
</span>
</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 >
<div class="clr-row">
@@ -101,13 +101,13 @@ declare const fb
<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">{{line.confirmed.balance | number: '1.8-18'}}</clr-dg-cell>
<clr-dg-cell class="monospace">
<clr-dg-cell class="">{{line.confirmed.balance | number: '1.8-18'}}</clr-dg-cell>
<clr-dg-cell class="">
<span *ngIf="line.unconfirmed.balance != 0">
{{line.unconfirmed.balance | number: '1.8-18'}}
</span>
</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 >
<div class="clr-row">
@@ -141,7 +141,8 @@ declare const fb
</div>
`
})
export class AddressViewerComponent implements OnInit{
export class AddressViewerComponent implements OnInit, OnDestroy{
balanceFilter = new BalanceFilter()
otherBalanceFilter = new BalanceFilter()
regularAddresses = []
@@ -161,6 +162,10 @@ export class AddressViewerComponent implements OnInit{
setChangeAddresses(addresses){
this.changeAddresses = addresses
}
ngOnDestroy(): void {
}
}
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 { WalletPickerComponent } from './wallet-picker.component';
import { HDKey } from "btc-hdkey"
import { AddressViewerComponent } from './address-viewer.component';
const fetch = require("node-fetch")
const coinselect = require('coinselect/accumulative')
const coinselect = require('coinselect')
import { TransactionBuilder, Signer } from 'bitcoinjs-lib'
import { networks } from 'bitcoinjs-lib'
import { SubscriptionResponse, ErrorResponse } from 'frontblock-generic/Types';
let feeRate = 55 // satoshis per byte
const hdkey = new HDKey()
@@ -31,7 +32,7 @@ declare const fb
</clr-modal>
<!-- / loading -->
<!-- row 0 -->
<!-- faucets -->
<div *ngIf="mode.net == 'testnet'" class="clr-all-12">
<div class="card">
@@ -51,6 +52,7 @@ declare const fb
</div>
</div>
<!-- /faucets -->
<!-- row 1 -->
<div class="clr-all-12">
@@ -137,9 +139,14 @@ declare const fb
</p>
</div>
<div class="card-footer" >
<button class="btn btn-icon" (click)="reload()"> <clr-icon shape="refresh"></clr-icon> Reload </button>
<div class="card-footer clr-row" style="margin-left: 2px" >
<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>
<!-- Balance box-->
@@ -149,18 +156,59 @@ declare const fb
</div>
<!-- /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">
<address-viewer></address-viewer>
</div>
<!-- address-viewer -->
</div>
<!-- /row 1 -->
`
})
export class PluginsComponent implements AfterViewInit {
export class PluginsComponent implements AfterViewInit, OnDestroy {
timerRefresh: NodeJS.Timeout
errors: string[] = []
successes: string[] = []
wallets: WalletStore = {}
txToSend:any
rootkey: bip32Keypair = { publicExtendedKey: "", privateExtendedKey: "" }
keys: KeyStore = {}
regaddresses: AddressLine[] = []
@@ -181,6 +229,12 @@ export class PluginsComponent implements AfterViewInit {
sendAmount: number
loading = false
loadingN = 1
autorefresh = false
refreshing = false
apiClientPlugin = false
subscriptions = []
transactions = []
@ViewChild(AddressViewerComponent, { static: false })
AddressViewerComponent: AddressViewerComponent
@@ -195,12 +249,17 @@ export class PluginsComponent implements AfterViewInit {
this.WalletGeneratorComponent.setParent(this)
this.WalletPickerComponent.setParent(this)
this.AddressViewerComponent.setParent(this)
this.apiClientPlugin = fb.ApiClient != null
window['btc'] = this
this.timerRefresh = setInterval(async () => { if (this.autorefresh && !this.refreshing && !this.loading) this.refresh() }, 30000)
this.loadKey("tprv8cXm1S7PGS2fHuLjZajuDZZsvxerzv4zZJJAhkLAWZzwz5rE7efHm31xsqpzfoGMHBNC8bkRcsjiMdmkSuNn5C1qNqk7rrk1pCuhk4HfVak")
}
ngOnDestroy(): void {
clearInterval(this.timerRefresh)
}
addWallet(wallet) {
/* store somewhere */
@@ -215,13 +274,10 @@ export class PluginsComponent implements AfterViewInit {
loadKey(key: string) {
this.wallets = {}
this.txToSend = null
this.sendTo = ""
this.regaddresses = []
const t = hdkey.checkHDKey(key)
if (t) {
console.log(t)
this.mode = t
}
@@ -230,29 +286,52 @@ export class PluginsComponent implements AfterViewInit {
}
async reload(): Promise<void> {
if (this.loading || this.refreshing)
return
this.loading = true
this.loadingN = 1
this.keys = {}
this.balanceDisplay.total = 0
this.balanceDisplay.unconfirmed = 0
this.balanceDisplay.confirmed = 0
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
}
async refresh(): Promise<void> {
if (this.refreshing)
return
this.refreshing = true
let p1 = this.updateChange()
let p2 = this.updateBalance()
let balances: GrandTotal[] = await Promise.all([p1, p2])
balances.forEach(balance => {
this.balanceDisplay.confirmed += balance.confirmed
this.balanceDisplay.total += balance.total
this.balanceDisplay.unconfirmed += balance.unconfirmed
this.balanceDisplay = balances.reduce((a, o) => {
a.confirmed += o.confirmed
a.total += o.total
a.unconfirmed += o.unconfirmed
return a
}, {
confirmed: 0,
unconfirmed: 0,
total: 0
})
this.AddressViewerComponent.setChangeAddresses(this.changeaddresses)
this.AddressViewerComponent.setRegularAddresses(this.regaddresses)
this.refreshing = false
}
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){
try{
let r = await fetch(api[type]+'/address/'+address, {
@@ -316,25 +396,40 @@ export class PluginsComponent implements AfterViewInit {
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 url = api[type] + '/address/' + lookupstr + '/unspent'
let txs:getUnspentTxsApiResponse['unspent'] = []
while (true) {
try {
let r = await fetch(api[type]+'/address/'+lookupstr+'/unspent', {
let resp = await fetch(url, {
'method': 'GET',
'mode': 'cors'
})
if(r.status !== 200){
if (resp.status !== 200) {
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) {
console.warn("getUnspentTxs", e)
return { success: false }
}
}
return {
success: true,
unspent: txs
}
}
getKeyForAddress(keyName) {
@@ -445,7 +540,6 @@ They are completely safe and mean no more addresses were found`)
}
async createAndSendTx(target: string, value: number) {
if (target == null || typeof target !== 'string' || target === '' || value == null || value <= 0) {
this.errors.push('Bad inputs. Expected bitcoin address and number')
return
@@ -469,11 +563,10 @@ They are completely safe and mean no more addresses were found`)
address: t.addresses[0],
txId: t.txid,
vout: t.n,
value: t.value * 100000000
value: parseFloat(t.value) * 100000000
}
})
let { inputs, outputs, fee } = coinselect(utxos, [{address: target, value: value*100000000}], feeRate)
let { inputs, outputs, fee } = coinselect(utxos, [{ address: target, value: parseFloat(<any>value) * 100000000 }], feeRate)
// .inputs and .outputs will be undefined if no solution was found
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])
})
this.txToSend = txb.build()
this.sendTx()
await this.sendTx(txb.build())
}
private async sendTx(){
if(this.txToSend == null){
private async sendTx(tx) {
if (tx == null) {
this.errors.push('No transaction to send!')
return
}
@@ -514,17 +605,18 @@ They are completely safe and mean no more addresses were found`)
try {
r = await fetch(url, {
'method': 'POST',
'body': JSON.stringify({'hex': this.txToSend.toHex()})
'body': JSON.stringify({ 'hex': tx.toHex() })
})
} catch (e) {
console.warn("sendTx", e)
return
}
this.txToSend = null
if (r.status === 200) {
this.errors = []
this.successes.push("Sent " + this.sendAmount + " to " + this.sendTo)
this.reload()
this.sendTo = ""
this.sendAmount = 0
//this.reload()
} else {
this.errors.push('The API ' + url + ' returned a non-200 error code ' + r.status + ' ' + r.statusText)
}
@@ -559,7 +651,23 @@ type GrandTotal = {
total: number
}
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 = {
testnet: 'https://testnet-api.smartbit.com.au/v1/blockchain',
mainnet: 'https://api.smartbit.com.au/v1/blockchain'