Code Monkey home page Code Monkey logo

dartsv's Introduction

Introduction

Dart CI

Overview

TwoStack WalletSDK is a Bitcoin library for the Dart Language ( dartlang.org ), loosely based on the Moneybutton/BSV Javascript library. This library has been built in line with the ideals espoused by BitcoinSV, i.e. massive on-chain scaling, protocol stability and original-bitcoin-protocol implementation. It is intended for use in building multi-platform applications using the Flutter framework, or server-side bitcoin applications using frameworks like Serverpod

A note about Version 2.x (August 2023)

Version 2.x of the library is a major refactor and breaks backwards compatibility with several previous library APIs.

  • A new TransactionBuilder class for composing Transactions
  • Removal of the old Builder interface which was directly attached to the Transaction class
  • A complete re-implementation of the Script Interpreter
  • The Sighash class now exposes the SigHash Pre-Image; useful when creating OP_PUSH_TX spending scripts.
  • A new ScriptBuilder class to make it easy to create custom locking/unlocking scripts.
  • Merged contributed code to have better Flutter Web support.

Generally Supported features are :

  • Custom-Script Builder Interface to support novel locking/spending conditions within Script
  • Pre-built library code to support "standard" locking/unlocking scripts
    • P2PKH Transactions
    • P2SH Transactions
    • P2MS Transactions (naked multisig)
    • P2PK Transactions
    • Data-only Transactions (locked with OP_FALSE OP_RETURN)
    • Spendable data-carrier Transactions (locked with PUSH_DATA [your_data] OP_DROP [P2PKH locking code])
  • HD Key Derivation (BIP32)
  • Original Bitcoin Address format
  • Bitcoin Signed Messages
  • Mnemonic Seed Support (BIP39)
  • A built-in Bitcoin Script Interpreter
  • ECIES Encryption / Decryption (Supports Electrum ECIES / BIE1 )

Sample of the Transaction API:

    var utxo = txWithUTXO.outputs[0]; 
    var outpoint = TransactionOutpoint(txWithUTXO.id, 0, utxo.satoshis, utxo.script);
    var signer = TransactionSigner(SighashType.SIGHASH_FORKID.value | SighashType.SIGHASH_ALL.value, privateKey);

    var unlocker = P2PKHUnlockBuilder(privateKey.publicKey);
    
    var transaction = TransactionBuilder()
        .spendFromOutpointWithSigner(signer, outpoint, TransactionInput.MAX_SEQ_NUMBER, unlocker)
        .spendToPKH(recipientAddress, BigInt.from(50000000)) //spend half of a bitcoin 
        .sendChangeToPKH(changeAddress) // spend change to a different address
        .withFeePerKb(50) //set a fee of 50 satoshis per kilobyte
        .build(false); //build the transaction, disabling checks

    //at this point you have a fully signed transaction ready to be broadcast

    try {
      transaction.verify(); //perform a pre-broadcast sanity check on the transaction
    } on VerificationException catch (ex){
      print("Transaction failed verification - ${ex.cause}");  
    }

Installation

This library was built using version 3.0.7 of the Dart SDK( https://dart.dev/tools/sdk ).
As of Version 1.0.0 this library supports Dart Null Safety. Current minimum Dart SDK version required is version 2.17.0.

Navigate to the root folder of this project, and pull the required supported Dart libraries using the pub package manager.

> pub get

Running the Tests

In the root folder of this project, run the command:

> pub run test

Acknowledgement

A debt of gratitude is owed to the developers acknowledged in the LICENSE file. Without the hard work of individuals working on earlier library and node implementations like Bitcoin Core, Bitcoin Cash, MoneyButton/BSV, BitcoinJ and many more, this library would likely not have come to fruition. Thank you.

Contact

You can reach the author at :

dartsv's People

Contributors

chen610620 avatar michalbe avatar rafa-js avatar saiwin123 avatar stephanfeb avatar wouterglorieux avatar

Stargazers

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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

dartsv's Issues

The integer literal 0xFFFFFFFFFFFFFFFF can't be represented exactly in JavaScript.

Hi. I'm trying to use you lib in a Flutter app I'm doing for the web.

I'm getting this error:

Launching lib/main.dart on Chrome in debug mode...
/opt/flutter/.pub-cache/hosted/pub.dartlang.org/dartsv-0.3.3/lib/src/encoding/utils.dart:106:18: Error: The integer literal 0xFFFFFFFFFFFFFFFF can't
be represented exactly in JavaScript.
Try changing the literal to something that can be represented in Javascript. In Javascript 0x10000000000000000 is the nearest value that can be
represented exactly.
    if (length < 0xFFFFFFFFFFFFFFFF) {                                  
                 ^^^^^^^^^^^^^^^^^^                                     
/opt/flutter/.pub-cache/hosted/pub.dartlang.org/dartsv-0.3.3/lib/src/encoding/utils.dart:128:18: Error: The integer literal 0xFFFFFFFFFFFFFFFF can't
be represented exactly in JavaScript.
Try changing the literal to something that can be represented in Javascript. In Javascript 0x10000000000000000 is the nearest value that can be
represented exactly.
    if (length < 0xFFFFFFFFFFFFFFFF) return HEX.decode("FF" + length.toRadixString(16));
                 ^^^^^^^^^^^^^^^^^^                                     
Syncing files to device Chrome...                                  14.4s
Failed to compile application.

I'm using dartsv here:

class Wallet {
String privateKey;
String publicAddress;

Wallet() {
SVPrivateKey privKey = SVPrivateKey(networkType: NetworkType.MAIN);
this.privateKey = privKey.toWIF();
this.publicAddress = privKey.toAddress().toString();
}
}

Flutter 1.24.0-10.2.pre • channel beta • [email protected]:flutter/flutter.git
Framework • revision 022b333a08 (4 weeks ago) • 2020-11-18 11:35:09 -0800
Engine • revision 07c1eed46b
Tools • Dart 2.12.0 (build 2.12.0-29.10.beta)

Invalid WIF generation

Hi. I'm using your lib in a project and I've just found an issue with the private key generated using your lib.
Here there's the code I run to check the issue and the exception I get.

Sometimes, keys converted to WIF come out starting with a "2":

2BmWDrMmcarCt1ukGGpNcjiBhaNDjzggmtvMZ4NDKM5tGC63Yq3W

These key are invalid and cannot be decoded neither using SVPrivateKey.fromWIF(priv);

This is a test I runned:

test('check native privkey wif', () {
for (int i = 0; i < 100; i++) {
SVPrivateKey privKey = SVPrivateKey(networkType: NetworkType.MAIN);
String priv = privKey.toWIF();
String add = privKey.toAddress().toString();
print("$i key: $priv add: $add");
SVPrivateKey reKey = SVPrivateKey.fromWIF(priv);
String readd = reKey.toAddress().toString();
print("$i readd: $readd");
}
});

And this is the result:

~/Code/twostak/dartsv dart test test/privatekey_test.dart
00:06 +0: check native privkey wif
0 key: Ky4XdZFHv1DQXdhPpsiuykTYHgeTG1QLvigX2NwNdrp4UDXfWzBF add: 1JkMQpcU3pikdKGw2hrUD8oAb8EYduuo83
0 readd: 1JkMQpcU3pikdKGw2hrUD8oAb8EYduuo83
1 key: L1SFA8MPhBf1CRAjaNfcUv8ECjGKMzjBonYeFpNpnu565HAUNkJU add: 1EvBMPg6jXR8XzRxvaSuhQkBaf7zwrX8xN
1 readd: 1EvBMPg6jXR8XzRxvaSuhQkBaf7zwrX8xN
2 key: KzxTjfBfcQib9tkgnV2hHbfYsyna6wPidxote5j41kC3iPiHxZwm add: 1HWHQiniMAmCHzav4uj5JqKUmWqvE4aGro
2 readd: 1HWHQiniMAmCHzav4uj5JqKUmWqvE4aGro
3 key: Kya1vUhS5CWginQUpZyyTfUooCsHn77YQYG865nc6yAQwMVGcVZZ add: 1Pmm4RA7jQFVSyA5mukNoktCDrveHa3ibY
3 readd: 1Pmm4RA7jQFVSyA5mukNoktCDrveHa3ibY
4 key: L436bZZ5Kp8QpmST1qdKHqdyXAhuEdLpRnymLuVjiQvZjvgVdbTY add: 1NoneMnDVh3799Vh7SYoFLfURksEEZSJMK
4 readd: 1NoneMnDVh3799Vh7SYoFLfURksEEZSJMK
5 key: Kz44TzLLgb7GFwCF71fGQywhd7jp1tFAgY1imXWYQb84JCWYc57N add: 13Xxc9ehWWc3PVHbHFK3bURD2NdYK6pfYs
5 readd: 13Xxc9ehWWc3PVHbHFK3bURD2NdYK6pfYs
6 key: L4ab43YLvQ83JJfT1KH8haevmUuzS5SYGCdriiGt4U1tQVTHZ9NJ add: 166q27ZCoXSH1BRPBinG1JmcikQobPZZhU
6 readd: 166q27ZCoXSH1BRPBinG1JmcikQobPZZhU
7 key: 2Buv7dE3iz5sYHdsA35izazzyy4yLXrHZCtfpnCKWdNa6arN1BBc add: 13MD7Pe2dmgjQUX7psn3D2XvjH7XNBgHKn
00:06 +0 -1: check native privkey wif [E]
Instance of 'InvalidNetworkException'
package:dartsv/src/privatekey.dart 148:17 new SVPrivateKey.fromWIF
test/privatekey_test.dart 18:41 main.

00:07 +22 -1: Some tests failed.

Generate an address and send and receive Bitcoin

Hi, so I read your example on pub.dev and I want to build a wallet app so, I want to know the following (The example wasn't clear enough for me.) :

  • How do I generate an address to which Bitcoin can be sent?
  • How do I send Bitcoin from my generated address?
  • How do I receive Bitcoin to the address I generated on the device?

If you could provide me with a code-sample, I would be very grateful to you!

error

i use this code but get error
"
E/flutter ( 2251): Bad state: Too few elements
E/flutter ( 2251): #0 _TypedListBase.setRange (dart:typed_data-patch/typed_data_patch.dart:125:11)
E/flutter ( 2251): #1 _IntListMixin.setRange (dart:typed_data-patch/typed_data_patch.dart)
E/flutter ( 2251): #2 HDPrivateKey._deriveChildPrivateKey (package:dartsv/src/hdprivatekey.dart:202:15)
E/flutter ( 2251): #3 HDPrivateKey.deriveChildKey (package:dartsv/src/hdprivatekey.dart:143:19)
E/flutter ( 2251): #4 WalletDatasource.generateHdAddressFromNemonic. (package:zixowallet/data/datasources/wallet.datasource.dart:221:26)
E/flutter ( 2251): #5 _delayEntrypointInvocation. (dart:isolate-patch/isolate_patch.dart:300:17)
E/flutter ( 2251): #6 _RawReceivePort._handleMessage (dart:isolate-patch/isolate_patch.dart:184:12)
E/flutter ( 2251): [ERROR:flutter/runtime/dart_isolate.cc(1097)] Unhandled exception:
"

and my code is
print(
"type is ${type} and index is ${index} and address is m/44/236/0/${type}/${index}");

    print("vvvvvvvvvvvvvvvvvvvv ${hdPrivateKey}");

    HDPrivateKey derivedKey =
        hdPrivateKey.deriveChildKey('m/44/236/0/${type}/${index}');//this line has error

and value in log console is
I/flutter ( 2251): type is 1 and index is 39 and address is m/44/236/0/1/39
I/flutter ( 2251): vvvvvvvvvvvvvvvvvvvv tprv8ZgxMBicQKsPdArVcmqsQPUJJHZbuXZjL59bGVKCkkiUbjjEyfZbZW7Xx6Nx3JKXVMtaNj9968A3EiE

Error

hi
i use it
HDPrivateKey derivedKey =
hdPrivateKey.deriveChildKey('m/44/0/0/${0}/${77}');

        get error 
        E/flutter (27838): [ERROR:flutter/runtime/dart_isolate.cc(1097)] Unhandled exception:

E/flutter (27838): Bad state: Too few elements
E/flutter (27838): #0 _TypedIntListMixin.setRange (dart:typed_data-patch/typed_data_patch.dart:412:7)
E/flutter (27838): #1 HDPrivateKey._deriveChildPrivateKey
hdprivatekey.dart:197
E/flutter (27838): #2 HDPrivateKey.deriveChildKey
hdprivatekey.dart:144
E/flutter (27838): #3 WalletDatasource.generateHdAddressFromNemonic.
wallet.datasource.dart:144
E/flutter (27838): #4 _delayEntrypointInvocation. (dart:isolate-patch/isolate_patch.dart:299:17)
E/flutter (27838): #5 _RawReceivePort._handleMessage (dart:isolate-patch/isolate_patch.dart:189:12)
Reloaded 1 of 1846 libraries in 1,509ms (compile: 58 ms, reload: 781 ms, reassemble: 562 ms).

but use
HDPrivateKey derivedKey =
hdPrivateKey.deriveChildKey('m/44/0/0/${0}/${78}');
not any error

Unsupported operation: Isolate.resolvePackageUri

I'm trying to integrate this library in a Flutter project, however trying to run Mnemonic().generateMnemonic() crashes, as it tries to load the word list using a package uri, and it seems this is not supported by Flutter.

I think the easier fix would be to make the _loadWordlist configurable so it can be changed for another method.

Or is there any way to make it work with flutter?

Thanks in advance

transaction sign failed

this is a error in function signInput at file transacion/transaction.dart .

       // It's normal, not out of range.  => _txnInputs.length > index + 1
        if (_txnInputs.length > index + 1){ 
            throw TransactionException("Input index out of range. Max index is ${_txnInputs.length + 1}");
        }else if (_txnInputs.length == 0) {
            throw TransactionException( "No Inputs defined. Please add some Transaction Inputs");
        }

SVScript.fromString doesn't work correctly

final s = 'OP_0 OP_RETURN 34 0x31346b7871597633656d48477766386d36596753594c516b4743766e395172677239 66 0x303236336661663734633031356630376532633834343538623566333035653262323762366566303838393238383133326435343264633139633436663064663532 OP_PUSHDATA1 150 0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000';
final sc = sv.SVScript.fromString(s);

print(sc.toString() == s); // should be true

Bitcoin Signed Message sometimes produces bad signature

On rare occasions, the encodeBigInt function from pointycastle will return a list of 31 elements instead of 32
see: PointyCastle/pointycastle#181

This doesn't happen very often, but sometimes it causes a Bitcoin Signed Message to have a bad signature that can not be verified because the signature length is 64 instead of 65.
The pull request from pointycastle does fix this, but since that library is no longer maintained, i don't think it will get merged anytime soon.
I was able to fix this issue by just copying the code from the above pull request directly and specifing the correct size in the 'toCompact' function in signature.dart

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.