Giter VIP home page Giter VIP logo

bledger's People

Contributors

blusyn avatar braydonf avatar nodech avatar tynes avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

bledger's Issues

Assert MTX Failure when using 2 bcoin libraries

As a consumer of bcoin, I'd like to be able to use bcoin.primitives and then pass them into bledger, but the assert instanceof statements break this functionality because the bledger internal bcoin.primitives are different...

assert(MTX.isMTX(tx), 'Cannot use non-MTX tx for signing');

The above line makes signing impossible to do if I create the MTX using the bcoin from webpack

Non determinism

While testing out the provided examples, I noticed a case of nondeterminism
After cloning the repo down and running npm install:

$ while true; do node examples/bcoin-getXPUBs.js; sleep 1; done

{ Error: Incorrect sequence number.
    at ProtocolReader.readFirstMessage (/Users/marktyneway/Projects/github.com/bpanel-org/bledger/lib/protocol/ledgerprotocol.js:298:10)
    at ProtocolReader.pushMessage (/Users/marktyneway/Projects/github.com/bpanel-org/bledger/lib/protocol/ledgerprotocol.js:356:19)
    at HIDDevice._exchange (/Users/marktyneway/Projects/github.com/bpanel-org/bledger/lib/devices/ledgerhid.js:223:14)
    at <anonymous> type: 'ProtocolError', message: 'Incorrect sequence number.' }
Account: m/44'/0'/0' addresses:
  /0/0: ...
  /1/0: ...

  /0/1: ...
  /1/1: ...

  /0/2: ...
  /1/2: ...

  /0/3: ...
  /1/3: ...

It will sometimes return the addresses as expected in examples/bcoin-getXPUBs.js but other times it will result in the above error

How to get Ledger XPUB ?

I am trying to get XPUB for a ledger from below example. But I cannot get proper xpub for path m/44'/0'/0'.
https://github.com/bcoin-org/bledger/blob/08a9c0dcaa771aa02e609b2b2c4d880723937e71/examples/bcoin-getXPUBs.js

I have tried to get XPUB from HDPublic key from below functions -
xpubs[path].toJSON()
xpubs[path].xpubkey()

But XPUB generated from Mnemonic & bledger library for same path is different.
I have used https://iancoleman.io/bip39/ this website to generate XPUB from Mnemonic.

Need some urgent help.

Installing on OSX

When I run npm install bledger --save I receive the following error:

144 error In file included from ../../nan/nan.h:2884:
144 error ../../nan/nan_typedarray_contents.h:34:43: error: no member named 'GetContents' in 'v8::ArrayBuffer'
144 error       data   = static_cast<char*>(buffer->GetContents().Data()) + byte_offset;
144 error                                   ~~~~~~~~^

Any help is appreciated. Thanks!

Trusted Input Setter

I've noticed that this._trustedInputs is set to true here even when there are no trusted inputs, the code path could follow the continue and never reach the actual fetching of trusted inputs. This could be slightly misleading, is this the intended behavior? I also cannot find any other place where logic exists around this value besides setting it to true and then resetting it to false

this._trustedInputs = true;

Error in multisig transaction with ledger and local key

Hi,

I am trying to do a multisig p2sh transaction, signing first by ledger and then by locally stored key.

This is my current code mostly based on Multi Sig guide and P2SH ledger example

Code:

'use strict';

const fs = require('fs');
const bcoin = require('bcoin');
const assert = require('assert');
const KeyRing = bcoin.wallet.WalletKey;
const Script = bcoin.Script;
const MTX = bcoin.MTX;
const TX = bcoin.TX;
const Amount = bcoin.Amount;
const Coin = bcoin.Coin;

const bledger = require('../lib/bledger');
const {LedgerBcoin, LedgerTXInput} = bledger;
const {Device} = bledger.USB;

const NETWORK = 'testnet';
const compressed = true;

// Read keys from local system
const secret1 = fs.readFileSync(`./${NETWORK}-key1.wif`).toString();
const ring1 = KeyRing.fromSecret(secret1);

(async () => {

    // LEDGER INIT CODE --START
    const device = await Device.requestDevice();
    device.set({timeout: 50000});
    await device.open();
    const path = 'm/44\'/0\'/0\'';
    const path1 = `${path}/1/1`;
    const bcoinApp = new LedgerBcoin({device});
    const hdpub1 = await bcoinApp.getPublicKey(path1);
    const pub1 = hdpub1.publicKey;
    // LEDGER INIT CODE --FINISH

    //Create Script
    const [pk1, pk2] = [hdpub1.publicKey, ring1.publicKey];
    const [m, n] = [2, 2];

    const redeem = Script.fromMultisig(m, n, [pk1, pk2]);
    // p2sh script
    const script = Script.fromScripthash(redeem.hash160());
    const changeAddr = script.getAddress().toBase58(NETWORK);

    // tx info
    const sendTo = '2N4MrGXsu2PtDFMXZrvG34YQxK4Y77bmk7g';
    const txInfo = {
        // How much we received with this transaction
        value: Amount.fromBTC('0.0002').toValue(),

        // prevout txid and vout
        hash: 'aa253ca490d7f1c914246ad459a89c997291da9ca3dc7ec749f6555d2a5aabdf',
        index: 0
    };

    const coin = Coin.fromJSON({
        version: 1,
        height: -1,
        value: txInfo.value,
        coinbase: false,

        script: script.toJSON(),
        hash: txInfo.hash,
        index: txInfo.index
    });

    // Now we create mutable transaction object for signing with ledger
    const spend1 = new MTX();
    spend1.script = redeem;

    // send
    spend1.addOutput({
        address: sendTo,
        value: Amount.fromBTC('0.0001').toValue()
    });


    // send change to ourselves
    spend1.addOutput({
        address: changeAddr,
        value: Amount.fromBTC('0.00005').toValue()
    });

    spend1.addCoin(coin);

    const ledgerInputs = [];

    // Hex of input transaction
    const tx = TX.fromRaw(Buffer.from("01000000000101cdede91d7a739ba4100a46d3287fc20fa683720a39ca2b6e8f474a24570ab86a000000001716001409785e5b583363e2cfcff123be008fef302bd151ffffffff023cf30e000000000017a91470329ef305289ecfe4f2bc6448a6bac4b16b99b887204e00000000000017a9149fd0d66463fafe0ce272189faa4d196ab816ccf787024830450221008a727b5cf7d1f66f1cb3a3311937827a10818d6f8fd6320ebd55df7c5a6d0755022066a4a2f236f01ec6827e7627e5381f1f5ffee56b404d81b44d14ab86b593141d012102e054e792bf5c8e49d2ad73c60a2882e4a34f42db79b0981f95062718dff95a0b00000000", 'hex'))

    const ledgerInput = new LedgerTXInput({
        tx: tx,
        index: 0,
        redeem: redeem,
        path: path,
        publicKey: pub1
    });

    ledgerInputs.push(ledgerInput);

    await bcoinApp.signTransaction(spend1, ledgerInputs);

    //Get raw txn signed by ledger
    const raw = spend1.toRaw();

    // use raw tx to be signed by local key
    const spend2 = MTX.fromRaw(raw);
    spend2.script = redeem;

    // Because input already exists in transaction
    // we only need to provide Coin to CoinView
    spend2.view.addCoin(coin);

    // now we sign
    spend2.signInput(0, coin, ring1);

    //Check if transaction is valid
    assert(spend2.verify(), 'Transaction isnt valid.');

    console.log(spend2.toRaw().toString('hex'));


    await device.close();
})().catch((e) => {
    console.error(e);
    process.exit(1);
});

Currently, It's throwing me following error:

Error: Could not template input.
    at LedgerBcoin.applySignature (/ledger/bcoin/bledger/lib/ledger/ledgerbcoin.js:370:13)
    at LedgerBcoin._signTransaction (/ledger/bcoin/bledger/lib/ledger/ledgerbcoin.js:340:19)

Any pointers on what I am doing wrong?

webauthn support

U2F apis have been deprecated from the browser and replaced with WebAuthN, so in case webusb is not available, using webauthn will still be an option.

Impossible to use with legacy txs

On this line:

assert(!this.isWitness(), 'input script is program.');

If options.witness is false, then it asserts!this.isWitness()
which eventually tries to look at this.coin, which is still assigned a
null value in the constructor, and is not assigned anything until strictly
afterwards in the control flow,

this.coin = Coin.fromTX(this.tx, this.index, 0);

so this code path appears will always throw
an error as this.getCoin returns null and has no property script

  getPrev() {
    if (!this._prev)
      this._prev = this.getCoin().script;

    return this._prev;
  }

Comment Request

More comments around this function would be very useful to understand the bcoin helper functions regarding segwit. It would also be useful for devs consuming the library

getPrevRedeem() {

Signing fails if MTX is serialized first

Using the example bcoin-p2wpkh.js if I serialize/deserialize a the transaction object before trying to sign, the verify will fail:

const trxjson = mtx.getJSON('regtest');
const createdTx = MTX.fromJSON(trxjson);
await bcoinApp.signTransaction(createdTx, ledgerInputs);

In the code above, I tried toJSON() as well.

Dependencies

Consider using peerDependencies for bcoin and in the future bcash.

Even if we provide polymorphic methods wherever possible, we might still bundle two instances of the bcoin and bcash.
#10

Change bcoinLedger api

Right now, it's up to user to open/close device and make sure they manage them correctly.

Instead we can move open/close to LedgerBcoin, that will open/close device automatically. While this might make some operations slower, we can make Batch API that can be used in those cases.

instead we'll have ensureSupport method that will try to open device and make sure it's not busy.

This will make sure that device is not held by process that is not using it actively.
E.g. you may have several apps that want to use ledger and we make sure bledger users don't have to manager opening and closing it.

Feature Request: Parent Fingerprint

When calling device.getPublicKey, it returns a bcoin.HDPublicKey. It would be nice to populate the parentFingerPrint with the appropriate value. I think this would require the client to send 2 requests if that information doesn't come back from the the ledger-btc-app.

My usecase is comparing the equality of public keys and would also be useful for strict bip44 enforced wallets

The parentFingerPrint is always 0

HDPublicKey {
  depth: 3,
  parentFingerPrint: 0,
  childIndex: 2147483648,
  chainCode:
   <Buffer 6b 22 c5 12 3b a1 0a de af 4b fc bb 45 d1 a0 2d 82 8f 25 bf 86 46 95 7a 98 d0 62 87 c4 e2 b8 50>,
  publicKey:
   <Buffer 02 8b 42 cd 47 76 37 6c 82 79 1b 49 41 55 15 1f 56 c2 d7 b4 71 e0 c7 a5 26 a7 ce 60 dd 87 2e 38 67>,
  fingerPrint: -1 }

Bump bcrypto version

Should be 3.0.1. will help to share with other parallel dependencies to have latest.

Bcrypto and Bcoin dependencies.

Unfortunately, bcoin has not been published(or release/tagged) so current bledger will fail to compile on node v12.

Recent PR bcoin-org/bcoin#777 Fixes issues related to v12 build in bcoin.
After release/publish/tag we need to switch to new version.

Another important change is upcoming bcrypto@4 that has some breaking changes in the API, even though they are minor changes we need to update to bcrypto@4 same time as bcoin so we don't have two versions of bcrypto in the project.

bcrypto@4 changes that apply to bledger:

  • toDER/fromDER.

Buffer Set keys

https://github.com/bcoin-org/bledger/blob/master/lib/txstate.js#L146

Using a Set here results in a bug because the lookup is done by reference instead of by value. A buffer with the same value should result in the value being found in the set. Every time that I hit this code path:

https://github.com/bcoin-org/bledger/blob/master/lib/bcoin.js#L242

It cannot find the transaction. If we want to use buffers as keys, maybe we should use the buffer-map module like in bcoin

Here is an example:

> let x = new Set()
undefined
> let y = Buffer.from('hey')
undefined
> x.add(y)
Set { <Buffer 68 65 79> }
> x
Set { <Buffer 68 65 79> }
> x.has(Buffer.from('hey'))
false
> x.has(y)
true

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.