Bitcoin SV Library for Java

Overview

Introduction

Java CI

Overview

Bitcoin4J is a Bitcoin library for the Java Language licensed under the Apache License 2.0.

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.

Learn More about BitcoinSV

You can learn more about BitcoinSV by visiting :

Installation

Binaries for the library are available on Maven Central.

Gradle Dependencies

implementation("org.twostack:bitcoin4j:1.4.1")

Maven Dependencies

<dependency>
  <groupId>org.twostack</groupId>
  <artifactId>bitcoin4j</artifactId>
  <version>1.4.1</version>
</dependency>

Clean Transaction Builder

Several helper classes and APIs exist to make constructing Transactions more intuitive.

See the full example source code

As a native Java implementation, the library integrates well with other JVM languages, e.g. Kotlin.

    val txBuilder: TransactionBuilder = TransactionBuilder()
    val spendingTx: Transaction = txBuilder.spendFromTransaction(aliceFundingTx, 1, Transaction.NLOCKTIME_MAX_VALUE, unlockBuilder)
        .spendTo(bobLockingBuilder, BigInteger.valueOf(10000))
        .sendChangeTo(aliceAddress, aliceLockingBuilder)
        .withFeePerKb(512)
        .build(true)

Features

  • Unbounded Transaction Types (creating non-standard transactions)
  • HD Key Derivation (BIP32)
  • Mnemonic Seed Support (BIP39)
  • Original Bitcoin Address format
  • A built-in Bitcoin Script Interpreter
  • Custom-Script Builder Interface to support novel locking/spending conditions within Script
    • P2PKH Transaction Builder - Pay to Pubkey Hash standard Transactions
    • P2MS Transaction Builder - Pay to Multisig. This is naked MultiSig (the proper way to do multisig).
    • P2PK Transaction Builder - Pay to Public Key standard Transactions
    • P2SH Transaction Builder - Pay to Script Hash. This should be considered deprecated. BitcoinSV Nodes support this for backwards compatibility only.
    • P2PKHDataLockBuilder - This is something new. Create a spendable data output. Spendable using P2PKH Transaction.
    • UnspendableDataLockBuilder - OP_RETURN-style Data builder. Prepends a Transaction Output Script with OP_FALSE OP_RETURN followed by a series of data pushes.

Deprecated Features

The following features represent forks away from the original Bitcoin Protocol.

This library lacks, and does not implement :

  • Segregated Witness (Segwit) Transaction support (Bitcoin Core - BTC)
  • Schnorr Transaction Signature support (Bitcoin Cash - BCH)
  • Check Datasig (OP_CHECKDATASIG) (Bitcoin Cash - BCH)
  • Taproot (Bitcoin Core - BTC)

Acknowledgement

This library is a fork of the BitcoinJ and BitcoinJ-Cash projects. Contributor acknowledgements have been preserved in the AUTHORS file.

Contact

You can reach the author at : [email protected]

Comments
  • Minor fixes

    Minor fixes

    • Ensure and test that Transaction ID matches its hash. This appears to have been fixed in Transaction.getTransactionIdBytes() but not Transaction.getTransactionId()
    • Make some classes and constants public to be usable from the read-only library
    • Minor typo fixes in comments
    opened by nickabourisk 2
  • TransactionBuilder class have a bug, the method may be should chanag to  Utils.reverseBytes(txn.getTransactionIdBytes()

    TransactionBuilder class have a bug, the method may be should chanag to Utils.reverseBytes(txn.getTransactionIdBytes()

    public TransactionBuilder spendFromTransaction(Transaction txn, int outputIndex, long sequenceNumber, UnlockingScriptBuilder unlocker) { TransactionInput input = new TransactionInput(Utils.reverseBytes(txn.getTransactionIdBytes()), (long)outputIndex, sequenceNumber, unlocker); this.spendingMap.put(txn.getTransactionId(), ((TransactionOutput)txn.getOutputs().get(outputIndex)).getAmount()); this.inputs.add(input); return this; }

    opened by metanet4jDev 1
  • BugFix for Signature Generation

    BugFix for Signature Generation

    • Bug was caused where spending multiple inputs resulted in invalid signatures being created.
    • Added additional testing to verify that signatures don't break.
    opened by stephanfeb 0
  • TransactionBuilder Signature API Completion

    TransactionBuilder Signature API Completion

    Version 1.6.0 introduces the new API for passing a TransactionSigner to the TransactionBuilder.spendFromTransaction() method.

    This update completes the shape of that API by doing the same for :

    • TransactionBuilder.spendFromOutpoint()
    • TransactionBuilder.spendFromOutput()
    • TransactionBuilder.spendFromUtxoMap(
    opened by stephanfeb 0
  • TransactionBuilder Signature generation refactor

    TransactionBuilder Signature generation refactor

    - Transaction building suffered from a rather pernicious problem
      wherein it becomes hard/complicated to calculate fees.
      This stems from the fact that when you try to large number of
      utxos, the consequent large number of inputs in the spending tx
      leads to guesswork about the appropriate fee calculation.
    
      This update refactors the process of Transaction Signing so that
      the builder can directly generate the signed inputs and therefore
      perform the work of fee calculation internally.
    
      Please see the transaction/TransactionBuilderTest.java for an example use.
    
    opened by stephanfeb 0
  • Locking script & tx spending fixes

    Locking script & tx spending fixes

    • The spendFromTransaction() fundion in TransactionBuilder was using the incorrect endian encoding the for the transactionID. Fixed.
    • The P2PKHDataLockBuilder had a broken means for validating the script template. fixed.
    • Added hashcode and equals to TransactionOutpoint so it can used in collections
    opened by stephanfeb 0
  • Modular Arithmetic and Big Integers

    Modular Arithmetic and Big Integers

    • Java BigInteger does not support modular arithmetic on negative numbers so we use BigDecimal as temporary substitute
    • Expanded the Genesis Upgrade support to cover BigIntegers in general
    opened by stephanfeb 0
  • Genesis sync

    Genesis sync

    In February 2020 the BSV network underwent a hardfork known as the "Genesis Upgrade". https://wiki.bitcoinsv.io/index.php/Genesis_upgrade

    This release brings this library in line with the latest features from the Genesis upgrade.

    • Genesis OpCode support in Script Interpreter (a number of OpCodes were re-enabled)
    • New default limits on Script OpCodes
    • P2SH nuances w.r.t. simultaneous "soft-deprecation" of this feature.
    • Backward-compatibility with pre-fork transactions
    • Full compatibility with BitcoinSV Node 1.0.8 Test Vectors
    opened by stephanfeb 0
  • 1.4.1

    1.4.1

    Added tests and fixes for Locking / Unlock builders

    Changed toASM / fromASM API to be in line with that generated / used by 'bsv' and 'dartsv' libraries.

    Fixed a bug that prevented TransactionBuilder from creating any transactions that had no change output specified.

    Removed / Changed wrong or outdated code-comments.

    Make some classes and constants public to be accessible when using the read-only lib

    Bug fix for Transaction ID (bytes weren't reversed) and a new test to make sure the Transaction ID corresponds to its hash

    Added Spendable Data transaction Builder

    Added Script Builder Helpers for Standard Scripts

    Modified the interface to use "getLockingScript()" and "getUnlockScript()" instead of scriptSig and scriptPubkey. P2MSLock/UnlockBuilder - Pay to Multisig. This is naked MultiSig (the proper way to do multisig). P2PKLock/UnlockBuilder - Pay to Public Key P2SHLock/UnlockBuilder - Pay to Script Hash. This should be considered deprecated. Nodes support his for backwards compatibility only. P2PKHDataLockBuilder - This is something new. Create a spendable data output. UnspendableDataLockBuilder - OP_RETURN Data builder. Prepends a Transaction Output Script with OP_FALSE OP_RETURN followed by a series of data pushes.

    opened by stephanfeb 0
  • 1.4.1 Release Merge

    1.4.1 Release Merge

    • Added tests and fixes for Locking / Unlock builders

    • Changed toASM / fromASM API to be in line with that generated / used by 'bsv' and 'dartsv' libraries.

    • Fixed a bug that prevented TransactionBuilder from creating any transactions that had no change output specified.

    • Removed / Changed wrong or outdated code-comments.

    • Make some classes and constants public to be accessible when using the read-only lib

    • Bug fix for Transaction ID (bytes weren't reversed) and a new test to make sure the Transaction ID corresponds to its hash

    • Added Spendable Data transaction Builder

    • Added Script Builder Helpers for Standard Scripts

      • Modified the interface to use "getLockingScript()" and "getUnlockScript()" instead of scriptSig and scriptPubkey.
      • P2MSLock/UnlockBuilder - Pay to Multisig. This is naked MultiSig (the proper way to do multisig).
      • P2PKLock/UnlockBuilder - Pay to Public Key
      • P2SHLock/UnlockBuilder - Pay to Script Hash. This should be considered deprecated. Nodes support his for backwards compatibility only.
      • P2PKHDataLockBuilder - This is something new. Create a spendable data output.
      • UnspendableDataLockBuilder - OP_RETURN Data builder. Prepends a Transaction Output Script with OP_FALSE OP_RETURN followed by a series of data pushes.
    opened by stephanfeb 0
  • Transaction ID Bugfix

    Transaction ID Bugfix

    • This is a rather serious one. When serializing transactions the wrong endianness is generated, resulting in a revered TXID not recognised by the network. Transactions won't broadcast like this.
    opened by stephanfeb 0
  • the code execute error

    the code execute error

    Set<Script.VerifyFlag> verifyFlags =new HashSet<>();

            //Let's do a quick sanity check against the Script Interpreter
            //This is a useful example of how to test your own Locking/Unlocking Scripts
            try {
                Interpreter interp = new Interpreter();
                interp.correctlySpends(transactionToSign.getInputs().get(0).getScriptSig(), fundingOutput.getScript(), aliceTx, 0, verifyFlags);
            }catch(Exception ex){
                System.out.println(ex.getMessage());
            }
    

    the error message is :org.twostack.bitcoin4j.script.ScriptException: ForkID is not enabled, yet the flag is set at org.twostack.bitcoin4j.script.Interpreter.executeCheckSig(Interpreter.java:1221) at org.twostack.bitcoin4j.script.Interpreter.executeScript(Interpreter.java:952) at org.twostack.bitcoin4j.script.Interpreter.correctlySpends(Interpreter.java:1121) at org.twostack.bitcoin4j.script.Interpreter.correctlySpends(Interpreter.java:1080) at org.twostack.bitcoin4j.metaid.Main.main(Main.java:127)

    opened by metanet4jDev 0
Releases(1.6.4)
  • 1.6.4(Jan 27, 2022)

  • 1.6.3(Jan 27, 2022)

    • Bug was caused where spending multiple inputs resulted in invalid signatures being created.
    • Added additional testing to verify that signatures don't break.
    Source code(tar.gz)
    Source code(zip)
  • 1.6.2(Jan 21, 2022)

  • 1.6.1(Jan 21, 2022)

    TransactionBuilder Signature API Completion

    Version 1.6.0 introduces the new API for passing a TransactionSigner to the TransactionBuilder.spendFromTransaction() method.

    This update completes the shape of that API by doing the same for :

    • TransactionBuilder.spendFromOutpoint()
    • TransactionBuilder.spendFromOutput()
    • TransactionBuilder.spendFromUtxoMap()
    Source code(tar.gz)
    Source code(zip)
  • 1.6.0(Jan 21, 2022)

    TransactionBuilder Signature generation refactor

    Transaction building suffered from a rather pernicious problem
    wherein it becomes hard/complicated to calculate fees.
    This stems from the fact that when you try to large number of
    utxos, the consequent large number of inputs in the spending tx
    leads to guesswork about the appropriate fee calculation.

    This update refactors the process of Transaction Signing so that
    the builder can directly generate the signed inputs and therefore
    perform the work of fee calculation internally.

    Please see the transaction/TransactionBuilderTest.java for an example use.

    Source code(tar.gz)
    Source code(zip)
  • 1.5.5(Jan 5, 2022)

    Made constructors public so to allow outside-package subclassing

    Locking script & tx spending fixes:

    • The spendFromTransaction() fundion in TransactionBuilder was using the incorrect endian encoding the for the transactionID. Fixed.
    • The P2PKHDataLockBuilder had a broken means for validating the script template. fixed.
    • Added hashcode and equals to TransactionOutpoint so it can used in collections

    P2PKH Bugfix in template check

    Javadoc fixes:

    • Fixed javadocs for sha256 utility
    • Fixed javadocs for private key crypto
    • Fixed up ECKey constructor javadocs
    • Fixed javadocs for Monetary
    • Fixed javadocs for base58 encoder
    • Fixed javadocs for legacy addresses
    • Added javadoc entries for TransactionBuilder

    Allow zero-satoshi outputs for OP_RETURN data expose the Change Output of the Builder

    Refactored change API in TransactionBuilder

    • setting change in the TransactionBuilder is split into implicit P2PKH when address is provided and explicit locking script builder.

    Factored out pre-image signing

    Added local state to TransactionSigner:

    • Not the most elegant solution. Ideally the sign() method should return structured data with actual signature information. Instead, to not break the API for this method the internal state of the class now reflects additional data after signing.

    added documentation for getPrevoutsHash() because it's non-obvious from name

    Made public some previously protected byte array reader methods

    Added toAsmString() method

    Source code(tar.gz)
    Source code(zip)
  • 1.5.0(Aug 11, 2021)

    Release 1.5.0

    New Features

    In February 2020 the BSV network underwent a hardfork known as the "Genesis Upgrade". https://wiki.bitcoinsv.io/index.php/Genesis_upgrade

    This release brings this library in line with the latest features from the Genesis upgrade.

    • Genesis OpCode support in Script Interpreter (a number of OpCodes were re-enabled)
    • New default limits on Script OpCodes (number of opcodes in script, size of script etc.)
    • Expanded numeric support to cover BigIntegers in Script
    • P2SH nuances w.r.t. simultaneous "soft-deprecation" of this feature.
    • Backward-compatibility with pre-fork transactions (limits remaining in place)
    • Full compatibility with BitcoinSV Node 1.0.8 Test Vectors

    Notable Limits

    Below are some notable constants delimiting new limits available to Script developers. These limits are all governed by Flags that can be passed to the Script Interpreter.

    //maximum size of push operation after Genesis
    MAX_SCRIPT_ELEMENT_SIZE = 2147483647;  // 2Gigabytes after Genesis - (2^31 -1)
    
    //maximum size of push operation before Genesis
    MAX_SCRIPT_ELEMENT_SIZE_BEFORE_GENESIS = 520;
    
    // Maximum number of non-push operations per script before GENESIS
    MAX_OPS_PER_SCRIPT_BEFORE_GENESIS = 500;
    
    // Maximum number of non-push operations per script after GENESIS
    MAX_OPS_PER_SCRIPT_AFTER_GENESIS = UINT32_MAX // (4294967295L)
    
    // Maximum script number length after Genesis
    MAX_SCRIPT_NUM_LENGTH_AFTER_GENESIS = 750 * ONE_KILOBYTE;
    
    //maximum size of numbers in Script before Genesis
    MAX_SCRIPT_NUM_LENGTH_BEFORE_GENESIS = 4;
    
    
    Source code(tar.gz)
    Source code(zip)
  • 1.4.1(Jul 8, 2021)

    *** New Features New Locking / Unlocking Script Builders - P2MSLock/UnlockBuilder - Pay to Multisig. This is naked MultiSig (the proper way to do multisig). - P2PKLock/UnlockBuilder - Pay to Public Key - P2SHLock/UnlockBuilder - Pay to Script Hash. This should be considered deprecated. Nodes support his for backwards compatibility only. - P2PKHDataLockBuilder - This is something new. Create a spendable data output. - UnspendableDataLockBuilder - OP_RETURN Data builder. Prepends a Transaction Output Script with OP_FALSE OP_RETURN followed by a series of data pushes. - SpendableDataLockBuilder - OP_DROP-style locking script builder. Allows creation of P2PKH-spendable data outputs. - Added tests and fixes for Locking / Unlock builders

    *** API Changes - Changed toASM / fromASM API to be in line with that generated / used by 'bsv' and 'dartsv' libraries. - Made some classes and constants public to be accessible when using the read-only lib - Modified the interface to use "getLockingScript()" and "getUnlockScript()" instead of scriptSig and scriptPubkey.

    *** Bug Fixes - Fixed a bug that prevented TransactionBuilder from creating any transactions that had no change output specified. - Bug fix for Transaction ID (bytes weren't reversed) and a new test to make sure the Transaction ID corresponds to its hash - Removed / Changed wrong or outdated code-comments.

    Source code(tar.gz)
    Source code(zip)
  • 1.3.1(Jul 1, 2021)

    Bug Fixes

    • Ensure and test that Transaction ID matches its hash. This appears to have been fixed in Transaction.getTransactionIdBytes() but not Transaction.getTransactionId()
    • Make some classes and constants public to be usable from the read-only library
    • Minor typo fixes in comments
    Source code(tar.gz)
    Source code(zip)
  • 1.3.0(Jun 15, 2021)

    • Fixed a fee calculation bug which resulted in TransactionBuilder not taking the change output into account
    • Fixed an endianness bug with serialized Transaction IDs
    Source code(tar.gz)
    Source code(zip)
  • 1.1.0(Jun 14, 2021)

Modern Java - A Guide to Java 8

Modern Java - A Guide to Java 8 This article was originally posted on my blog. You should also read my Java 11 Tutorial (including new language and AP

Benjamin Winterberg 16.1k Dec 29, 2022
Design patterns implemented in Java

Design patterns implemented in Java Read in different language : CN, KR, FR, TR, AR Introduction Design patterns are the best formalized practices a p

Ilkka Seppälä 79k Jan 2, 2023
Java EE 7 Samples

Java EE 7 Samples This workspace consists of Java EE 7 Samples and unit tests. They are categorized in different directories, one for each Technology/

JavaEE Samples 2.5k Dec 20, 2022
Solutions for some common algorithm problems written in Java.

Algorithms This repository contains my solution for common algorithms. I've created this repository to learn about algorithms and improve solutions to

Pedro Vicente Gómez Sánchez 2.8k Dec 30, 2022
Algorithms and Data Structures implemented in Java

Java : Algorithms and Data Structure The algorithms and data structures are implemented in Java. This is a collection of algorithms and data structure

Justin Wetherell 4.2k Jan 5, 2023
MCQs and coding questions solutions of Object-Oriented Programming java of coding ninjas

cn-java-sols (⌐■_■) Link to This repository Other similar repository of my friend Link ?? enjoy having full marks ?? ?? now answers avaible up to Stri

Sanyam Mahajan 11 Dec 27, 2022
Rework of html-java-dsl to work with newer Javas

java-html-dsl Example DSL for writing html in Java. Rework of benjiman/java-html-dsl to work with newer versions of Java This String doc = html(

Benji Weber 19 Jan 25, 2022
A toolchain for Minecraft: Java Edition that builds a workspace to interact with the game using the official mappings provided to the public by Mojang Studios.

VanillaGradle is a toolchain for Minecraft: Java Edition that provides a workspace to interact with the game using official mappings provided by Mojan

SpongePowered 75 Nov 22, 2022
Amazing Ruby's "Enumerable" ported to Java

Overview How to use? .all .any .none .select .map .count .reject .find How to contribute? Contributors Overview enumerable4j is a Ruby's well known En

Yurii Dubinka 30 Oct 28, 2022
Java 16 Features

Java 16 Features. Features are separated by package name.

Rahman Usta 9 Jan 7, 2022
Java Kampında derslerde yazılan projeler

nLayeredDemo JavaCampDay5Lesson https://www.youtube.com/watch?v=yaBPeS65vwM&ab_channel=EnginDemiro%C4%9F linkteki derste yapılan proje. Nortwind JavaC

Zeyneb Eda YILMAZ 10 Dec 14, 2021
Engin DEMIROG yotube java kamp HW

JavaBootCamp https://www.kodlama.io/courses/enrolled/1332369 Engin DEMIROG yotube javaBootCamp HW ve projeler Java & React Bootcamp (https://kodlama.i

Melik KARACA 8 Nov 13, 2022
Software Developer Training Camp (JAVA + REACT) works under the guidance of Engin Demiroğ

https://kodlama.io/p/yazilim-gelistirici-yetistirme-kampi2 [EN] Java_React-BootCamp Software Developer Training Camp (JAVA + REACT) works under the gu

Saba ÜRGÜP 18 Dec 24, 2022
A Java game Solitaire, made with JavaFX

Java Solitaire A game made with JavaFX Installation requirements: At least Java 11 installed. setup: 2.1. Intellij -> Open the file in the IDE and exe

Walter Alleyz 15 May 6, 2021
Repository for Bryn and Ethan's Java with MicroServices Batch

210607-FeederProgram This repository houses examples and environment setup for the Revature feeder program beginning on 6/7/2021 Environment Setup Gui

Bryn Portella 17 May 22, 2022
http://kodlama.io "Java & React Bootcamp" up to date Lectures and Homeworks.

Java & React Bootcamp (https://kodlama.io/) Lectures Lecture 1 intro Lecture 2 oopIntro homework Lecture 3 oopIntro2 inheritance inheritance2 homework

Karcan Ozbal 237 Dec 29, 2022
Códigos do Bootcamp Java Básico DIO

Curso Java Básico Digital Innovation One https://digitalinnovation.one Tive a honra de fazer parceria com o pessoal da Digital Innovation One, com doi

Nicole Bidigaray 3 Jul 28, 2021
Slicer4J is an accurate, low-overhead dynamic slicer for Java programs.

Slicer4J This repository hosts Slicer4J, an accurate, low-overhead dynamic slicer for Java programs. Slicer4J automatically generates a backward dynam

The Reliable, Secure, and Sustainable Software Lab 25 Dec 19, 2022
Ejercicios de CodeSignal resueltos en Java

CodeSignal Ejercicios resueltos en Java de la plataforma CodeSignal. Crear el proyecto con Maven Abrimos un terminal y ejecutamos el siguiente comando

Desarrollo de Interfaces (DAD) 3 Sep 21, 2021