├── src ├── secp256k1 │ ├── obj │ │ └── .gitignore │ ├── autogen.sh │ ├── TODO │ ├── src │ │ ├── modules │ │ │ ├── ecdh │ │ │ │ ├── Makefile.am.include │ │ │ │ ├── main_impl.h │ │ │ │ └── tests_impl.h │ │ │ ├── recovery │ │ │ │ ├── Makefile.am.include │ │ │ │ └── main_impl.h │ │ │ └── schnorr │ │ │ │ ├── Makefile.am.include │ │ │ │ ├── schnorr.h │ │ │ │ └── main_impl.h │ │ ├── java │ │ │ ├── org_bitcoin_NativeSecp256k1.h │ │ │ ├── org_bitcoin_NativeSecp256k1.c │ │ │ └── org │ │ │ │ └── bitcoin │ │ │ │ └── NativeSecp256k1.java │ │ ├── ecmult_const.h │ │ ├── num_gmp.h │ │ ├── num_impl.h │ │ ├── scalar_8x32.h │ │ ├── scalar_4x64.h │ │ ├── basic-config.h │ │ ├── testrand.h │ │ ├── ecdsa.h │ │ ├── ecmult.h │ │ ├── eckey.h │ │ ├── bench_ecdh.c │ │ ├── bench_sign.c │ │ ├── hash.h │ │ ├── field_5x52.h │ │ ├── bench.h │ │ ├── field_10x26.h │ │ ├── testrand_impl.h │ │ ├── bench_recover.c │ │ ├── ecmult_gen.h │ │ ├── gen_context.c │ │ ├── bench_verify.c │ │ ├── bench_schnorr_verify.c │ │ ├── num.h │ │ ├── util.h │ │ ├── scalar.h │ │ └── field.h │ ├── libsecp256k1.pc.in │ ├── .gitignore │ ├── include │ │ ├── secp256k1_ecdh.h │ │ └── secp256k1_recovery.h │ ├── COPYING │ ├── .travis.yml │ ├── build-aux │ │ └── m4 │ │ │ ├── bitcoin_secp.m4 │ │ │ └── ax_prog_cc_for_build.m4 │ ├── README.md │ └── Makefile.am ├── buffer.h ├── buffer.c ├── cstr.h ├── ripemd160.h ├── random.h ├── utils.h ├── random.c ├── vector.h ├── cstr.c ├── sha2.h ├── serialize.h ├── ecc_key.c ├── portable_endian.h ├── ecc_libsecp256k1.c ├── vector.c ├── serialize.c ├── script.h ├── aes.h └── utils.c ├── autogen.sh ├── libbtc.pc ├── libbtc.pc.in ├── .gitignore ├── test ├── random_tests.c ├── buffer_tests.c ├── ecc_tests.c ├── eckey_tests.c ├── unittester.c ├── cstr_tests.c ├── utils_tests.c ├── serialize_tests.c ├── vector_tests.c └── utest.h ├── .travis.yml ├── m4 └── macros │ └── with.m4 ├── README.md ├── include └── btc │ ├── base58.h │ ├── btc.h │ ├── ecc_key.h │ ├── bip32.h │ ├── ecc.h │ └── tx.h ├── Makefile.am ├── configure.ac └── contrib └── github-merge.sh /src/secp256k1/obj/.gitignore: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /autogen.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | set -e 3 | autoreconf -if --warnings=all 4 | -------------------------------------------------------------------------------- /src/secp256k1/autogen.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | set -e 3 | autoreconf -if --warnings=all 4 | -------------------------------------------------------------------------------- /src/secp256k1/TODO: -------------------------------------------------------------------------------- 1 | * Unit tests for fieldelem/groupelem, including ones intended to 2 | trigger fieldelem's boundary cases. 3 | * Complete constant-time operations for signing/keygen 4 | -------------------------------------------------------------------------------- /libbtc.pc: -------------------------------------------------------------------------------- 1 | prefix=/usr/local 2 | exec_prefix=${prefix} 3 | libdir=${exec_prefix}/lib 4 | includedir=${prefix}/include 5 | 6 | Name: libbtc 7 | Description: C library for manipulating bitcoin data structures 8 | URL: https://github.com/jonasschnelli/libbtc 9 | Version: 0.1 10 | Cflags: -I${includedir} 11 | Libs: -L${libdir} -lbtc 12 | 13 | -------------------------------------------------------------------------------- /libbtc.pc.in: -------------------------------------------------------------------------------- 1 | prefix=@prefix@ 2 | exec_prefix=@exec_prefix@ 3 | libdir=@libdir@ 4 | includedir=@includedir@ 5 | 6 | Name: libbtc 7 | Description: C library for manipulating bitcoin data structures 8 | URL: https://github.com/jonasschnelli/libbtc 9 | Version: @PACKAGE_VERSION@ 10 | Cflags: -I${includedir} 11 | Libs: -L${libdir} -lbtc 12 | 13 | -------------------------------------------------------------------------------- /src/secp256k1/src/modules/ecdh/Makefile.am.include: -------------------------------------------------------------------------------- 1 | include_HEADERS += include/secp256k1_ecdh.h 2 | noinst_HEADERS += src/modules/ecdh/main_impl.h 3 | noinst_HEADERS += src/modules/ecdh/tests_impl.h 4 | if USE_BENCHMARK 5 | noinst_PROGRAMS += bench_ecdh 6 | bench_ecdh_SOURCES = src/bench_ecdh.c 7 | bench_ecdh_LDADD = libsecp256k1.la $(SECP_LIBS) 8 | endif 9 | -------------------------------------------------------------------------------- /src/secp256k1/src/modules/recovery/Makefile.am.include: -------------------------------------------------------------------------------- 1 | include_HEADERS += include/secp256k1_recovery.h 2 | noinst_HEADERS += src/modules/recovery/main_impl.h 3 | noinst_HEADERS += src/modules/recovery/tests_impl.h 4 | if USE_BENCHMARK 5 | noinst_PROGRAMS += bench_recover 6 | bench_recover_SOURCES = src/bench_recover.c 7 | bench_recover_LDADD = libsecp256k1.la $(SECP_LIBS) 8 | endif 9 | -------------------------------------------------------------------------------- /src/secp256k1/libsecp256k1.pc.in: -------------------------------------------------------------------------------- 1 | prefix=@prefix@ 2 | exec_prefix=@exec_prefix@ 3 | libdir=@libdir@ 4 | includedir=@includedir@ 5 | 6 | Name: libsecp256k1 7 | Description: Optimized C library for EC operations on curve secp256k1 8 | URL: https://github.com/bitcoin/secp256k1 9 | Version: @PACKAGE_VERSION@ 10 | Cflags: -I${includedir} 11 | Libs.private: @SECP_LIBS@ 12 | Libs: -L${libdir} -lsecp256k1 13 | 14 | -------------------------------------------------------------------------------- /src/secp256k1/src/modules/schnorr/Makefile.am.include: -------------------------------------------------------------------------------- 1 | include_HEADERS += include/secp256k1_schnorr.h 2 | noinst_HEADERS += src/modules/schnorr/main_impl.h 3 | noinst_HEADERS += src/modules/schnorr/schnorr.h 4 | noinst_HEADERS += src/modules/schnorr/schnorr_impl.h 5 | noinst_HEADERS += src/modules/schnorr/tests_impl.h 6 | if USE_BENCHMARK 7 | noinst_PROGRAMS += bench_schnorr_verify 8 | bench_schnorr_verify_SOURCES = src/bench_schnorr_verify.c 9 | bench_schnorr_verify_LDADD = libsecp256k1.la $(SECP_LIBS) 10 | endif 11 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | tests 2 | tests.* 3 | test-suite.log 4 | *.exe 5 | *.so 6 | *.a 7 | !.gitignore 8 | 9 | Makefile 10 | configure 11 | .libs/ 12 | Makefile.in 13 | aclocal.m4 14 | autom4te.cache/ 15 | config.log 16 | config.status 17 | *.tar.gz 18 | *.la 19 | libtool 20 | .deps/ 21 | .dirstamp 22 | build-aux/ 23 | *.lo 24 | *.o 25 | *~ 26 | src/libbtc-config.h 27 | src/libbtc-config.h.in 28 | m4/libtool.m4 29 | m4/ltoptions.m4 30 | m4/ltsugar.m4 31 | m4/ltversion.m4 32 | m4/lt~obsolete.m4 33 | src/stamp-h1 34 | libbtc256k1.pc 35 | *.DS_Store 36 | *.gcda 37 | *.gcov 38 | *.gcno 39 | -------------------------------------------------------------------------------- /src/secp256k1/src/java/org_bitcoin_NativeSecp256k1.h: -------------------------------------------------------------------------------- 1 | /* DO NOT EDIT THIS FILE - it is machine generated */ 2 | #include 3 | /* Header for class org_bitcoin_NativeSecp256k1 */ 4 | 5 | #ifndef _Included_org_bitcoin_NativeSecp256k1 6 | #define _Included_org_bitcoin_NativeSecp256k1 7 | #ifdef __cplusplus 8 | extern "C" { 9 | #endif 10 | /* 11 | * Class: org_bitcoin_NativeSecp256k1 12 | * Method: secp256k1_ecdsa_verify 13 | * Signature: (Ljava/nio/ByteBuffer;)I 14 | */ 15 | JNIEXPORT jint JNICALL Java_org_bitcoin_NativeSecp256k1_secp256k1_1ecdsa_1verify 16 | (JNIEnv *, jclass, jobject); 17 | 18 | #ifdef __cplusplus 19 | } 20 | #endif 21 | #endif 22 | -------------------------------------------------------------------------------- /src/secp256k1/src/ecmult_const.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2015 Andrew Poelstra * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_ECMULT_CONST_ 8 | #define _SECP256K1_ECMULT_CONST_ 9 | 10 | #include "scalar.h" 11 | #include "group.h" 12 | 13 | static void secp256k1_ecmult_const(secp256k1_gej *r, const secp256k1_ge *a, const secp256k1_scalar *q); 14 | 15 | #endif 16 | -------------------------------------------------------------------------------- /test/random_tests.c: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2015 Jonas Schnelli * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #include "random.h" 8 | 9 | #include 10 | #include 11 | #include 12 | #include 13 | 14 | void test_random() 15 | { 16 | unsigned char r_buf[32]; 17 | memset(r_buf, 0, 32); 18 | random_init(); 19 | random_bytes(r_buf, 32, 0); 20 | } 21 | -------------------------------------------------------------------------------- /src/secp256k1/.gitignore: -------------------------------------------------------------------------------- 1 | bench_inv 2 | bench_ecdh 3 | bench_sign 4 | bench_verify 5 | bench_schnorr_verify 6 | bench_recover 7 | bench_internal 8 | tests 9 | gen_context 10 | *.exe 11 | *.so 12 | *.a 13 | !.gitignore 14 | 15 | Makefile 16 | configure 17 | .libs/ 18 | Makefile.in 19 | aclocal.m4 20 | autom4te.cache/ 21 | config.log 22 | config.status 23 | *.tar.gz 24 | *.la 25 | libtool 26 | .deps/ 27 | .dirstamp 28 | build-aux/ 29 | *.lo 30 | *.o 31 | *~ 32 | src/libsecp256k1-config.h 33 | src/libsecp256k1-config.h.in 34 | src/ecmult_static_context.h 35 | m4/libtool.m4 36 | m4/ltoptions.m4 37 | m4/ltsugar.m4 38 | m4/ltversion.m4 39 | m4/lt~obsolete.m4 40 | src/stamp-h1 41 | libsecp256k1.pc 42 | -------------------------------------------------------------------------------- /src/secp256k1/src/num_gmp.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2013, 2014 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_NUM_REPR_ 8 | #define _SECP256K1_NUM_REPR_ 9 | 10 | #include 11 | 12 | #define NUM_LIMBS ((256+GMP_NUMB_BITS-1)/GMP_NUMB_BITS) 13 | 14 | typedef struct { 15 | mp_limb_t data[2*NUM_LIMBS]; 16 | int neg; 17 | int limbs; 18 | } secp256k1_num; 19 | 20 | #endif 21 | -------------------------------------------------------------------------------- /src/buffer.h: -------------------------------------------------------------------------------- 1 | #ifndef __LIBCCOIN_BUFFER_H__ 2 | #define __LIBCCOIN_BUFFER_H__ 3 | /* Copyright 2012 exMULTI, Inc. 4 | * Distributed under the MIT/X11 software license, see the accompanying 5 | * file COPYING or http://www.opensource.org/licenses/mit-license.php. 6 | */ 7 | 8 | #include 9 | #include 10 | #include 11 | 12 | struct buffer { 13 | void *p; 14 | size_t len; 15 | }; 16 | 17 | struct const_buffer { 18 | const void *p; 19 | size_t len; 20 | }; 21 | 22 | extern bool buffer_equal(const void *a, const void *b); 23 | extern void buffer_free(void *struct_buffer); 24 | extern struct buffer *buffer_copy(const void *data, size_t data_len); 25 | 26 | #endif /* __LIBCCOIN_BUFFER_H__ */ 27 | -------------------------------------------------------------------------------- /src/secp256k1/src/num_impl.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2013, 2014 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_NUM_IMPL_H_ 8 | #define _SECP256K1_NUM_IMPL_H_ 9 | 10 | #if defined HAVE_CONFIG_H 11 | #include "libsecp256k1-config.h" 12 | #endif 13 | 14 | #include "num.h" 15 | 16 | #if defined(USE_NUM_GMP) 17 | #include "num_gmp_impl.h" 18 | #elif defined(USE_NUM_NONE) 19 | /* Nothing. */ 20 | #else 21 | #error "Please select num implementation" 22 | #endif 23 | 24 | #endif 25 | -------------------------------------------------------------------------------- /src/secp256k1/src/scalar_8x32.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2014 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_SCALAR_REPR_ 8 | #define _SECP256K1_SCALAR_REPR_ 9 | 10 | #include 11 | 12 | /** A scalar modulo the group order of the secp256k1 curve. */ 13 | typedef struct { 14 | uint32_t d[8]; 15 | } secp256k1_scalar; 16 | 17 | #define SECP256K1_SCALAR_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {{(d0), (d1), (d2), (d3), (d4), (d5), (d6), (d7)}} 18 | 19 | #endif 20 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: c 2 | os: 3 | - osx 4 | - linux 5 | 6 | compiler: 7 | - clang 8 | - gcc 9 | 10 | addons: 11 | apt: 12 | packages: 13 | - valgrind 14 | 15 | before_install: 16 | - pip install --user cpp-coveralls 17 | - if [ "${TRAVIS_OS_NAME}" = "osx" ]; then brew install valgrind; fi 18 | 19 | matrix: 20 | fast_finish: 21 | - true 22 | 23 | script: 24 | - ./autogen.sh 25 | - ./configure CFLAGS='-fprofile-arcs -ftest-coverage' 26 | - make 27 | - if [ ${CC} = gcc ] || [ "${TRAVIS_OS_NAME}" = "osx" ]; then valgrind --leak-check=full --error-exitcode=1 ./tests; fi; 28 | - make check 29 | 30 | after_success: 31 | - coveralls --verbose -i src -x c -e src/secp256k1 -r $TRAVIS_BUILD_DIR -b $TRAVIS_BUILD_DIR --gcov-options '\-lp' -------------------------------------------------------------------------------- /m4/macros/with.m4: -------------------------------------------------------------------------------- 1 | 2 | # ARG_WITH_SUBST(option, default, help) 3 | # ----------------------------------- 4 | # Create a --with-$1 option with helptext, AC_SUBST($1) to $withval/default 5 | AC_DEFUN([ARG_WITH_SUBST], 6 | [AC_ARG_WITH( 7 | [$1], 8 | AS_HELP_STRING([--with-$1=arg], [$3 (default: $2).]), 9 | [AC_SUBST(patsubst([$1], [-], [_]), ["$withval"])], 10 | [AC_SUBST(patsubst([$1], [-], [_]), ["$2"])] 11 | )] 12 | ) 13 | 14 | # ARG_WITH_SET(option, default, help) 15 | # ----------------------------------- 16 | # Create a --with-$1 option with helptext, set a variable $1 to $withval/default 17 | AC_DEFUN([ARG_WITH_SET], 18 | [AC_ARG_WITH( 19 | [$1], 20 | AS_HELP_STRING([--with-$1=arg], [$3 (default: $2).]), 21 | patsubst([$1], [-], [_])="$withval", 22 | patsubst([$1], [-], [_])=$2 23 | )] 24 | ) 25 | -------------------------------------------------------------------------------- /test/buffer_tests.c: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2015 Jonas Schnelli * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | #include "buffer.h" 13 | 14 | void test_buffer() 15 | { 16 | struct const_buffer buf0 = { "data", 4 }; 17 | struct const_buffer buf1 = { "data", 4 }; 18 | 19 | assert(buffer_equal(&buf0.p, &buf1.p) == true); 20 | 21 | struct buffer *buf2 = buffer_copy(&buf0.p, buf0.len); 22 | buffer_free(buf2); 23 | } 24 | -------------------------------------------------------------------------------- /src/secp256k1/src/scalar_4x64.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2014 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_SCALAR_REPR_ 8 | #define _SECP256K1_SCALAR_REPR_ 9 | 10 | #include 11 | 12 | /** A scalar modulo the group order of the secp256k1 curve. */ 13 | typedef struct { 14 | uint64_t d[4]; 15 | } secp256k1_scalar; 16 | 17 | #define SECP256K1_SCALAR_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {{((uint64_t)(d1)) << 32 | (d0), ((uint64_t)(d3)) << 32 | (d2), ((uint64_t)(d5)) << 32 | (d4), ((uint64_t)(d7)) << 32 | (d6)}} 18 | 19 | #endif 20 | -------------------------------------------------------------------------------- /src/secp256k1/src/java/org_bitcoin_NativeSecp256k1.c: -------------------------------------------------------------------------------- 1 | #include "org_bitcoin_NativeSecp256k1.h" 2 | #include "include/secp256k1.h" 3 | 4 | JNIEXPORT jint JNICALL Java_org_bitcoin_NativeSecp256k1_secp256k1_1ecdsa_1verify 5 | (JNIEnv* env, jclass classObject, jobject byteBufferObject) 6 | { 7 | unsigned char* data = (unsigned char*) (*env)->GetDirectBufferAddress(env, byteBufferObject); 8 | int sigLen = *((int*)(data + 32)); 9 | int pubLen = *((int*)(data + 32 + 4)); 10 | 11 | return secp256k1_ecdsa_verify(data, 32, data+32+8, sigLen, data+32+8+sigLen, pubLen); 12 | } 13 | 14 | static void __javasecp256k1_attach(void) __attribute__((constructor)); 15 | static void __javasecp256k1_detach(void) __attribute__((destructor)); 16 | 17 | static void __javasecp256k1_attach(void) { 18 | secp256k1_start(SECP256K1_START_VERIFY); 19 | } 20 | 21 | static void __javasecp256k1_detach(void) { 22 | secp256k1_stop(); 23 | } 24 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | libbtc – A Simple and Effective C Library for Bitcoin Wallets 2 | ============================================================= 3 | 4 | [![Build Status](https://travis-ci.org/libbtc/libbtc.svg?branch=master)](https://travis-ci.org/libbtc/libbtc) [![Coverage Status](https://coveralls.io/repos/libbtc/libbtc/badge.svg?branch=master&service=github)](https://coveralls.io/github/libbtc/libbtc?branch=master) 5 | 6 | 7 | What is libbtc? 8 | ---------------- 9 | 10 | Libbtc is a simple and portable C library for creating and manipulating bitcoin data structures like creating keys and addresses (HD/bip32) or parsing, creating and signing transactions. 11 | 12 | What is the Focus of Libbtc? 13 | ---------------- 14 | 15 | * minimum dependencies (only dependency libsecp256k1) 16 | * optimized for low mem environments like embedded/MCU 17 | * full test coverage 18 | * mem leak free (valgrind check during CI) 19 | 20 | How to Build 21 | ---------------- 22 | ``` 23 | ./autogen.sh 24 | ./configure 25 | make check 26 | ``` 27 | -------------------------------------------------------------------------------- /src/secp256k1/include/secp256k1_ecdh.h: -------------------------------------------------------------------------------- 1 | #ifndef _SECP256K1_ECDH_ 2 | # define _SECP256K1_ECDH_ 3 | 4 | # include "secp256k1.h" 5 | 6 | # ifdef __cplusplus 7 | extern "C" { 8 | # endif 9 | 10 | /** Compute an EC Diffie-Hellman secret in constant time 11 | * Returns: 1: exponentiation was successful 12 | * 0: scalar was invalid (zero or overflow) 13 | * Args: ctx: pointer to a context object (cannot be NULL) 14 | * Out: result: a 32-byte array which will be populated by an ECDH 15 | * secret computed from the point and scalar 16 | * In: point: pointer to a public point 17 | * scalar: a 32-byte scalar with which to multiply the point 18 | */ 19 | SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ecdh( 20 | const secp256k1_context* ctx, 21 | unsigned char *result, 22 | const secp256k1_pubkey *point, 23 | const unsigned char *scalar 24 | ) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4); 25 | 26 | # ifdef __cplusplus 27 | } 28 | # endif 29 | 30 | #endif 31 | -------------------------------------------------------------------------------- /src/secp256k1/src/basic-config.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2013, 2014 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_BASIC_CONFIG_ 8 | #define _SECP256K1_BASIC_CONFIG_ 9 | 10 | #ifdef USE_BASIC_CONFIG 11 | 12 | #undef USE_ASM_X86_64 13 | #undef USE_ENDOMORPHISM 14 | #undef USE_FIELD_10X26 15 | #undef USE_FIELD_5X52 16 | #undef USE_FIELD_INV_BUILTIN 17 | #undef USE_FIELD_INV_NUM 18 | #undef USE_NUM_GMP 19 | #undef USE_NUM_NONE 20 | #undef USE_SCALAR_4X64 21 | #undef USE_SCALAR_8X32 22 | #undef USE_SCALAR_INV_BUILTIN 23 | #undef USE_SCALAR_INV_NUM 24 | 25 | #define USE_NUM_NONE 1 26 | #define USE_FIELD_INV_BUILTIN 1 27 | #define USE_SCALAR_INV_BUILTIN 1 28 | #define USE_FIELD_10X26 1 29 | #define USE_SCALAR_8X32 1 30 | 31 | #endif // USE_BASIC_CONFIG 32 | #endif // _SECP256K1_BASIC_CONFIG_ 33 | -------------------------------------------------------------------------------- /src/buffer.c: -------------------------------------------------------------------------------- 1 | /* Copyright 2012 exMULTI, Inc. 2 | * Distributed under the MIT/X11 software license, see the accompanying 3 | * file COPYING or http://www.opensource.org/licenses/mit-license.php. 4 | */ 5 | 6 | #include "buffer.h" 7 | 8 | #include 9 | #include 10 | 11 | bool buffer_equal(const void *a_, const void *b_) 12 | { 13 | const struct buffer *a = a_; 14 | const struct buffer *b = b_; 15 | 16 | if (a->len != b->len) 17 | return false; 18 | return memcmp(a->p, b->p, a->len) == 0; 19 | } 20 | 21 | void buffer_free(void *struct_buffer) 22 | { 23 | struct buffer *buf = struct_buffer; 24 | if (!buf) 25 | return; 26 | 27 | free(buf->p); 28 | free(buf); 29 | } 30 | 31 | struct buffer *buffer_copy(const void *data, size_t data_len) 32 | { 33 | struct buffer *buf; 34 | buf = malloc(sizeof(*buf)); 35 | if (!buf) 36 | goto err_out; 37 | 38 | buf->p = malloc(data_len); 39 | if (!buf->p) 40 | goto err_out_free; 41 | 42 | memcpy(buf->p, data, data_len); 43 | buf->len = data_len; 44 | 45 | return buf; 46 | 47 | err_out_free: 48 | free(buf); 49 | err_out: 50 | return NULL; 51 | } 52 | 53 | -------------------------------------------------------------------------------- /src/secp256k1/COPYING: -------------------------------------------------------------------------------- 1 | Copyright (c) 2013 Pieter Wuille 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in 11 | all copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | THE SOFTWARE. 20 | -------------------------------------------------------------------------------- /src/secp256k1/src/testrand.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2013, 2014 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_TESTRAND_H_ 8 | #define _SECP256K1_TESTRAND_H_ 9 | 10 | #if defined HAVE_CONFIG_H 11 | #include "libsecp256k1-config.h" 12 | #endif 13 | 14 | /* A non-cryptographic RNG used only for test infrastructure. */ 15 | 16 | /** Seed the pseudorandom number generator for testing. */ 17 | SECP256K1_INLINE static void secp256k1_rand_seed(const unsigned char *seed16); 18 | 19 | /** Generate a pseudorandom 32-bit number. */ 20 | static uint32_t secp256k1_rand32(void); 21 | 22 | /** Generate a pseudorandom 32-byte array. */ 23 | static void secp256k1_rand256(unsigned char *b32); 24 | 25 | /** Generate a pseudorandom 32-byte array with long sequences of zero and one bits. */ 26 | static void secp256k1_rand256_test(unsigned char *b32); 27 | 28 | #endif 29 | -------------------------------------------------------------------------------- /src/cstr.h: -------------------------------------------------------------------------------- 1 | #ifndef LIBBTC_CSTR_H__ 2 | #define LIBBTC_CSTR_H__ 3 | /* Copyright 2015 BitPay, Inc. 4 | * Distributed under the MIT/X11 software license, see the accompanying 5 | * file COPYING or http://www.opensource.org/licenses/mit-license.php. 6 | */ 7 | 8 | #include 9 | #include 10 | #include 11 | 12 | typedef struct cstring { 13 | char *str; /* string data, incl. NUL */ 14 | size_t len; /* length of string, not including NUL */ 15 | size_t alloc; /* total allocated buffer length */ 16 | } cstring; 17 | 18 | extern cstring *cstr_new(const char *init_str); 19 | extern cstring *cstr_new_sz(size_t sz); 20 | extern cstring *cstr_new_buf(const void *buf, size_t sz); 21 | extern void cstr_free(cstring *s, bool free_buf); 22 | 23 | extern bool cstr_equal(const cstring *a, const cstring *b); 24 | extern bool cstr_resize(cstring *s, size_t sz); 25 | extern bool cstr_erase(cstring *s, size_t pos, ssize_t len); 26 | 27 | extern bool cstr_append_buf(cstring *s, const void *buf, size_t sz); 28 | 29 | static inline bool cstr_append_c(cstring *s, char ch) 30 | { 31 | return cstr_append_buf(s, &ch, 1); 32 | } 33 | 34 | #endif /* __LIBCCOIN_CSTR_H__ */ 35 | -------------------------------------------------------------------------------- /src/ripemd160.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2013-2014 Tomas Dzetkulic 3 | * Copyright (c) 2013-2014 Pavol Rusnak 4 | * 5 | * Permission is hereby granted, free of charge, to any person obtaining 6 | * a copy of this software and associated documentation files (the "Software"), 7 | * to deal in the Software without restriction, including without limitation 8 | * the rights to use, copy, modify, merge, publish, distribute, sublicense, 9 | * and/or sell copies of the Software, and to permit persons to whom the 10 | * Software is furnished to do so, subject to the following conditions: 11 | * 12 | * The above copyright notice and this permission notice shall be included 13 | * in all copies or substantial portions of the Software. 14 | * 15 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 16 | * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 18 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES 19 | * OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 20 | * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 21 | * OTHER DEALINGS IN THE SOFTWARE. 22 | */ 23 | 24 | 25 | #ifndef __RIPEMD160_H__ 26 | #define __RIPEMD160_H__ 27 | 28 | #include 29 | 30 | void ripemd160(const uint8_t *msg, uint32_t msg_len, uint8_t *hash); 31 | 32 | #endif 33 | -------------------------------------------------------------------------------- /src/random.h: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | The MIT License (MIT) 4 | 5 | Copyright (c) 2015 Douglas J. Bakkum 6 | 7 | Permission is hereby granted, free of charge, to any person obtaining 8 | a copy of this software and associated documentation files (the "Software"), 9 | to deal in the Software without restriction, including without limitation 10 | the rights to use, copy, modify, merge, publish, distribute, sublicense, 11 | and/or sell copies of the Software, and to permit persons to whom the 12 | Software is furnished to do so, subject to the following conditions: 13 | 14 | The above copyright notice and this permission notice shall be included 15 | in all copies or substantial portions of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 18 | OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 19 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 20 | THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES 21 | OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 22 | ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 23 | OTHER DEALINGS IN THE SOFTWARE. 24 | 25 | */ 26 | 27 | 28 | #ifndef _RANDOM_H_ 29 | #define _RANDOM_H_ 30 | 31 | #include 32 | #include 33 | 34 | void random_init(void); 35 | int random_bytes(uint8_t *buf, uint32_t len, const uint8_t update_seed); 36 | 37 | #endif 38 | -------------------------------------------------------------------------------- /src/secp256k1/src/modules/schnorr/schnorr.h: -------------------------------------------------------------------------------- 1 | /*********************************************************************** 2 | * Copyright (c) 2014-2015 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php. * 5 | ***********************************************************************/ 6 | 7 | #ifndef _SECP256K1_MODULE_SCHNORR_H_ 8 | #define _SECP256K1_MODULE_SCHNORR_H_ 9 | 10 | #include "scalar.h" 11 | #include "group.h" 12 | 13 | typedef void (*secp256k1_schnorr_msghash)(unsigned char *h32, const unsigned char *r32, const unsigned char *msg32); 14 | 15 | static int secp256k1_schnorr_sig_sign(const secp256k1_ecmult_gen_context* ctx, unsigned char *sig64, const secp256k1_scalar *key, const secp256k1_scalar *nonce, const secp256k1_ge *pubnonce, secp256k1_schnorr_msghash hash, const unsigned char *msg32); 16 | static int secp256k1_schnorr_sig_verify(const secp256k1_ecmult_context* ctx, const unsigned char *sig64, const secp256k1_ge *pubkey, secp256k1_schnorr_msghash hash, const unsigned char *msg32); 17 | static int secp256k1_schnorr_sig_recover(const secp256k1_ecmult_context* ctx, const unsigned char *sig64, secp256k1_ge *pubkey, secp256k1_schnorr_msghash hash, const unsigned char *msg32); 18 | static int secp256k1_schnorr_sig_combine(unsigned char *sig64, int n, const unsigned char * const *sig64ins); 19 | 20 | #endif 21 | -------------------------------------------------------------------------------- /src/secp256k1/src/ecdsa.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2013, 2014 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_ECDSA_ 8 | #define _SECP256K1_ECDSA_ 9 | 10 | #include 11 | 12 | #include "scalar.h" 13 | #include "group.h" 14 | #include "ecmult.h" 15 | 16 | static int secp256k1_ecdsa_sig_parse(secp256k1_scalar *r, secp256k1_scalar *s, const unsigned char *sig, size_t size); 17 | static int secp256k1_ecdsa_sig_serialize(unsigned char *sig, size_t *size, const secp256k1_scalar *r, const secp256k1_scalar *s); 18 | static int secp256k1_ecdsa_sig_verify(const secp256k1_ecmult_context *ctx, const secp256k1_scalar* r, const secp256k1_scalar* s, const secp256k1_ge *pubkey, const secp256k1_scalar *message); 19 | static int secp256k1_ecdsa_sig_sign(const secp256k1_ecmult_gen_context *ctx, secp256k1_scalar* r, secp256k1_scalar* s, const secp256k1_scalar *seckey, const secp256k1_scalar *message, const secp256k1_scalar *nonce, int *recid); 20 | static int secp256k1_ecdsa_sig_recover(const secp256k1_ecmult_context *ctx, const secp256k1_scalar* r, const secp256k1_scalar* s, secp256k1_ge *pubkey, const secp256k1_scalar *message, int recid); 21 | 22 | #endif 23 | -------------------------------------------------------------------------------- /include/btc/base58.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2013-2014 Tomas Dzetkulic 3 | * Copyright (c) 2013-2014 Pavol Rusnak 4 | * 5 | * Permission is hereby granted, free of charge, to any person obtaining 6 | * a copy of this software and associated documentation files (the "Software"), 7 | * to deal in the Software without restriction, including without limitation 8 | * the rights to use, copy, modify, merge, publish, distribute, sublicense, 9 | * and/or sell copies of the Software, and to permit persons to whom the 10 | * Software is furnished to do so, subject to the following conditions: 11 | * 12 | * The above copyright notice and this permission notice shall be included 13 | * in all copies or substantial portions of the Software. 14 | * 15 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 16 | * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 18 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES 19 | * OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 20 | * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 21 | * OTHER DEALINGS IN THE SOFTWARE. 22 | */ 23 | 24 | #ifndef __LIBBTC_BASE58_H__ 25 | #define __LIBBTC_BASE58_H__ 26 | 27 | #include "btc.h" 28 | 29 | #include 30 | 31 | LIBBTC_API int base58_encode_check(const uint8_t *data, int len, char *str, int strsize); 32 | LIBBTC_API int base58_decode_check(const char *str, uint8_t *data, int datalen); 33 | 34 | #endif //__LIBBTC_BASE58_H__ 35 | -------------------------------------------------------------------------------- /src/secp256k1/src/ecmult.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2013, 2014 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_ECMULT_ 8 | #define _SECP256K1_ECMULT_ 9 | 10 | #include "num.h" 11 | #include "group.h" 12 | 13 | typedef struct { 14 | /* For accelerating the computation of a*P + b*G: */ 15 | secp256k1_ge_storage (*pre_g)[]; /* odd multiples of the generator */ 16 | #ifdef USE_ENDOMORPHISM 17 | secp256k1_ge_storage (*pre_g_128)[]; /* odd multiples of 2^128*generator */ 18 | #endif 19 | } secp256k1_ecmult_context; 20 | 21 | static void secp256k1_ecmult_context_init(secp256k1_ecmult_context *ctx); 22 | static void secp256k1_ecmult_context_build(secp256k1_ecmult_context *ctx, const secp256k1_callback *cb); 23 | static void secp256k1_ecmult_context_clone(secp256k1_ecmult_context *dst, 24 | const secp256k1_ecmult_context *src, const secp256k1_callback *cb); 25 | static void secp256k1_ecmult_context_clear(secp256k1_ecmult_context *ctx); 26 | static int secp256k1_ecmult_context_is_built(const secp256k1_ecmult_context *ctx); 27 | 28 | /** Double multiply: R = na*A + ng*G */ 29 | static void secp256k1_ecmult(const secp256k1_ecmult_context *ctx, secp256k1_gej *r, const secp256k1_gej *a, const secp256k1_scalar *na, const secp256k1_scalar *ng); 30 | 31 | #endif 32 | -------------------------------------------------------------------------------- /src/secp256k1/src/eckey.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2013, 2014 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_ECKEY_ 8 | #define _SECP256K1_ECKEY_ 9 | 10 | #include 11 | 12 | #include "group.h" 13 | #include "scalar.h" 14 | #include "ecmult.h" 15 | #include "ecmult_gen.h" 16 | 17 | static int secp256k1_eckey_pubkey_parse(secp256k1_ge *elem, const unsigned char *pub, size_t size); 18 | static int secp256k1_eckey_pubkey_serialize(secp256k1_ge *elem, unsigned char *pub, size_t *size, unsigned int flags); 19 | 20 | static int secp256k1_eckey_privkey_parse(secp256k1_scalar *key, const unsigned char *privkey, size_t privkeylen); 21 | static int secp256k1_eckey_privkey_serialize(const secp256k1_ecmult_gen_context *ctx, unsigned char *privkey, size_t *privkeylen, const secp256k1_scalar *key, unsigned int flags); 22 | 23 | static int secp256k1_eckey_privkey_tweak_add(secp256k1_scalar *key, const secp256k1_scalar *tweak); 24 | static int secp256k1_eckey_pubkey_tweak_add(const secp256k1_ecmult_context *ctx, secp256k1_ge *key, const secp256k1_scalar *tweak); 25 | static int secp256k1_eckey_privkey_tweak_mul(secp256k1_scalar *key, const secp256k1_scalar *tweak); 26 | static int secp256k1_eckey_pubkey_tweak_mul(const secp256k1_ecmult_context *ctx, secp256k1_ge *key, const secp256k1_scalar *tweak); 27 | 28 | #endif 29 | -------------------------------------------------------------------------------- /src/secp256k1/src/bench_ecdh.c: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2015 Pieter Wuille, Andrew Poelstra * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #include 8 | 9 | #include "include/secp256k1.h" 10 | #include "include/secp256k1_ecdh.h" 11 | #include "util.h" 12 | #include "bench.h" 13 | 14 | typedef struct { 15 | secp256k1_context *ctx; 16 | secp256k1_pubkey point; 17 | unsigned char scalar[32]; 18 | } bench_ecdh_t; 19 | 20 | static void bench_ecdh_setup(void* arg) { 21 | int i; 22 | bench_ecdh_t *data = (bench_ecdh_t*)arg; 23 | const unsigned char point[] = { 24 | 0x03, 25 | 0x54, 0x94, 0xc1, 0x5d, 0x32, 0x09, 0x97, 0x06, 26 | 0xc2, 0x39, 0x5f, 0x94, 0x34, 0x87, 0x45, 0xfd, 27 | 0x75, 0x7c, 0xe3, 0x0e, 0x4e, 0x8c, 0x90, 0xfb, 28 | 0xa2, 0xba, 0xd1, 0x84, 0xf8, 0x83, 0xc6, 0x9f 29 | }; 30 | 31 | data->ctx = secp256k1_context_create(0); 32 | for (i = 0; i < 32; i++) { 33 | data->scalar[i] = i + 1; 34 | } 35 | CHECK(secp256k1_ec_pubkey_parse(data->ctx, &data->point, point, sizeof(point)) == 1); 36 | } 37 | 38 | static void bench_ecdh(void* arg) { 39 | int i; 40 | unsigned char res[32]; 41 | bench_ecdh_t *data = (bench_ecdh_t*)arg; 42 | 43 | for (i = 0; i < 20000; i++) { 44 | CHECK(secp256k1_ecdh(data->ctx, res, &data->point, data->scalar) == 1); 45 | } 46 | } 47 | 48 | int main(void) { 49 | bench_ecdh_t data; 50 | 51 | run_benchmark("ecdh", bench_ecdh, bench_ecdh_setup, NULL, &data, 10, 20000); 52 | return 0; 53 | } 54 | -------------------------------------------------------------------------------- /src/secp256k1/src/bench_sign.c: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2014 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #include "include/secp256k1.h" 8 | #include "util.h" 9 | #include "bench.h" 10 | 11 | typedef struct { 12 | secp256k1_context* ctx; 13 | unsigned char msg[32]; 14 | unsigned char key[32]; 15 | } bench_sign_t; 16 | 17 | static void bench_sign_setup(void* arg) { 18 | int i; 19 | bench_sign_t *data = (bench_sign_t*)arg; 20 | 21 | for (i = 0; i < 32; i++) { 22 | data->msg[i] = i + 1; 23 | } 24 | for (i = 0; i < 32; i++) { 25 | data->key[i] = i + 65; 26 | } 27 | } 28 | 29 | static void bench_sign(void* arg) { 30 | int i; 31 | bench_sign_t *data = (bench_sign_t*)arg; 32 | 33 | unsigned char sig[74]; 34 | for (i = 0; i < 20000; i++) { 35 | size_t siglen = 74; 36 | int j; 37 | secp256k1_ecdsa_signature signature; 38 | CHECK(secp256k1_ecdsa_sign(data->ctx, &signature, data->msg, data->key, NULL, NULL)); 39 | CHECK(secp256k1_ecdsa_signature_serialize_der(data->ctx, sig, &siglen, &signature)); 40 | for (j = 0; j < 32; j++) { 41 | data->msg[j] = sig[j]; 42 | data->key[j] = sig[j + 32]; 43 | } 44 | } 45 | } 46 | 47 | int main(void) { 48 | bench_sign_t data; 49 | 50 | data.ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN); 51 | 52 | run_benchmark("ecdsa_sign", bench_sign, bench_sign_setup, NULL, &data, 10, 20000); 53 | 54 | secp256k1_context_destroy(data.ctx); 55 | return 0; 56 | } 57 | -------------------------------------------------------------------------------- /src/secp256k1/src/hash.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2014 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_HASH_ 8 | #define _SECP256K1_HASH_ 9 | 10 | #include 11 | #include 12 | 13 | typedef struct { 14 | uint32_t s[32]; 15 | uint32_t buf[16]; /* In big endian */ 16 | size_t bytes; 17 | } secp256k1_sha256_t; 18 | 19 | static void secp256k1_sha256_initialize(secp256k1_sha256_t *hash); 20 | static void secp256k1_sha256_write(secp256k1_sha256_t *hash, const unsigned char *data, size_t size); 21 | static void secp256k1_sha256_finalize(secp256k1_sha256_t *hash, unsigned char *out32); 22 | 23 | typedef struct { 24 | secp256k1_sha256_t inner, outer; 25 | } secp256k1_hmac_sha256_t; 26 | 27 | static void secp256k1_hmac_sha256_initialize(secp256k1_hmac_sha256_t *hash, const unsigned char *key, size_t size); 28 | static void secp256k1_hmac_sha256_write(secp256k1_hmac_sha256_t *hash, const unsigned char *data, size_t size); 29 | static void secp256k1_hmac_sha256_finalize(secp256k1_hmac_sha256_t *hash, unsigned char *out32); 30 | 31 | typedef struct { 32 | unsigned char v[32]; 33 | unsigned char k[32]; 34 | int retry; 35 | } secp256k1_rfc6979_hmac_sha256_t; 36 | 37 | static void secp256k1_rfc6979_hmac_sha256_initialize(secp256k1_rfc6979_hmac_sha256_t *rng, const unsigned char *key, size_t keylen); 38 | static void secp256k1_rfc6979_hmac_sha256_generate(secp256k1_rfc6979_hmac_sha256_t *rng, unsigned char *out, size_t outlen); 39 | static void secp256k1_rfc6979_hmac_sha256_finalize(secp256k1_rfc6979_hmac_sha256_t *rng); 40 | 41 | #endif 42 | -------------------------------------------------------------------------------- /src/secp256k1/src/field_5x52.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2013, 2014 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_FIELD_REPR_ 8 | #define _SECP256K1_FIELD_REPR_ 9 | 10 | #include 11 | 12 | typedef struct { 13 | /* X = sum(i=0..4, elem[i]*2^52) mod n */ 14 | uint64_t n[5]; 15 | #ifdef VERIFY 16 | int magnitude; 17 | int normalized; 18 | #endif 19 | } secp256k1_fe; 20 | 21 | /* Unpacks a constant into a overlapping multi-limbed FE element. */ 22 | #define SECP256K1_FE_CONST_INNER(d7, d6, d5, d4, d3, d2, d1, d0) { \ 23 | (d0) | (((uint64_t)(d1) & 0xFFFFFUL) << 32), \ 24 | ((uint64_t)(d1) >> 20) | (((uint64_t)(d2)) << 12) | (((uint64_t)(d3) & 0xFFUL) << 44), \ 25 | ((uint64_t)(d3) >> 8) | (((uint64_t)(d4) & 0xFFFFFFFUL) << 24), \ 26 | ((uint64_t)(d4) >> 28) | (((uint64_t)(d5)) << 4) | (((uint64_t)(d6) & 0xFFFFUL) << 36), \ 27 | ((uint64_t)(d6) >> 16) | (((uint64_t)(d7)) << 16) \ 28 | } 29 | 30 | #ifdef VERIFY 31 | #define SECP256K1_FE_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {SECP256K1_FE_CONST_INNER((d7), (d6), (d5), (d4), (d3), (d2), (d1), (d0)), 1, 1} 32 | #else 33 | #define SECP256K1_FE_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {SECP256K1_FE_CONST_INNER((d7), (d6), (d5), (d4), (d3), (d2), (d1), (d0))} 34 | #endif 35 | 36 | typedef struct { 37 | uint64_t n[4]; 38 | } secp256k1_fe_storage; 39 | 40 | #define SECP256K1_FE_STORAGE_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {{ \ 41 | (d0) | (((uint64_t)(d1)) << 32), \ 42 | (d2) | (((uint64_t)(d3)) << 32), \ 43 | (d4) | (((uint64_t)(d5)) << 32), \ 44 | (d6) | (((uint64_t)(d7)) << 32) \ 45 | }} 46 | 47 | #endif 48 | -------------------------------------------------------------------------------- /Makefile.am: -------------------------------------------------------------------------------- 1 | ACLOCAL_AMFLAGS = -I build-aux/m4 2 | .PHONY: gen 3 | .INTERMEDIATE: $(GENBIN) 4 | 5 | DIST_SUBDIRS = src/secp256k1 6 | 7 | LIBSECP256K1=src/secp256k1/libsecp256k1.la 8 | 9 | $(LIBSECP256K1): $(wildcard src/secp256k1/src/*) $(wildcard src/secp256k1/include/*) 10 | $(AM_V_at)$(MAKE) $(AM_MAKEFLAGS) -C $(@D) $(@F) 11 | 12 | lib_LTLIBRARIES = libbtc.la 13 | include_HEADERS = include/btc/btc.h \ 14 | include/btc/tx.h \ 15 | include/btc/base58.h \ 16 | include/btc/bip32.h \ 17 | include/btc/ecc_key.h \ 18 | include/btc/ecc.h 19 | 20 | noinst_HEADERS = \ 21 | src/sha2.h \ 22 | src/utils.h \ 23 | src/ripemd160.h \ 24 | src/random.h \ 25 | src/vector.h \ 26 | src/buffer.h \ 27 | src/cstr.h \ 28 | src/serialize.h \ 29 | src/script.h 30 | 31 | pkgconfigdir = $(libdir)/pkgconfig 32 | pkgconfig_DATA = libbtc.pc 33 | 34 | libbtc_la_SOURCES = \ 35 | src/sha2.c \ 36 | src/utils.c \ 37 | src/base58.c \ 38 | src/ripemd160.c \ 39 | src/bip32.c \ 40 | src/ecc_libsecp256k1.c \ 41 | src/random.c \ 42 | src/vector.c \ 43 | src/buffer.c \ 44 | src/cstr.c \ 45 | src/serialize.c \ 46 | src/tx.c \ 47 | src/script.c \ 48 | src/ecc_key.c 49 | 50 | libbtc_la_LDFLAGS = \ 51 | -version-info 1:0:0 \ 52 | -no-undefined 53 | libbtc_la_CFLAGS = -I$(top_srcdir)/include 54 | libbtc_la_LIBADD = $(LIBSECP256K1) 55 | 56 | if USE_TESTS 57 | noinst_PROGRAMS = tests 58 | tests_LDADD = libbtc.la 59 | tests_SOURCES = \ 60 | test/utest.h \ 61 | test/unittester.c \ 62 | test/sha2_tests.c \ 63 | test/base58check_tests.c \ 64 | test/bip32_tests.c \ 65 | test/random_tests.c \ 66 | test/ecc_tests.c \ 67 | test/vector_tests.c \ 68 | test/cstr_tests.c \ 69 | test/buffer_tests.c \ 70 | test/utils_tests.c \ 71 | test/serialize_tests.c \ 72 | test/tx_tests.c \ 73 | test/eckey_tests.c 74 | 75 | tests_CFLAGS = -I$(top_srcdir)/include 76 | tests_CPPFLAGS = -I$(top_srcdir)/src 77 | tests_LDFLAGS = -static 78 | TESTS = tests 79 | endif -------------------------------------------------------------------------------- /include/btc/btc.h: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | The MIT License (MIT) 4 | 5 | Copyright (c) 2015 Jonas Schnelli 6 | 7 | Permission is hereby granted, free of charge, to any person obtaining 8 | a copy of this software and associated documentation files (the "Software"), 9 | to deal in the Software without restriction, including without limitation 10 | the rights to use, copy, modify, merge, publish, distribute, sublicense, 11 | and/or sell copies of the Software, and to permit persons to whom the 12 | Software is furnished to do so, subject to the following conditions: 13 | 14 | The above copyright notice and this permission notice shall be included 15 | in all copies or substantial portions of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 18 | OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 19 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 20 | THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES 21 | OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 22 | ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 23 | OTHER DEALINGS IN THE SOFTWARE. 24 | 25 | */ 26 | 27 | #ifndef _LIBBTC_H_ 28 | #define _LIBBTC_H_ 29 | 30 | #include 31 | #include 32 | 33 | #include "libbtc-config.h" 34 | 35 | #if defined(HAVE_STDBOOL_H) && defined(HAVE_BOOL_T) 36 | #include 37 | #endif 38 | 39 | #ifdef __cplusplus 40 | extern "C" { 41 | #endif 42 | 43 | #ifndef LIBBTC_API 44 | # if defined(_WIN32) 45 | # ifdef LIBBTC_BUILD 46 | # define LIBBTC_API __declspec(dllexport) 47 | # else 48 | # define LIBBTC_API 49 | # endif 50 | # elif defined(__GNUC__) && defined(LIBBTC_BUILD) 51 | # define LIBBTC_API __attribute__ ((visibility ("default"))) 52 | # else 53 | # define LIBBTC_API 54 | # endif 55 | #endif 56 | 57 | #ifdef __cplusplus 58 | } 59 | #endif 60 | 61 | #endif //_LIBBTC_H_ 62 | -------------------------------------------------------------------------------- /src/utils.h: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | The MIT License (MIT) 4 | 5 | Copyright (c) 2015 Douglas J. Bakkum 6 | Copyright (c) 2015 Jonas Schnelli 7 | 8 | Permission is hereby granted, free of charge, to any person obtaining 9 | a copy of this software and associated documentation files (the "Software"), 10 | to deal in the Software without restriction, including without limitation 11 | the rights to use, copy, modify, merge, publish, distribute, sublicense, 12 | and/or sell copies of the Software, and to permit persons to whom the 13 | Software is furnished to do so, subject to the following conditions: 14 | 15 | The above copyright notice and this permission notice shall be included 16 | in all copies or substantial portions of the Software. 17 | 18 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 19 | OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 21 | THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES 22 | OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 23 | ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 24 | OTHER DEALINGS IN THE SOFTWARE. 25 | 26 | */ 27 | 28 | 29 | #ifndef _UTILS_H_ 30 | #define _UTILS_H_ 31 | 32 | 33 | #include 34 | #include 35 | 36 | 37 | #define TO_UINT8_HEX_BUF_LEN 2048 38 | #define VARINT_LEN 20 39 | 40 | #define strlens(s) (s == NULL ? 0 : strlen(s)) 41 | 42 | 43 | void utils_clear_buffers(void); 44 | void utils_hex_to_bin(const char *str, unsigned char *out, int inLen, int *outLen); 45 | void utils_bin_to_hex(unsigned char *bin_in, size_t inlen, char *hex_out); 46 | uint8_t *utils_hex_to_uint8(const char *str); 47 | char *utils_uint8_to_hex(const uint8_t *bin, size_t l); 48 | void utils_reverse_hex(char *h, int len); 49 | void utils_uint64_to_varint(char *vi, int *l, uint64_t i); 50 | int utils_varint_to_uint64(const char *vi, uint64_t *i); 51 | 52 | #endif 53 | -------------------------------------------------------------------------------- /test/ecc_tests.c: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2015 Jonas Schnelli * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | #include 13 | 14 | #include "random.h" 15 | #include "utest.h" 16 | #include "utils.h" 17 | 18 | void test_ecc() 19 | { 20 | unsigned char r_buf[32]; 21 | memset(r_buf, 0, 32); 22 | random_init(); 23 | 24 | while(ecc_verify_privatekey(r_buf) == 0) 25 | { 26 | random_bytes(r_buf, 32, 0); 27 | } 28 | 29 | memset(r_buf, 0xFF, 32); 30 | u_assert_int_eq(ecc_verify_privatekey(r_buf), 0); //secp256k1 overflow 31 | 32 | uint8_t pub_key33[33],pub_key33_invalid[33], pub_key65[65], pub_key65_invalid[65]; 33 | 34 | memcpy(pub_key33, utils_hex_to_uint8("02fcba7ecf41bc7e1be4ee122d9d22e3333671eb0a3a87b5cdf099d59874e1940f"), 35 | 33); 36 | memcpy(pub_key33_invalid, utils_hex_to_uint8("999999999941bc7e1be4ee122d9d22e3333671eb0a3a87b5cdf099d59874e1940f"), 37 | 33); 38 | memcpy(pub_key65, utils_hex_to_uint8("044054fd18aeb277aeedea01d3f3986ff4e5be18092a04339dcf4e524e2c0a09746c7083ed2097011b1223a17a644e81f59aa3de22dac119fd980b36a8ff29a244"), 39 | 65); 40 | memcpy(pub_key65_invalid, utils_hex_to_uint8("044054fd18aeb277aeedea01d3f3986ff4e5be18092a04339dcf4e524e2c0a09746c7083ed2097011b1223a17a644e81f59aa3de22dac119fd980b39999f29a244"), 41 | 65); 42 | 43 | 44 | u_assert_int_eq(ecc_verify_pubkey(pub_key33, 1), 1); 45 | u_assert_int_eq(ecc_verify_pubkey(pub_key65, 0), 1); 46 | 47 | u_assert_int_eq(ecc_verify_pubkey(pub_key33_invalid, 1), 0); 48 | u_assert_int_eq(ecc_verify_pubkey(pub_key65_invalid, 0), 0); 49 | } 50 | -------------------------------------------------------------------------------- /src/secp256k1/src/bench.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2014 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_BENCH_H_ 8 | #define _SECP256K1_BENCH_H_ 9 | 10 | #include 11 | #include 12 | #include "sys/time.h" 13 | 14 | static double gettimedouble(void) { 15 | struct timeval tv; 16 | gettimeofday(&tv, NULL); 17 | return tv.tv_usec * 0.000001 + tv.tv_sec; 18 | } 19 | 20 | void print_number(double x) { 21 | double y = x; 22 | int c = 0; 23 | if (y < 0.0) { 24 | y = -y; 25 | } 26 | while (y < 100.0) { 27 | y *= 10.0; 28 | c++; 29 | } 30 | printf("%.*f", c, x); 31 | } 32 | 33 | void run_benchmark(char *name, void (*benchmark)(void*), void (*setup)(void*), void (*teardown)(void*), void* data, int count, int iter) { 34 | int i; 35 | double min = HUGE_VAL; 36 | double sum = 0.0; 37 | double max = 0.0; 38 | for (i = 0; i < count; i++) { 39 | double begin, total; 40 | if (setup != NULL) { 41 | setup(data); 42 | } 43 | begin = gettimedouble(); 44 | benchmark(data); 45 | total = gettimedouble() - begin; 46 | if (teardown != NULL) { 47 | teardown(data); 48 | } 49 | if (total < min) { 50 | min = total; 51 | } 52 | if (total > max) { 53 | max = total; 54 | } 55 | sum += total; 56 | } 57 | printf("%s: min ", name); 58 | print_number(min * 1000000.0 / iter); 59 | printf("us / avg "); 60 | print_number((sum / count) * 1000000.0 / iter); 61 | printf("us / max "); 62 | print_number(max * 1000000.0 / iter); 63 | printf("us\n"); 64 | } 65 | 66 | #endif 67 | -------------------------------------------------------------------------------- /src/secp256k1/src/field_10x26.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2013, 2014 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_FIELD_REPR_ 8 | #define _SECP256K1_FIELD_REPR_ 9 | 10 | #include 11 | 12 | typedef struct { 13 | /* X = sum(i=0..9, elem[i]*2^26) mod n */ 14 | uint32_t n[10]; 15 | #ifdef VERIFY 16 | int magnitude; 17 | int normalized; 18 | #endif 19 | } secp256k1_fe; 20 | 21 | /* Unpacks a constant into a overlapping multi-limbed FE element. */ 22 | #define SECP256K1_FE_CONST_INNER(d7, d6, d5, d4, d3, d2, d1, d0) { \ 23 | (d0) & 0x3FFFFFFUL, \ 24 | (((uint32_t)d0) >> 26) | (((uint32_t)(d1) & 0xFFFFFUL) << 6), \ 25 | (((uint32_t)d1) >> 20) | (((uint32_t)(d2) & 0x3FFFUL) << 12), \ 26 | (((uint32_t)d2) >> 14) | (((uint32_t)(d3) & 0xFFUL) << 18), \ 27 | (((uint32_t)d3) >> 8) | (((uint32_t)(d4) & 0x3UL) << 24), \ 28 | (((uint32_t)d4) >> 2) & 0x3FFFFFFUL, \ 29 | (((uint32_t)d4) >> 28) | (((uint32_t)(d5) & 0x3FFFFFUL) << 4), \ 30 | (((uint32_t)d5) >> 22) | (((uint32_t)(d6) & 0xFFFFUL) << 10), \ 31 | (((uint32_t)d6) >> 16) | (((uint32_t)(d7) & 0x3FFUL) << 16), \ 32 | (((uint32_t)d7) >> 10) \ 33 | } 34 | 35 | #ifdef VERIFY 36 | #define SECP256K1_FE_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {SECP256K1_FE_CONST_INNER((d7), (d6), (d5), (d4), (d3), (d2), (d1), (d0)), 1, 1} 37 | #else 38 | #define SECP256K1_FE_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {SECP256K1_FE_CONST_INNER((d7), (d6), (d5), (d4), (d3), (d2), (d1), (d0))} 39 | #endif 40 | 41 | typedef struct { 42 | uint32_t n[8]; 43 | } secp256k1_fe_storage; 44 | 45 | #define SECP256K1_FE_STORAGE_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {{ (d0), (d1), (d2), (d3), (d4), (d5), (d6), (d7) }} 46 | #define SECP256K1_FE_STORAGE_CONST_GET(d) d.n[7], d.n[6], d.n[5], d.n[4],d.n[3], d.n[2], d.n[1], d.n[0] 47 | #endif 48 | -------------------------------------------------------------------------------- /src/secp256k1/src/modules/ecdh/main_impl.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2015 Andrew Poelstra * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_MODULE_ECDH_MAIN_ 8 | #define _SECP256K1_MODULE_ECDH_MAIN_ 9 | 10 | #include "include/secp256k1_ecdh.h" 11 | #include "ecmult_const_impl.h" 12 | 13 | int secp256k1_ecdh(const secp256k1_context* ctx, unsigned char *result, const secp256k1_pubkey *point, const unsigned char *scalar) { 14 | int ret = 0; 15 | int overflow = 0; 16 | secp256k1_gej res; 17 | secp256k1_ge pt; 18 | secp256k1_scalar s; 19 | ARG_CHECK(result != NULL); 20 | ARG_CHECK(point != NULL); 21 | ARG_CHECK(scalar != NULL); 22 | (void)ctx; 23 | 24 | secp256k1_pubkey_load(ctx, &pt, point); 25 | secp256k1_scalar_set_b32(&s, scalar, &overflow); 26 | if (overflow || secp256k1_scalar_is_zero(&s)) { 27 | ret = 0; 28 | } else { 29 | unsigned char x[32]; 30 | unsigned char y[1]; 31 | secp256k1_sha256_t sha; 32 | 33 | secp256k1_ecmult_const(&res, &pt, &s); 34 | secp256k1_ge_set_gej(&pt, &res); 35 | /* Compute a hash of the point in compressed form 36 | * Note we cannot use secp256k1_eckey_pubkey_serialize here since it does not 37 | * expect its output to be secret and has a timing sidechannel. */ 38 | secp256k1_fe_normalize(&pt.x); 39 | secp256k1_fe_normalize(&pt.y); 40 | secp256k1_fe_get_b32(x, &pt.x); 41 | y[0] = 0x02 | secp256k1_fe_is_odd(&pt.y); 42 | 43 | secp256k1_sha256_initialize(&sha); 44 | secp256k1_sha256_write(&sha, y, sizeof(y)); 45 | secp256k1_sha256_write(&sha, x, sizeof(x)); 46 | secp256k1_sha256_finalize(&sha, result); 47 | ret = 1; 48 | } 49 | 50 | secp256k1_scalar_clear(&s); 51 | return ret; 52 | } 53 | 54 | #endif 55 | -------------------------------------------------------------------------------- /test/eckey_tests.c: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | The MIT License (MIT) 4 | 5 | Copyright (c) 2015 Jonas Schnelli 6 | 7 | Permission is hereby granted, free of charge, to any person obtaining 8 | a copy of this software and associated documentation files (the "Software"), 9 | to deal in the Software without restriction, including without limitation 10 | the rights to use, copy, modify, merge, publish, distribute, sublicense, 11 | and/or sell copies of the Software, and to permit persons to whom the 12 | Software is furnished to do so, subject to the following conditions: 13 | 14 | The above copyright notice and this permission notice shall be included 15 | in all copies or substantial portions of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 18 | OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 19 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 20 | THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES 21 | OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 22 | ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 23 | OTHER DEALINGS IN THE SOFTWARE. 24 | 25 | */ 26 | 27 | 28 | #include 29 | #include 30 | #include 31 | #include 32 | 33 | #include 34 | 35 | #include "utils.h" 36 | 37 | void test_eckey() 38 | { 39 | btc_key* key = btc_privkey_new(); 40 | btc_privkey_gen(key); 41 | 42 | btc_pubkey *pubkey = btc_pubkey_new(); 43 | btc_pubkey_from_key(key, pubkey); 44 | 45 | unsigned int i; 46 | for(i = 33; i < BTC_ECKEY_UNCOMPRESSED_LENGTH; i++) 47 | assert(pubkey->pubkey[i] == 0); 48 | 49 | uint8_t *hash = utils_hex_to_uint8((const char *)"26db47a48a10b9b0b697b793f5c0231aa35fe192c9d063d7b03a55e3c302850a"); 50 | uint8_t hash2[32]; 51 | memcpy(hash2, hash, 32); 52 | unsigned char sig[100]; 53 | int outlen = 0; 54 | btc_key_sign_hash(key, hash, sig, &outlen); 55 | 56 | btc_pubkey_verify_sig(pubkey, hash2, sig, outlen); 57 | 58 | btc_pubkey_free(pubkey); 59 | btc_privkey_free(key); 60 | } 61 | -------------------------------------------------------------------------------- /src/random.c: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | The MIT License (MIT) 4 | 5 | Copyright (c) 2015 Douglas J. Bakkum 6 | 7 | Permission is hereby granted, free of charge, to any person obtaining 8 | a copy of this software and associated documentation files (the "Software"), 9 | to deal in the Software without restriction, including without limitation 10 | the rights to use, copy, modify, merge, publish, distribute, sublicense, 11 | and/or sell copies of the Software, and to permit persons to whom the 12 | Software is furnished to do so, subject to the following conditions: 13 | 14 | The above copyright notice and this permission notice shall be included 15 | in all copies or substantial portions of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 18 | OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 19 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 20 | THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES 21 | OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 22 | ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 23 | OTHER DEALINGS IN THE SOFTWARE. 24 | 25 | */ 26 | 27 | #include "random.h" 28 | 29 | #include 30 | #include 31 | #include 32 | #include 33 | 34 | #include "btc/btc.h" 35 | 36 | #ifdef TESTING 37 | void random_init(void) 38 | { 39 | srand(time(NULL)); 40 | } 41 | 42 | 43 | int random_bytes(uint8_t *buf, uint32_t len, uint8_t update_seed) 44 | { 45 | (void) update_seed; 46 | for (uint32_t i = 0; i < len; i++) { 47 | buf[i] = rand(); 48 | } 49 | 50 | return true; 51 | } 52 | #elif FILE_RANDOM 53 | void random_init(void) { } 54 | 55 | 56 | int random_bytes(uint8_t *buf, uint32_t len, const uint8_t update_seed) 57 | { 58 | (void)update_seed;//unused 59 | FILE *frand = fopen(RANDOM_DEVICE, "r"); 60 | if (!frand) { 61 | return false; 62 | } 63 | 64 | size_t len_read = fread(buf, 1, len, frand); 65 | assert(len_read == len); 66 | fclose(frand); 67 | return true; 68 | } 69 | #else 70 | //provide extern interface 71 | #endif 72 | -------------------------------------------------------------------------------- /src/vector.h: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | The MIT License (MIT) 4 | 5 | Copyright (c) 2015 Jonas Schnelli 6 | 7 | Permission is hereby granted, free of charge, to any person obtaining 8 | a copy of this software and associated documentation files (the "Software"), 9 | to deal in the Software without restriction, including without limitation 10 | the rights to use, copy, modify, merge, publish, distribute, sublicense, 11 | and/or sell copies of the Software, and to permit persons to whom the 12 | Software is furnished to do so, subject to the following conditions: 13 | 14 | The above copyright notice and this permission notice shall be included 15 | in all copies or substantial portions of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 18 | OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 19 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 20 | THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES 21 | OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 22 | ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 23 | OTHER DEALINGS IN THE SOFTWARE. 24 | 25 | */ 26 | 27 | #ifndef LIBBTC_VECTOR_H_ 28 | #define LIBBTC_VECTOR_H_ 29 | 30 | #include 31 | #include 32 | #include 33 | 34 | typedef struct vector { 35 | void **data; /* array of pointers */ 36 | size_t len; /* array element count */ 37 | size_t alloc; /* allocated array elements */ 38 | 39 | void (*elem_free_f)(void *); 40 | } vector; 41 | 42 | extern vector *vector_new(size_t res, void (*free_f)(void *)); 43 | extern void vector_free(vector *vec, bool free_array); 44 | 45 | extern bool vector_add(vector *vec, void *data); 46 | extern bool vector_remove(vector *vec, void *data); 47 | extern void vector_remove_idx(vector *vec, size_t idx); 48 | extern void vector_remove_range(vector *vec, size_t idx, size_t len); 49 | extern bool vector_resize(vector *vec, size_t newsz); 50 | 51 | extern ssize_t vector_find(vector *vec, void *data); 52 | 53 | #define vector_idx(vec, idx) ((vec)->data[(idx)]) 54 | 55 | #endif /* LIBBTC_VECTOR_H_ */ 56 | -------------------------------------------------------------------------------- /test/unittester.c: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2015 Jonas Schnelli * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #if defined HAVE_CONFIG_H 8 | #include "libbtc-config.h" 9 | #endif 10 | 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | #include "utest.h" 17 | 18 | #ifdef HAVE_BUILTIN_EXPECT 19 | #define EXPECT(x,c) __builtin_expect((x),(c)) 20 | #else 21 | #define EXPECT(x,c) (x) 22 | #endif 23 | 24 | #define TEST_FAILURE(msg) do { \ 25 | fprintf(stderr, "%s:%d: %s\n", __FILE__, __LINE__, msg); \ 26 | abort(); \ 27 | } while(0) 28 | 29 | #define CHECK(cond) do { \ 30 | if (EXPECT(!(cond), 0)) { \ 31 | TEST_FAILURE("test condition failed: " #cond); \ 32 | } \ 33 | } while(0) 34 | 35 | extern void test_random(); 36 | extern void test_sha_256(); 37 | extern void test_sha_512(); 38 | extern void test_sha_hmac(); 39 | extern void test_base58check(); 40 | extern void test_bip32(); 41 | extern void test_ecc(); 42 | extern void test_vector(); 43 | extern void test_cstr(); 44 | extern void test_buffer(); 45 | extern void test_utils(); 46 | extern void test_serialize(); 47 | extern void test_tx_serialization(); 48 | extern void test_tx_sighash(); 49 | extern void test_script_parse(); 50 | extern void test_eckey(); 51 | 52 | 53 | extern void ecc_start(); 54 | extern void ecc_stop(); 55 | 56 | int U_TESTS_RUN = 0; 57 | int U_TESTS_FAIL = 0; 58 | 59 | int main() 60 | { 61 | ecc_start(); 62 | 63 | test_random(); 64 | test_sha_256(); 65 | test_sha_512(); 66 | test_sha_hmac(); 67 | test_base58check(); 68 | test_utils(); 69 | 70 | test_bip32(); 71 | test_ecc(); 72 | test_vector(); 73 | test_cstr(); 74 | test_buffer(); 75 | test_serialize(); 76 | test_tx_serialization(); 77 | test_tx_sighash(); 78 | test_script_parse(); 79 | 80 | test_eckey(); 81 | 82 | ecc_stop(); 83 | return 0; 84 | } 85 | -------------------------------------------------------------------------------- /src/secp256k1/.travis.yml: -------------------------------------------------------------------------------- 1 | language: c 2 | sudo: false 3 | addons: 4 | apt: 5 | packages: libgmp-dev 6 | compiler: 7 | - clang 8 | - gcc 9 | env: 10 | global: 11 | - FIELD=auto BIGNUM=auto SCALAR=auto ENDOMORPHISM=no STATICPRECOMPUTATION=yes ASM=no BUILD=check EXTRAFLAGS= HOST= ECDH=no schnorr=NO RECOVERY=NO 12 | matrix: 13 | - SCALAR=32bit RECOVERY=yes 14 | - SCALAR=32bit FIELD=32bit ECDH=yes 15 | - SCALAR=64bit 16 | - FIELD=64bit RECOVERY=yes 17 | - FIELD=64bit ENDOMORPHISM=yes 18 | - FIELD=64bit ENDOMORPHISM=yes ECDH=yes 19 | - FIELD=64bit ASM=x86_64 20 | - FIELD=64bit ENDOMORPHISM=yes ASM=x86_64 21 | - FIELD=32bit SCHNORR=yes 22 | - FIELD=32bit ENDOMORPHISM=yes 23 | - BIGNUM=no 24 | - BIGNUM=no ENDOMORPHISM=yes SCHNORR=yes RECOVERY=yes 25 | - BIGNUM=no STATICPRECOMPUTATION=no 26 | - BUILD=distcheck 27 | - EXTRAFLAGS=CFLAGS=-DDETERMINISTIC 28 | matrix: 29 | fast_finish: true 30 | include: 31 | - compiler: clang 32 | env: HOST=i686-linux-gnu ENDOMORPHISM=yes 33 | addons: 34 | apt: 35 | packages: 36 | - gcc-multilib 37 | - libgmp-dev:i386 38 | - compiler: clang 39 | env: HOST=i686-linux-gnu 40 | addons: 41 | apt: 42 | packages: 43 | - gcc-multilib 44 | - compiler: gcc 45 | env: HOST=i686-linux-gnu ENDOMORPHISM=yes 46 | addons: 47 | apt: 48 | packages: 49 | - gcc-multilib 50 | - compiler: gcc 51 | env: HOST=i686-linux-gnu 52 | addons: 53 | apt: 54 | packages: 55 | - gcc-multilib 56 | - libgmp-dev:i386 57 | before_script: ./autogen.sh 58 | script: 59 | - if [ -n "$HOST" ]; then export USE_HOST="--host=$HOST"; fi 60 | - if [ "x$HOST" = "xi686-linux-gnu" ]; then export CC="$CC -m32"; fi 61 | - ./configure --enable-endomorphism=$ENDOMORPHISM --with-field=$FIELD --with-bignum=$BIGNUM --with-scalar=$SCALAR --enable-ecmult-static-precomputation=$STATICPRECOMPUTATION --enable-module-ecdh=$ECDH --enable-module-schnorr=$SCHNORR $EXTRAFLAGS $USE_HOST && make -j2 $BUILD 62 | os: linux 63 | -------------------------------------------------------------------------------- /src/secp256k1/src/testrand_impl.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2013, 2014 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_TESTRAND_IMPL_H_ 8 | #define _SECP256K1_TESTRAND_IMPL_H_ 9 | 10 | #include 11 | #include 12 | 13 | #include "testrand.h" 14 | #include "hash.h" 15 | 16 | static secp256k1_rfc6979_hmac_sha256_t secp256k1_test_rng; 17 | static uint32_t secp256k1_test_rng_precomputed[8]; 18 | static int secp256k1_test_rng_precomputed_used = 8; 19 | 20 | SECP256K1_INLINE static void secp256k1_rand_seed(const unsigned char *seed16) { 21 | secp256k1_rfc6979_hmac_sha256_initialize(&secp256k1_test_rng, seed16, 16); 22 | } 23 | 24 | SECP256K1_INLINE static uint32_t secp256k1_rand32(void) { 25 | if (secp256k1_test_rng_precomputed_used == 8) { 26 | secp256k1_rfc6979_hmac_sha256_generate(&secp256k1_test_rng, (unsigned char*)(&secp256k1_test_rng_precomputed[0]), sizeof(secp256k1_test_rng_precomputed)); 27 | secp256k1_test_rng_precomputed_used = 0; 28 | } 29 | return secp256k1_test_rng_precomputed[secp256k1_test_rng_precomputed_used++]; 30 | } 31 | 32 | static void secp256k1_rand256(unsigned char *b32) { 33 | secp256k1_rfc6979_hmac_sha256_generate(&secp256k1_test_rng, b32, 32); 34 | } 35 | 36 | static void secp256k1_rand256_test(unsigned char *b32) { 37 | int bits=0; 38 | uint64_t ent = 0; 39 | int entleft = 0; 40 | memset(b32, 0, 32); 41 | while (bits < 256) { 42 | int now; 43 | uint32_t val; 44 | if (entleft < 12) { 45 | ent |= ((uint64_t)secp256k1_rand32()) << entleft; 46 | entleft += 32; 47 | } 48 | now = 1 + ((ent % 64)*((ent >> 6) % 32)+16)/31; 49 | val = 1 & (ent >> 11); 50 | ent >>= 12; 51 | entleft -= 12; 52 | while (now > 0 && bits < 256) { 53 | b32[bits / 8] |= val << (bits % 8); 54 | now--; 55 | bits++; 56 | } 57 | } 58 | } 59 | 60 | #endif 61 | -------------------------------------------------------------------------------- /src/secp256k1/src/bench_recover.c: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2014-2015 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #include "include/secp256k1.h" 8 | #include "include/secp256k1_recovery.h" 9 | #include "util.h" 10 | #include "bench.h" 11 | 12 | typedef struct { 13 | secp256k1_context *ctx; 14 | unsigned char msg[32]; 15 | unsigned char sig[64]; 16 | } bench_recover_t; 17 | 18 | void bench_recover(void* arg) { 19 | int i; 20 | bench_recover_t *data = (bench_recover_t*)arg; 21 | secp256k1_pubkey pubkey; 22 | unsigned char pubkeyc[33]; 23 | 24 | for (i = 0; i < 20000; i++) { 25 | int j; 26 | size_t pubkeylen = 33; 27 | secp256k1_ecdsa_recoverable_signature sig; 28 | CHECK(secp256k1_ecdsa_recoverable_signature_parse_compact(data->ctx, &sig, data->sig, i % 2)); 29 | CHECK(secp256k1_ecdsa_recover(data->ctx, &pubkey, &sig, data->msg)); 30 | CHECK(secp256k1_ec_pubkey_serialize(data->ctx, pubkeyc, &pubkeylen, &pubkey, SECP256K1_EC_COMPRESSED)); 31 | for (j = 0; j < 32; j++) { 32 | data->sig[j + 32] = data->msg[j]; /* Move former message to S. */ 33 | data->msg[j] = data->sig[j]; /* Move former R to message. */ 34 | data->sig[j] = pubkeyc[j + 1]; /* Move recovered pubkey X coordinate to R (which must be a valid X coordinate). */ 35 | } 36 | } 37 | } 38 | 39 | void bench_recover_setup(void* arg) { 40 | int i; 41 | bench_recover_t *data = (bench_recover_t*)arg; 42 | 43 | for (i = 0; i < 32; i++) { 44 | data->msg[i] = 1 + i; 45 | } 46 | for (i = 0; i < 64; i++) { 47 | data->sig[i] = 65 + i; 48 | } 49 | } 50 | 51 | int main(void) { 52 | bench_recover_t data; 53 | 54 | data.ctx = secp256k1_context_create(SECP256K1_CONTEXT_VERIFY); 55 | 56 | run_benchmark("ecdsa_recover", bench_recover, bench_recover_setup, NULL, &data, 10, 20000); 57 | 58 | secp256k1_context_destroy(data.ctx); 59 | return 0; 60 | } 61 | -------------------------------------------------------------------------------- /src/secp256k1/src/java/org/bitcoin/NativeSecp256k1.java: -------------------------------------------------------------------------------- 1 | package org.bitcoin; 2 | 3 | import java.nio.ByteBuffer; 4 | import java.nio.ByteOrder; 5 | 6 | import com.google.common.base.Preconditions; 7 | 8 | 9 | /** 10 | * This class holds native methods to handle ECDSA verification. 11 | * You can find an example library that can be used for this at 12 | * https://github.com/sipa/secp256k1 13 | */ 14 | public class NativeSecp256k1 { 15 | public static final boolean enabled; 16 | static { 17 | boolean isEnabled = true; 18 | try { 19 | System.loadLibrary("javasecp256k1"); 20 | } catch (UnsatisfiedLinkError e) { 21 | isEnabled = false; 22 | } 23 | enabled = isEnabled; 24 | } 25 | 26 | private static ThreadLocal nativeECDSABuffer = new ThreadLocal(); 27 | /** 28 | * Verifies the given secp256k1 signature in native code. 29 | * Calling when enabled == false is undefined (probably library not loaded) 30 | * 31 | * @param data The data which was signed, must be exactly 32 bytes 32 | * @param signature The signature 33 | * @param pub The public key which did the signing 34 | */ 35 | public static boolean verify(byte[] data, byte[] signature, byte[] pub) { 36 | Preconditions.checkArgument(data.length == 32 && signature.length <= 520 && pub.length <= 520); 37 | 38 | ByteBuffer byteBuff = nativeECDSABuffer.get(); 39 | if (byteBuff == null) { 40 | byteBuff = ByteBuffer.allocateDirect(32 + 8 + 520 + 520); 41 | byteBuff.order(ByteOrder.nativeOrder()); 42 | nativeECDSABuffer.set(byteBuff); 43 | } 44 | byteBuff.rewind(); 45 | byteBuff.put(data); 46 | byteBuff.putInt(signature.length); 47 | byteBuff.putInt(pub.length); 48 | byteBuff.put(signature); 49 | byteBuff.put(pub); 50 | return secp256k1_ecdsa_verify(byteBuff) == 1; 51 | } 52 | 53 | /** 54 | * @param byteBuff signature format is byte[32] data, 55 | * native-endian int signatureLength, native-endian int pubkeyLength, 56 | * byte[signatureLength] signature, byte[pubkeyLength] pub 57 | * @returns 1 for valid signature, anything else for invalid 58 | */ 59 | private static native int secp256k1_ecdsa_verify(ByteBuffer byteBuff); 60 | } 61 | -------------------------------------------------------------------------------- /src/secp256k1/build-aux/m4/bitcoin_secp.m4: -------------------------------------------------------------------------------- 1 | dnl libsecp25k1 helper checks 2 | AC_DEFUN([SECP_INT128_CHECK],[ 3 | has_int128=$ac_cv_type___int128 4 | ]) 5 | 6 | dnl 7 | AC_DEFUN([SECP_64BIT_ASM_CHECK],[ 8 | AC_MSG_CHECKING(for x86_64 assembly availability) 9 | AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ 10 | #include ]],[[ 11 | uint64_t a = 11, tmp; 12 | __asm__ __volatile__("movq $0x100000000,%1; mulq %%rsi" : "+a"(a) : "S"(tmp) : "cc", "%rdx"); 13 | ]])],[has_64bit_asm=yes],[has_64bit_asm=no]) 14 | AC_MSG_RESULT([$has_64bit_asm]) 15 | ]) 16 | 17 | dnl 18 | AC_DEFUN([SECP_OPENSSL_CHECK],[ 19 | has_libcrypto=no 20 | m4_ifdef([PKG_CHECK_MODULES],[ 21 | PKG_CHECK_MODULES([CRYPTO], [libcrypto], [has_libcrypto=yes],[has_libcrypto=no]) 22 | if test x"$has_libcrypto" = x"yes"; then 23 | TEMP_LIBS="$LIBS" 24 | LIBS="$LIBS $CRYPTO_LIBS" 25 | AC_CHECK_LIB(crypto, main,[AC_DEFINE(HAVE_LIBCRYPTO,1,[Define this symbol if libcrypto is installed])],[has_libcrypto=no]) 26 | LIBS="$TEMP_LIBS" 27 | fi 28 | ]) 29 | if test x$has_libcrypto = xno; then 30 | AC_CHECK_HEADER(openssl/crypto.h,[ 31 | AC_CHECK_LIB(crypto, main,[ 32 | has_libcrypto=yes 33 | CRYPTO_LIBS=-lcrypto 34 | AC_DEFINE(HAVE_LIBCRYPTO,1,[Define this symbol if libcrypto is installed]) 35 | ]) 36 | ]) 37 | LIBS= 38 | fi 39 | if test x"$has_libcrypto" = x"yes" && test x"$has_openssl_ec" = x; then 40 | AC_MSG_CHECKING(for EC functions in libcrypto) 41 | AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ 42 | #include 43 | #include 44 | #include ]],[[ 45 | EC_KEY *eckey = EC_KEY_new_by_curve_name(NID_secp256k1); 46 | ECDSA_sign(0, NULL, 0, NULL, NULL, eckey); 47 | ECDSA_verify(0, NULL, 0, NULL, 0, eckey); 48 | EC_KEY_free(eckey); 49 | ]])],[has_openssl_ec=yes],[has_openssl_ec=no]) 50 | AC_MSG_RESULT([$has_openssl_ec]) 51 | fi 52 | ]) 53 | 54 | dnl 55 | AC_DEFUN([SECP_GMP_CHECK],[ 56 | if test x"$has_gmp" != x"yes"; then 57 | CPPFLAGS_TEMP="$CPPFLAGS" 58 | CPPFLAGS="$GMP_CPPFLAGS $CPPFLAGS" 59 | LIBS_TEMP="$LIBS" 60 | LIBS="$GMP_LIBS $LIBS" 61 | AC_CHECK_HEADER(gmp.h,[AC_CHECK_LIB(gmp, __gmpz_init,[has_gmp=yes; GMP_LIBS="$GMP_LIBS -lgmp"; AC_DEFINE(HAVE_LIBGMP,1,[Define this symbol if libgmp is installed])])]) 62 | CPPFLAGS="$CPPFLAGS_TEMP" 63 | LIBS="$LIBS_TEMP" 64 | fi 65 | ]) 66 | -------------------------------------------------------------------------------- /src/secp256k1/src/ecmult_gen.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2013, 2014 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_ECMULT_GEN_ 8 | #define _SECP256K1_ECMULT_GEN_ 9 | 10 | #include "scalar.h" 11 | #include "group.h" 12 | 13 | typedef struct { 14 | /* For accelerating the computation of a*G: 15 | * To harden against timing attacks, use the following mechanism: 16 | * * Break up the multiplicand into groups of 4 bits, called n_0, n_1, n_2, ..., n_63. 17 | * * Compute sum(n_i * 16^i * G + U_i, i=0..63), where: 18 | * * U_i = U * 2^i (for i=0..62) 19 | * * U_i = U * (1-2^63) (for i=63) 20 | * where U is a point with no known corresponding scalar. Note that sum(U_i, i=0..63) = 0. 21 | * For each i, and each of the 16 possible values of n_i, (n_i * 16^i * G + U_i) is 22 | * precomputed (call it prec(i, n_i)). The formula now becomes sum(prec(i, n_i), i=0..63). 23 | * None of the resulting prec group elements have a known scalar, and neither do any of 24 | * the intermediate sums while computing a*G. 25 | */ 26 | secp256k1_ge_storage (*prec)[64][16]; /* prec[j][i] = 16^j * i * G + U_i */ 27 | secp256k1_scalar blind; 28 | secp256k1_gej initial; 29 | } secp256k1_ecmult_gen_context; 30 | 31 | static void secp256k1_ecmult_gen_context_init(secp256k1_ecmult_gen_context* ctx); 32 | static void secp256k1_ecmult_gen_context_build(secp256k1_ecmult_gen_context* ctx, const secp256k1_callback* cb); 33 | static void secp256k1_ecmult_gen_context_clone(secp256k1_ecmult_gen_context *dst, 34 | const secp256k1_ecmult_gen_context* src, const secp256k1_callback* cb); 35 | static void secp256k1_ecmult_gen_context_clear(secp256k1_ecmult_gen_context* ctx); 36 | static int secp256k1_ecmult_gen_context_is_built(const secp256k1_ecmult_gen_context* ctx); 37 | 38 | /** Multiply with the generator: R = a*G */ 39 | static void secp256k1_ecmult_gen(const secp256k1_ecmult_gen_context* ctx, secp256k1_gej *r, const secp256k1_scalar *a); 40 | 41 | static void secp256k1_ecmult_gen_blind(secp256k1_ecmult_gen_context *ctx, const unsigned char *seed32); 42 | 43 | #endif 44 | -------------------------------------------------------------------------------- /test/cstr_tests.c: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) Copyright 2015 BitPay, Inc. * 3 | * Copyright (c) Copyright 2015 Jonas Schnelli * 4 | * Distributed under the MIT software license, see the accompanying * 5 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 6 | **********************************************************************/ 7 | 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | #include "cstr.h" 14 | 15 | void test_cstr() 16 | { 17 | cstring *s = cstr_new("foo"); 18 | assert(s != NULL); 19 | assert(s->len == 3); 20 | assert(strcmp(s->str, "foo") == 0); 21 | 22 | cstr_free(s, true); 23 | 24 | s = cstr_new_sz(200); 25 | assert(s != NULL); 26 | assert(s->alloc > 200); 27 | assert(s->len == 0); 28 | 29 | cstr_free(s, true); 30 | 31 | s = cstr_new_buf("foo", 2); 32 | assert(s != NULL); 33 | assert(s->len == 2); 34 | assert(strcmp(s->str, "fo") == 0); 35 | 36 | cstr_free(s, true); 37 | 38 | s = cstr_new(NULL); 39 | assert(s != NULL); 40 | cstr_append_buf(s, "f", 1); 41 | cstr_append_buf(s, "o", 1); 42 | cstr_append_buf(s, "o", 1); 43 | assert(s->len == 3); 44 | assert(strcmp(s->str, "foo") == 0); 45 | 46 | cstr_free(s, true); 47 | 48 | s = cstr_new("foo"); 49 | assert(s != NULL); 50 | 51 | cstr_resize(s, 2); 52 | cstr_resize(s, 2); 53 | assert(s->len == 2); 54 | assert(strcmp(s->str, "fo") == 0); 55 | 56 | cstr_resize(s, 4); 57 | assert(s->len == 4); 58 | assert(s->alloc > 4); 59 | memcpy(s->str, "food", 4); 60 | assert(strcmp(s->str, "food") == 0); 61 | 62 | cstr_free(s, true); 63 | 64 | cstring *s1 = cstr_new("foo"); 65 | cstring *s2 = cstr_new("foo"); 66 | cstring *s3 = cstr_new("bar"); 67 | cstring *s4 = cstr_new("bar1"); 68 | 69 | assert(cstr_equal(s1, s2) == true); 70 | assert(cstr_equal(s1, s3) == false); 71 | assert(cstr_equal(s1, NULL) == false); 72 | assert(cstr_equal(s2, s3) == false); 73 | assert(cstr_equal(s3, s3) == true); 74 | assert(cstr_equal(s3, s4) == false); 75 | cstr_erase(s4, 0,3); 76 | assert(strcmp(s4->str, "1") == 0); 77 | 78 | cstr_free(s1, true); 79 | cstr_free(s2, true); 80 | cstr_free(s3, true); 81 | cstr_free(s4, true); 82 | } 83 | -------------------------------------------------------------------------------- /test/utils_tests.c: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2015 Jonas Schnelli * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | #include "utils.h" 13 | 14 | void test_utils() 15 | { 16 | char hash[] = "28969cdfa74a12c82f3bad960b0b000aca2ac329deea5c2328ebc6f2ba9802c1"; 17 | uint8_t *hash_bin = utils_hex_to_uint8(hash); 18 | char *new = utils_uint8_to_hex(hash_bin, 32); 19 | assert(strncmp(new, hash, 64) == 0); 20 | 21 | uint64_t bigint = 0xFFFFFFFFFFFFFFFF; 22 | char vint[255]; 23 | int outlen; 24 | utils_uint64_to_varint(vint, &outlen, bigint); 25 | assert(outlen = 16); 26 | assert(strncmp("ffffffffffffffffff", vint, outlen) == 0); 27 | 28 | memset(vint, 0, 255); 29 | bigint = 0xFA; 30 | utils_uint64_to_varint(vint, &outlen, bigint); 31 | assert(outlen = 2); 32 | assert(strncmp("fa", vint, outlen) == 0); 33 | 34 | memset(vint, 0, 255); 35 | bigint = 0xFFA; 36 | utils_uint64_to_varint(vint, &outlen, bigint); 37 | assert(outlen = 4); 38 | assert(strncmp("fdfa0f", vint, outlen) == 0); 39 | 40 | memset(vint, 0, 255); 41 | bigint = 0xFFFFA; 42 | utils_uint64_to_varint(vint, &outlen, bigint); 43 | assert(outlen = 8); 44 | assert(strncmp("fefaff0f00", vint, outlen) == 0); 45 | 46 | char varint0[] = "fa"; 47 | utils_varint_to_uint64(varint0, &bigint); 48 | assert(bigint == 250); 49 | 50 | char varint1[] = "ffffffffffffffffff"; 51 | utils_varint_to_uint64(varint1, &bigint); 52 | assert(bigint == 0xFFFFFFFFFFFFFFFF); 53 | 54 | char varint2[] = "fdfa0f"; 55 | utils_varint_to_uint64(varint2, &bigint); 56 | assert(bigint == 4090); 57 | 58 | char varint3[] = "fefaff0f00"; 59 | utils_varint_to_uint64(varint3, &bigint); 60 | assert(bigint == 1048570); 61 | 62 | unsigned char data[] = {0x00, 0xFF, 0x00, 0xAA, 0x00, 0xFF, 0x00, 0xAA}; 63 | char hex[sizeof(data)*2+1]; 64 | utils_bin_to_hex(data, sizeof(data), hex); 65 | assert(strcmp(hex, "00ff00aa00ff00aa") == 0); 66 | 67 | unsigned char data2[sizeof(data)]; 68 | utils_hex_to_bin(hex, data2, strlen(hex), &outlen); 69 | assert(outlen == 8); 70 | assert(memcmp(data, data2, outlen) == 0); 71 | } 72 | -------------------------------------------------------------------------------- /include/btc/ecc_key.h: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | The MIT License (MIT) 4 | 5 | Copyright (c) 2015 Jonas Schnelli 6 | 7 | Permission is hereby granted, free of charge, to any person obtaining 8 | a copy of this software and associated documentation files (the "Software"), 9 | to deal in the Software without restriction, including without limitation 10 | the rights to use, copy, modify, merge, publish, distribute, sublicense, 11 | and/or sell copies of the Software, and to permit persons to whom the 12 | Software is furnished to do so, subject to the following conditions: 13 | 14 | The above copyright notice and this permission notice shall be included 15 | in all copies or substantial portions of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 18 | OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 19 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 20 | THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES 21 | OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 22 | ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 23 | OTHER DEALINGS IN THE SOFTWARE. 24 | 25 | */ 26 | 27 | #ifndef __LIBBTC_ECC_KEY_H__ 28 | #define __LIBBTC_ECC_KEY_H__ 29 | 30 | #include "btc.h" 31 | 32 | #include 33 | #include 34 | #include 35 | 36 | #define BTC_ECKEY_UNCOMPRESSED_LENGTH 64 37 | #define BTC_ECKEY_COMPRESSED_LENGTH 33 38 | #define BTC_ECKEY_PKEY_LENGTH 32 39 | 40 | typedef struct btc_key_ 41 | { 42 | uint8_t privkey[BTC_ECKEY_PKEY_LENGTH]; 43 | } btc_key; 44 | 45 | typedef struct btc_pubkey_ 46 | { 47 | bool compressed; 48 | uint8_t pubkey[BTC_ECKEY_UNCOMPRESSED_LENGTH]; 49 | } btc_pubkey; 50 | 51 | LIBBTC_API btc_key* btc_privkey_new(); 52 | LIBBTC_API void btc_privkey_gen(btc_key *privkey); 53 | LIBBTC_API void btc_privkey_free(btc_key *privkey); 54 | 55 | LIBBTC_API btc_pubkey* btc_pubkey_new(); 56 | LIBBTC_API void btc_pubkey_free(btc_pubkey* pubkey); 57 | LIBBTC_API void btc_pubkey_from_key(btc_key *privkey, btc_pubkey* pubkey_inout); 58 | 59 | //sign a 32byte message/hash and returns a DER encoded signature (through *sigout) 60 | LIBBTC_API bool btc_key_sign_hash(const btc_key *privkey, const uint8_t *hash, unsigned char *sigout, int *outlen); 61 | 62 | //verifies a DER encoded signature with given pubkey and return true if valid 63 | LIBBTC_API bool btc_pubkey_verify_sig(const btc_pubkey *pubkey, const uint8_t *hash, unsigned char *sigder, int len); 64 | 65 | #endif //__LIBBTC_ECC_KEY_H__ 66 | -------------------------------------------------------------------------------- /include/btc/bip32.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2013-2014 Tomas Dzetkulic 3 | * Copyright (c) 2013-2014 Pavol Rusnak 4 | * Copyright (c) 2015 Douglas J. Bakkumk 5 | * Copyright (c) 2015 Jonas Schnelli 6 | * 7 | * Permission is hereby granted, free of charge, to any person obtaining 8 | * a copy of this software and associated documentation files (the "Software"), 9 | * to deal in the Software without restriction, including without limitation 10 | * the rights to use, copy, modify, merge, publish, distribute, sublicense, 11 | * and/or sell copies of the Software, and to permit persons to whom the 12 | * Software is furnished to do so, subject to the following conditions: 13 | * 14 | * The above copyright notice and this permission notice shall be included 15 | * in all copies or substantial portions of the Software. 16 | * 17 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 18 | * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 19 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 20 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES 21 | * OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 22 | * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 23 | * OTHER DEALINGS IN THE SOFTWARE. 24 | */ 25 | 26 | 27 | #ifndef __LIBBTC_BIP32_H__ 28 | #define __LIBBTC_BIP32_H__ 29 | 30 | #include "btc.h" 31 | 32 | #include 33 | 34 | 35 | typedef struct { 36 | uint32_t depth; 37 | uint32_t fingerprint; 38 | uint32_t child_num; 39 | uint8_t chain_code[32]; 40 | uint8_t private_key[32]; 41 | uint8_t public_key[33]; 42 | } HDNode; 43 | 44 | 45 | #define hdnode_private_ckd_prime(X, I) hdnode_private_ckd((X), ((I) | 0x80000000)) 46 | 47 | 48 | LIBBTC_API bool hdnode_public_ckd(HDNode *inout, uint32_t i); 49 | LIBBTC_API bool hdnode_from_seed(const uint8_t *seed, int seed_len, HDNode *out); 50 | LIBBTC_API bool hdnode_private_ckd(HDNode *inout, uint32_t i); 51 | LIBBTC_API void hdnode_fill_public_key(HDNode *node); 52 | LIBBTC_API void hdnode_serialize_public(const HDNode *node, char *str, int strsize); 53 | LIBBTC_API void hdnode_serialize_private(const HDNode *node, char *str, int strsize); 54 | LIBBTC_API bool hdnode_deserialize(const char *str, HDNode *node); 55 | 56 | //!derive HDNode including private key from master private key 57 | LIBBTC_API bool hd_generate_key(HDNode *node, const char *keypath, const uint8_t *privkeymaster, 58 | const uint8_t *chaincode); 59 | 60 | #endif // __LIBBTC_BIP32_H__ 61 | -------------------------------------------------------------------------------- /src/secp256k1/src/gen_context.c: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2013, 2014, 2015 Thomas Daede, Cory Fields * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #define USE_BASIC_CONFIG 1 8 | 9 | #include "basic-config.h" 10 | #include "include/secp256k1.h" 11 | #include "field_impl.h" 12 | #include "scalar_impl.h" 13 | #include "group_impl.h" 14 | #include "ecmult_gen_impl.h" 15 | 16 | static void default_error_callback_fn(const char* str, void* data) { 17 | (void)data; 18 | fprintf(stderr, "[libsecp256k1] internal consistency check failed: %s\n", str); 19 | abort(); 20 | } 21 | 22 | static const secp256k1_callback default_error_callback = { 23 | default_error_callback_fn, 24 | NULL 25 | }; 26 | 27 | int main(int argc, char **argv) { 28 | secp256k1_ecmult_gen_context ctx; 29 | int inner; 30 | int outer; 31 | FILE* fp; 32 | 33 | (void)argc; 34 | (void)argv; 35 | 36 | fp = fopen("src/ecmult_static_context.h","w"); 37 | if (fp == NULL) { 38 | fprintf(stderr, "Could not open src/ecmult_static_context.h for writing!\n"); 39 | return -1; 40 | } 41 | 42 | fprintf(fp, "#ifndef _SECP256K1_ECMULT_STATIC_CONTEXT_\n"); 43 | fprintf(fp, "#define _SECP256K1_ECMULT_STATIC_CONTEXT_\n"); 44 | fprintf(fp, "#include \"group.h\"\n"); 45 | fprintf(fp, "#define SC SECP256K1_GE_STORAGE_CONST\n"); 46 | fprintf(fp, "static const secp256k1_ge_storage secp256k1_ecmult_static_context[64][16] = {\n"); 47 | 48 | secp256k1_ecmult_gen_context_init(&ctx); 49 | secp256k1_ecmult_gen_context_build(&ctx, &default_error_callback); 50 | for(outer = 0; outer != 64; outer++) { 51 | fprintf(fp,"{\n"); 52 | for(inner = 0; inner != 16; inner++) { 53 | fprintf(fp," SC(%uu, %uu, %uu, %uu, %uu, %uu, %uu, %uu, %uu, %uu, %uu, %uu, %uu, %uu, %uu, %uu)", SECP256K1_GE_STORAGE_CONST_GET((*ctx.prec)[outer][inner])); 54 | if (inner != 15) { 55 | fprintf(fp,",\n"); 56 | } else { 57 | fprintf(fp,"\n"); 58 | } 59 | } 60 | if (outer != 63) { 61 | fprintf(fp,"},\n"); 62 | } else { 63 | fprintf(fp,"}\n"); 64 | } 65 | } 66 | fprintf(fp,"};\n"); 67 | secp256k1_ecmult_gen_context_clear(&ctx); 68 | 69 | fprintf(fp, "#undef SC\n"); 70 | fprintf(fp, "#endif\n"); 71 | fclose(fp); 72 | 73 | return 0; 74 | } 75 | -------------------------------------------------------------------------------- /src/secp256k1/src/bench_verify.c: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2014 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #include 8 | #include 9 | 10 | #include "include/secp256k1.h" 11 | #include "util.h" 12 | #include "bench.h" 13 | 14 | typedef struct { 15 | secp256k1_context *ctx; 16 | unsigned char msg[32]; 17 | unsigned char key[32]; 18 | unsigned char sig[72]; 19 | size_t siglen; 20 | unsigned char pubkey[33]; 21 | size_t pubkeylen; 22 | } benchmark_verify_t; 23 | 24 | static void benchmark_verify(void* arg) { 25 | int i; 26 | benchmark_verify_t* data = (benchmark_verify_t*)arg; 27 | 28 | for (i = 0; i < 20000; i++) { 29 | secp256k1_pubkey pubkey; 30 | secp256k1_ecdsa_signature sig; 31 | data->sig[data->siglen - 1] ^= (i & 0xFF); 32 | data->sig[data->siglen - 2] ^= ((i >> 8) & 0xFF); 33 | data->sig[data->siglen - 3] ^= ((i >> 16) & 0xFF); 34 | CHECK(secp256k1_ec_pubkey_parse(data->ctx, &pubkey, data->pubkey, data->pubkeylen) == 1); 35 | CHECK(secp256k1_ecdsa_signature_parse_der(data->ctx, &sig, data->sig, data->siglen) == 1); 36 | CHECK(secp256k1_ecdsa_verify(data->ctx, &sig, data->msg, &pubkey) == (i == 0)); 37 | data->sig[data->siglen - 1] ^= (i & 0xFF); 38 | data->sig[data->siglen - 2] ^= ((i >> 8) & 0xFF); 39 | data->sig[data->siglen - 3] ^= ((i >> 16) & 0xFF); 40 | } 41 | } 42 | 43 | int main(void) { 44 | int i; 45 | secp256k1_pubkey pubkey; 46 | secp256k1_ecdsa_signature sig; 47 | benchmark_verify_t data; 48 | 49 | data.ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); 50 | 51 | for (i = 0; i < 32; i++) { 52 | data.msg[i] = 1 + i; 53 | } 54 | for (i = 0; i < 32; i++) { 55 | data.key[i] = 33 + i; 56 | } 57 | data.siglen = 72; 58 | CHECK(secp256k1_ecdsa_sign(data.ctx, &sig, data.msg, data.key, NULL, NULL)); 59 | CHECK(secp256k1_ecdsa_signature_serialize_der(data.ctx, data.sig, &data.siglen, &sig)); 60 | CHECK(secp256k1_ec_pubkey_create(data.ctx, &pubkey, data.key)); 61 | CHECK(secp256k1_ec_pubkey_serialize(data.ctx, data.pubkey, &data.pubkeylen, &pubkey, SECP256K1_EC_COMPRESSED) == 1); 62 | 63 | run_benchmark("ecdsa_verify", benchmark_verify, NULL, NULL, &data, 10, 20000); 64 | 65 | secp256k1_context_destroy(data.ctx); 66 | return 0; 67 | } 68 | -------------------------------------------------------------------------------- /src/secp256k1/src/bench_schnorr_verify.c: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2014 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #include 8 | #include 9 | 10 | #include "include/secp256k1.h" 11 | #include "include/secp256k1_schnorr.h" 12 | #include "util.h" 13 | #include "bench.h" 14 | 15 | typedef struct { 16 | unsigned char key[32]; 17 | unsigned char sig[64]; 18 | unsigned char pubkey[33]; 19 | size_t pubkeylen; 20 | } benchmark_schnorr_sig_t; 21 | 22 | typedef struct { 23 | secp256k1_context *ctx; 24 | unsigned char msg[32]; 25 | benchmark_schnorr_sig_t sigs[64]; 26 | int numsigs; 27 | } benchmark_schnorr_verify_t; 28 | 29 | static void benchmark_schnorr_init(void* arg) { 30 | int i, k; 31 | benchmark_schnorr_verify_t* data = (benchmark_schnorr_verify_t*)arg; 32 | 33 | for (i = 0; i < 32; i++) { 34 | data->msg[i] = 1 + i; 35 | } 36 | for (k = 0; k < data->numsigs; k++) { 37 | secp256k1_pubkey pubkey; 38 | for (i = 0; i < 32; i++) { 39 | data->sigs[k].key[i] = 33 + i + k; 40 | } 41 | secp256k1_schnorr_sign(data->ctx, data->sigs[k].sig, data->msg, data->sigs[k].key, NULL, NULL); 42 | data->sigs[k].pubkeylen = 33; 43 | CHECK(secp256k1_ec_pubkey_create(data->ctx, &pubkey, data->sigs[k].key)); 44 | CHECK(secp256k1_ec_pubkey_serialize(data->ctx, data->sigs[k].pubkey, &data->sigs[k].pubkeylen, &pubkey, SECP256K1_EC_COMPRESSED)); 45 | } 46 | } 47 | 48 | static void benchmark_schnorr_verify(void* arg) { 49 | int i; 50 | benchmark_schnorr_verify_t* data = (benchmark_schnorr_verify_t*)arg; 51 | 52 | for (i = 0; i < 20000 / data->numsigs; i++) { 53 | secp256k1_pubkey pubkey; 54 | data->sigs[0].sig[(i >> 8) % 64] ^= (i & 0xFF); 55 | CHECK(secp256k1_ec_pubkey_parse(data->ctx, &pubkey, data->sigs[0].pubkey, data->sigs[0].pubkeylen)); 56 | CHECK(secp256k1_schnorr_verify(data->ctx, data->sigs[0].sig, data->msg, &pubkey) == ((i & 0xFF) == 0)); 57 | data->sigs[0].sig[(i >> 8) % 64] ^= (i & 0xFF); 58 | } 59 | } 60 | 61 | 62 | 63 | int main(void) { 64 | benchmark_schnorr_verify_t data; 65 | 66 | data.ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); 67 | 68 | data.numsigs = 1; 69 | run_benchmark("schnorr_verify", benchmark_schnorr_verify, benchmark_schnorr_init, NULL, &data, 10, 20000); 70 | 71 | secp256k1_context_destroy(data.ctx); 72 | return 0; 73 | } 74 | -------------------------------------------------------------------------------- /include/btc/ecc.h: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | The MIT License (MIT) 4 | 5 | Copyright (c) 2015 Jonas Schnelli 6 | 7 | Permission is hereby granted, free of charge, to any person obtaining 8 | a copy of this software and associated documentation files (the "Software"), 9 | to deal in the Software without restriction, including without limitation 10 | the rights to use, copy, modify, merge, publish, distribute, sublicense, 11 | and/or sell copies of the Software, and to permit persons to whom the 12 | Software is furnished to do so, subject to the following conditions: 13 | 14 | The above copyright notice and this permission notice shall be included 15 | in all copies or substantial portions of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 18 | OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 19 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 20 | THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES 21 | OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 22 | ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 23 | OTHER DEALINGS IN THE SOFTWARE. 24 | 25 | */ 26 | 27 | #ifndef __LIBBTC_ECC_H__ 28 | #define __LIBBTC_ECC_H__ 29 | 30 | #include "btc.h" 31 | 32 | #include 33 | 34 | //!init static ecc context 35 | LIBBTC_API void ecc_start(void); 36 | 37 | //!destroys the static ecc context 38 | LIBBTC_API void ecc_stop(void); 39 | 40 | //!get public key from given private key 41 | LIBBTC_API void ecc_get_pubkey(const uint8_t *private_key, uint8_t *public_key, 42 | int public_key_len, int compressed); 43 | 44 | //!get uncompressed public key from given private key 45 | void ecc_get_public_key65(const uint8_t *private_key, uint8_t *public_key); 46 | 47 | //!get compressed public key from given private key 48 | void ecc_get_public_key33(const uint8_t *private_key, uint8_t *public_key); 49 | 50 | //!ec mul tweak on given private key 51 | LIBBTC_API bool ecc_private_key_tweak_add(uint8_t *private_key, const uint8_t *tweak); 52 | 53 | //!ec mul tweak on given public key 54 | LIBBTC_API bool ecc_public_key_tweak_add(uint8_t *public_key_inout, const uint8_t *tweak); 55 | 56 | //!verifies a given 32byte key 57 | LIBBTC_API bool ecc_verify_privatekey(const uint8_t *private_key); 58 | 59 | //!verifies a given public key (compressed[33] or uncompressed[65] bytes) 60 | LIBBTC_API bool ecc_verify_pubkey(const uint8_t *public_key, int compressed); 61 | 62 | LIBBTC_API bool ecc_sign(const uint8_t *private_key, const uint8_t *hash, unsigned char *sigder, size_t *outlen); 63 | LIBBTC_API bool ecc_verify_sig(const uint8_t *public_key, int compressed, const uint8_t *hash, unsigned char *sigder, size_t siglen); 64 | 65 | #endif //__LIBBTC_ECC_H__ 66 | -------------------------------------------------------------------------------- /src/secp256k1/src/num.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2013, 2014 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_NUM_ 8 | #define _SECP256K1_NUM_ 9 | 10 | #ifndef USE_NUM_NONE 11 | 12 | #if defined HAVE_CONFIG_H 13 | #include "libsecp256k1-config.h" 14 | #endif 15 | 16 | #if defined(USE_NUM_GMP) 17 | #include "num_gmp.h" 18 | #else 19 | #error "Please select num implementation" 20 | #endif 21 | 22 | /** Copy a number. */ 23 | static void secp256k1_num_copy(secp256k1_num *r, const secp256k1_num *a); 24 | 25 | /** Convert a number's absolute value to a binary big-endian string. 26 | * There must be enough place. */ 27 | static void secp256k1_num_get_bin(unsigned char *r, unsigned int rlen, const secp256k1_num *a); 28 | 29 | /** Set a number to the value of a binary big-endian string. */ 30 | static void secp256k1_num_set_bin(secp256k1_num *r, const unsigned char *a, unsigned int alen); 31 | 32 | /** Compute a modular inverse. The input must be less than the modulus. */ 33 | static void secp256k1_num_mod_inverse(secp256k1_num *r, const secp256k1_num *a, const secp256k1_num *m); 34 | 35 | /** Compare the absolute value of two numbers. */ 36 | static int secp256k1_num_cmp(const secp256k1_num *a, const secp256k1_num *b); 37 | 38 | /** Test whether two number are equal (including sign). */ 39 | static int secp256k1_num_eq(const secp256k1_num *a, const secp256k1_num *b); 40 | 41 | /** Add two (signed) numbers. */ 42 | static void secp256k1_num_add(secp256k1_num *r, const secp256k1_num *a, const secp256k1_num *b); 43 | 44 | /** Subtract two (signed) numbers. */ 45 | static void secp256k1_num_sub(secp256k1_num *r, const secp256k1_num *a, const secp256k1_num *b); 46 | 47 | /** Multiply two (signed) numbers. */ 48 | static void secp256k1_num_mul(secp256k1_num *r, const secp256k1_num *a, const secp256k1_num *b); 49 | 50 | /** Replace a number by its remainder modulo m. M's sign is ignored. The result is a number between 0 and m-1, 51 | even if r was negative. */ 52 | static void secp256k1_num_mod(secp256k1_num *r, const secp256k1_num *m); 53 | 54 | /** Right-shift the passed number by bits bits. */ 55 | static void secp256k1_num_shift(secp256k1_num *r, int bits); 56 | 57 | /** Check whether a number is zero. */ 58 | static int secp256k1_num_is_zero(const secp256k1_num *a); 59 | 60 | /** Check whether a number is strictly negative. */ 61 | static int secp256k1_num_is_neg(const secp256k1_num *a); 62 | 63 | /** Change a number's sign. */ 64 | static void secp256k1_num_negate(secp256k1_num *r); 65 | 66 | #endif 67 | 68 | #endif 69 | -------------------------------------------------------------------------------- /test/serialize_tests.c: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2015 Jonas Schnelli * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | #include "cstr.h" 13 | #include "serialize.h" 14 | #include "utils.h" 15 | 16 | void test_serialize() 17 | { 18 | char hex0[] = "28969cdfa74a12c82f3bad960b0b000aca2ac329deea5c2328ebc6f2ba9802c1"; 19 | char hex1[] = "28969cdfa74a12c82f3bad960b0b000aca2ac329deea5c2328ebc6f2ba9802c2"; 20 | char hex2[] = "28969cdfa74a12c82f3bad960b0b000aca2ac329deea5c2328ebc6f2ba9802c3"; 21 | uint8_t *hash0 = malloc(32); 22 | uint8_t *hash1 = malloc(32); 23 | uint8_t *hash2 = malloc(32); 24 | 25 | memcpy(hash0, utils_hex_to_uint8(hex0), 32); 26 | memcpy(hash1, utils_hex_to_uint8(hex1), 32); 27 | memcpy(hash2, utils_hex_to_uint8(hex2), 32); 28 | vector *vec = vector_new(5,free); 29 | vector_add(vec, hash0); 30 | vector_add(vec, hash1); 31 | vector_add(vec, hash2); 32 | 33 | 34 | cstring *s = cstr_new_sz(200); 35 | ser_u256_vector(s, vec); 36 | vector_free(vec, true); 37 | 38 | vector *vec2 = vector_new(0,NULL); 39 | struct const_buffer buf = { s->str, s->len }; 40 | deser_u256_vector(&vec2, &buf); 41 | 42 | vector_free(vec2, true); 43 | cstr_free(s, true); 44 | 45 | 46 | cstring *s2 = cstr_new_sz(200); 47 | ser_u16(s2,0xAAFF); 48 | ser_u32(s2,0xDDBBAAFF); 49 | ser_u64(s2,0x99FF99FFDDBBAAFF); 50 | ser_varlen(s2, 10); 51 | ser_varlen(s2, 1000); 52 | ser_varlen(s2, 100000000); 53 | ser_str(s2, "test", 4); 54 | cstring *s3 = cstr_new("foo"); 55 | ser_varstr(s2, s3); 56 | cstr_free(s3, true); 57 | // ser_varlen(s2, (uint64_t)0x9999999999999999); // uint64 varlen is not supported right now 58 | 59 | struct const_buffer buf2 = { s2->str, s2->len }; 60 | uint16_t num0; 61 | deser_u16(&num0, &buf2); 62 | assert(num0 == 43775); //0xAAFF 63 | uint32_t num1; 64 | deser_u32(&num1, &buf2); 65 | assert(num1 == 3720063743); //0xDDBBAAFF 66 | uint64_t num2; 67 | deser_u64(&num2, &buf2); 68 | assert(num2 == 0x99FF99FFDDBBAAFF); //0x99FF99FFDDBBAAFF 69 | uint32_t num3; 70 | deser_varlen(&num3, &buf2); 71 | assert(num3 == 10); 72 | deser_varlen(&num3, &buf2); 73 | assert(num3 == 1000); 74 | deser_varlen(&num3, &buf2); 75 | assert(num3 == 100000000); 76 | 77 | 78 | char strbuf[255]; 79 | deser_str(strbuf, &buf2, 255); 80 | assert(strncmp(strbuf, "test", 4) == 0); 81 | 82 | cstring *deser_test = cstr_new_sz(0); 83 | deser_varstr(&deser_test, &buf2); 84 | assert(strncmp(deser_test->str, "foo", 3) == 0); 85 | 86 | cstr_free(deser_test, true); 87 | 88 | cstr_free(s2, true); 89 | } 90 | -------------------------------------------------------------------------------- /src/secp256k1/src/modules/ecdh/tests_impl.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2015 Andrew Poelstra * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_MODULE_ECDH_TESTS_ 8 | #define _SECP256K1_MODULE_ECDH_TESTS_ 9 | 10 | void test_ecdh_generator_basepoint(void) { 11 | unsigned char s_one[32] = { 0 }; 12 | secp256k1_pubkey point[2]; 13 | int i; 14 | 15 | s_one[31] = 1; 16 | /* Check against pubkey creation when the basepoint is the generator */ 17 | for (i = 0; i < 100; ++i) { 18 | secp256k1_sha256_t sha; 19 | unsigned char s_b32[32]; 20 | unsigned char output_ecdh[32]; 21 | unsigned char output_ser[32]; 22 | unsigned char point_ser[33]; 23 | size_t point_ser_len = sizeof(point_ser); 24 | secp256k1_scalar s; 25 | 26 | random_scalar_order(&s); 27 | secp256k1_scalar_get_b32(s_b32, &s); 28 | 29 | /* compute using ECDH function */ 30 | CHECK(secp256k1_ec_pubkey_create(ctx, &point[0], s_one) == 1); 31 | CHECK(secp256k1_ecdh(ctx, output_ecdh, &point[0], s_b32) == 1); 32 | /* compute "explicitly" */ 33 | CHECK(secp256k1_ec_pubkey_create(ctx, &point[1], s_b32) == 1); 34 | CHECK(secp256k1_ec_pubkey_serialize(ctx, point_ser, &point_ser_len, &point[1], SECP256K1_EC_COMPRESSED) == 1); 35 | CHECK(point_ser_len == sizeof(point_ser)); 36 | secp256k1_sha256_initialize(&sha); 37 | secp256k1_sha256_write(&sha, point_ser, point_ser_len); 38 | secp256k1_sha256_finalize(&sha, output_ser); 39 | /* compare */ 40 | CHECK(memcmp(output_ecdh, output_ser, sizeof(output_ser)) == 0); 41 | } 42 | } 43 | 44 | void test_bad_scalar(void) { 45 | unsigned char s_zero[32] = { 0 }; 46 | unsigned char s_overflow[32] = { 47 | 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 48 | 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 49 | 0xba, 0xae, 0xdc, 0xe6, 0xaf, 0x48, 0xa0, 0x3b, 50 | 0xbf, 0xd2, 0x5e, 0x8c, 0xd0, 0x36, 0x41, 0x41 51 | }; 52 | unsigned char s_rand[32] = { 0 }; 53 | unsigned char output[32]; 54 | secp256k1_scalar rand; 55 | secp256k1_pubkey point; 56 | 57 | /* Create random point */ 58 | random_scalar_order(&rand); 59 | secp256k1_scalar_get_b32(s_rand, &rand); 60 | CHECK(secp256k1_ec_pubkey_create(ctx, &point, s_rand) == 1); 61 | 62 | /* Try to multiply it by bad values */ 63 | CHECK(secp256k1_ecdh(ctx, output, &point, s_zero) == 0); 64 | CHECK(secp256k1_ecdh(ctx, output, &point, s_overflow) == 0); 65 | /* ...and a good one */ 66 | s_overflow[31] -= 1; 67 | CHECK(secp256k1_ecdh(ctx, output, &point, s_overflow) == 1); 68 | } 69 | 70 | void run_ecdh_tests(void) { 71 | test_ecdh_generator_basepoint(); 72 | test_bad_scalar(); 73 | } 74 | 75 | #endif 76 | -------------------------------------------------------------------------------- /src/cstr.c: -------------------------------------------------------------------------------- 1 | /* Copyright 2015 BitPay, Inc. 2 | * Distributed under the MIT/X11 software license, see the accompanying 3 | * file COPYING or http://www.opensource.org/licenses/mit-license.php. 4 | */ 5 | 6 | #include "cstr.h" 7 | 8 | #include 9 | 10 | static bool cstr_alloc_min_sz(cstring *s, size_t sz) 11 | { 12 | sz++; // NUL overhead 13 | 14 | if (s->alloc && (s->alloc >= sz)) 15 | return true; 16 | 17 | unsigned int shift = 3; 18 | unsigned int al_sz; 19 | while ((al_sz = (1 << shift)) < sz) 20 | shift++; 21 | 22 | char *new_s = realloc(s->str, al_sz); 23 | if (!new_s) 24 | return false; 25 | 26 | s->str = new_s; 27 | s->alloc = al_sz; 28 | s->str[s->len] = 0; 29 | 30 | return true; 31 | } 32 | 33 | cstring *cstr_new_sz(size_t sz) 34 | { 35 | cstring *s = calloc(1, sizeof(cstring)); 36 | if (!s) 37 | return NULL; 38 | 39 | if (!cstr_alloc_min_sz(s, sz)) { 40 | free(s); 41 | return NULL; 42 | } 43 | 44 | return s; 45 | } 46 | 47 | cstring *cstr_new_buf(const void *buf, size_t sz) 48 | { 49 | cstring *s = cstr_new_sz(sz); 50 | if (!s) 51 | return NULL; 52 | 53 | memcpy(s->str, buf, sz); 54 | s->len = sz; 55 | s->str[s->len] = 0; 56 | 57 | return s; 58 | } 59 | 60 | cstring *cstr_new(const char *init_str) 61 | { 62 | if (!init_str || !*init_str) 63 | return cstr_new_sz(0); 64 | 65 | size_t slen = strlen(init_str); 66 | return cstr_new_buf(init_str, slen); 67 | } 68 | 69 | void cstr_free(cstring *s, bool free_buf) 70 | { 71 | if (!s) 72 | return; 73 | 74 | if (free_buf) 75 | free(s->str); 76 | 77 | memset(s, 0, sizeof(*s)); 78 | free(s); 79 | } 80 | 81 | bool cstr_resize(cstring *s, size_t new_sz) 82 | { 83 | // no change 84 | if (new_sz == s->len) 85 | return true; 86 | 87 | // truncate string 88 | if (new_sz <= s->len) { 89 | s->len = new_sz; 90 | s->str[s->len] = 0; 91 | return true; 92 | } 93 | 94 | // increase string size 95 | if (!cstr_alloc_min_sz(s, new_sz)) 96 | return false; 97 | 98 | // contents of string tail undefined 99 | 100 | s->len = new_sz; 101 | s->str[s->len] = 0; 102 | 103 | return true; 104 | } 105 | 106 | bool cstr_append_buf(cstring *s, const void *buf, size_t sz) 107 | { 108 | if (!cstr_alloc_min_sz(s, s->len + sz)) 109 | return false; 110 | 111 | memcpy(s->str + s->len, buf, sz); 112 | s->len += sz; 113 | s->str[s->len] = 0; 114 | 115 | return true; 116 | } 117 | 118 | bool cstr_equal(const cstring *a, const cstring *b) 119 | { 120 | if (a == b) 121 | return true; 122 | if (!a || !b) 123 | return false; 124 | if (a->len != b->len) 125 | return false; 126 | return (memcmp(a->str, b->str, a->len) == 0); 127 | } 128 | 129 | bool cstr_erase(cstring *s, size_t pos, ssize_t len) 130 | { 131 | if (pos == s->len && len == 0) 132 | return true; 133 | if (pos >= s->len) 134 | return false; 135 | 136 | ssize_t old_tail = s->len - pos; 137 | if ((len >= 0) && (len > old_tail)) 138 | return false; 139 | 140 | memmove(&s->str[pos], &s->str[pos + len], old_tail - len); 141 | s->len -= len; 142 | s->str[s->len] = 0; 143 | 144 | return true; 145 | } 146 | 147 | -------------------------------------------------------------------------------- /src/sha2.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2000-2001 Aaron D. Gifford 3 | * Copyright (c) 2013 Pavol Rusnak 4 | * Copyright (c) 2015 Jonas Schnelli 5 | * All rights reserved. 6 | * 7 | * Redistribution and use in source and binary forms, with or without 8 | * modification, are permitted provided that the following conditions 9 | * are met: 10 | * 1. Redistributions of source code must retain the above copyright 11 | * notice, this list of conditions and the following disclaimer. 12 | * 2. Redistributions in binary form must reproduce the above copyright 13 | * notice, this list of conditions and the following disclaimer in the 14 | * documentation and/or other materials provided with the distribution. 15 | * 3. Neither the name of the copyright holder nor the names of contributors 16 | * may be used to endorse or promote products derived from this software 17 | * without specific prior written permission. 18 | * 19 | * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTOR(S) ``AS IS'' AND 20 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 21 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 22 | * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTOR(S) BE LIABLE 23 | * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 24 | * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 25 | * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 26 | * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 27 | * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 28 | * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 29 | * SUCH DAMAGE. 30 | */ 31 | 32 | #ifndef __SHA2_H__ 33 | #define __SHA2_H__ 34 | 35 | #include 36 | #include 37 | 38 | #define SHA256_BLOCK_LENGTH 64 39 | #define SHA256_DIGEST_LENGTH 32 40 | #define SHA256_DIGEST_STRING_LENGTH (SHA256_DIGEST_LENGTH * 2 + 1) 41 | #define SHA512_BLOCK_LENGTH 128 42 | #define SHA512_DIGEST_LENGTH 64 43 | #define SHA512_DIGEST_STRING_LENGTH (SHA512_DIGEST_LENGTH * 2 + 1) 44 | 45 | typedef struct _SHA256_CTX { 46 | uint32_t state[8]; 47 | uint64_t bitcount; 48 | uint8_t buffer[SHA256_BLOCK_LENGTH]; 49 | } SHA256_CTX; 50 | typedef struct _SHA512_CTX { 51 | uint64_t state[8]; 52 | uint64_t bitcount[2]; 53 | uint8_t buffer[SHA512_BLOCK_LENGTH]; 54 | } SHA512_CTX; 55 | 56 | void sha256_Init(SHA256_CTX *); 57 | void sha256_Update(SHA256_CTX *, const uint8_t *, size_t); 58 | void sha256_Final(uint8_t[SHA256_DIGEST_LENGTH], SHA256_CTX *); 59 | void sha256_Raw(const uint8_t *, size_t, uint8_t[SHA256_DIGEST_LENGTH]); 60 | 61 | void sha512_Init(SHA512_CTX *); 62 | void sha512_Update(SHA512_CTX *, const uint8_t *, size_t); 63 | void sha512_Final(uint8_t[SHA512_DIGEST_LENGTH], SHA512_CTX *); 64 | void sha512_Raw(const uint8_t *, size_t, uint8_t[SHA512_DIGEST_LENGTH]); 65 | 66 | void hmac_sha256(const uint8_t *key, const uint32_t keylen, const uint8_t *msg, 67 | const uint32_t msglen, uint8_t *hmac); 68 | void hmac_sha512(const uint8_t *key, const uint32_t keylen, const uint8_t *msg, 69 | const uint32_t msglen, uint8_t *hmac); 70 | #endif 71 | -------------------------------------------------------------------------------- /src/serialize.h: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | The MIT License (MIT) 4 | 5 | Copyright (c) 2012 exMULTI, Inc. 6 | Copyright (c) 2015 Jonas Schnelli 7 | 8 | Permission is hereby granted, free of charge, to any person obtaining 9 | a copy of this software and associated documentation files (the "Software"), 10 | to deal in the Software without restriction, including without limitation 11 | the rights to use, copy, modify, merge, publish, distribute, sublicense, 12 | and/or sell copies of the Software, and to permit persons to whom the 13 | Software is furnished to do so, subject to the following conditions: 14 | 15 | The above copyright notice and this permission notice shall be included 16 | in all copies or substantial portions of the Software. 17 | 18 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 19 | OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 21 | THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES 22 | OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 23 | ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 24 | OTHER DEALINGS IN THE SOFTWARE. 25 | 26 | */ 27 | 28 | #ifndef LIBBTC_VECTOR_H__ 29 | #define LIBBTC_VECTOR_H__ 30 | 31 | #include 32 | #include 33 | 34 | #include "buffer.h" 35 | #include "cstr.h" 36 | #include "vector.h" 37 | 38 | #include "portable_endian.h" 39 | 40 | extern void ser_bytes(cstring *s, const void *p, size_t len); 41 | extern void ser_u16(cstring *s, uint16_t v_); 42 | extern void ser_u32(cstring *s, uint32_t v_); 43 | extern void ser_u64(cstring *s, uint64_t v_); 44 | 45 | static inline void ser_u256(cstring *s, const unsigned char *v_) 46 | { 47 | ser_bytes(s, v_, 32); 48 | } 49 | 50 | extern void ser_varlen(cstring *s, uint32_t vlen); 51 | extern void ser_str(cstring *s, const char *s_in, size_t maxlen); 52 | extern void ser_varstr(cstring *s, cstring *s_in); 53 | 54 | static inline void ser_s32(cstring *s, int32_t v_) 55 | { 56 | ser_u32(s, (uint32_t) v_); 57 | } 58 | 59 | static inline void ser_s64(cstring *s, int64_t v_) 60 | { 61 | ser_u64(s, (uint64_t) v_); 62 | } 63 | 64 | extern void ser_u256_vector(cstring *s, vector *vec); 65 | 66 | extern bool deser_skip(struct const_buffer *buf, size_t len); 67 | extern bool deser_bytes(void *po, struct const_buffer *buf, size_t len); 68 | extern bool deser_u16(uint16_t *vo, struct const_buffer *buf); 69 | extern bool deser_u32(uint32_t *vo, struct const_buffer *buf); 70 | extern bool deser_u64(uint64_t *vo, struct const_buffer *buf); 71 | 72 | static inline bool deser_u256(uint8_t *vo, struct const_buffer *buf) 73 | { 74 | return deser_bytes(vo, buf, 32); 75 | } 76 | 77 | extern bool deser_varlen(uint32_t *lo, struct const_buffer *buf); 78 | extern bool deser_str(char *so, struct const_buffer *buf, size_t maxlen); 79 | extern bool deser_varstr(cstring **so, struct const_buffer *buf); 80 | 81 | static inline bool deser_s64(int64_t *vo, struct const_buffer *buf) 82 | { 83 | return deser_u64((uint64_t *) vo, buf); 84 | } 85 | 86 | extern bool deser_u256_vector(vector **vo, struct const_buffer *buf); 87 | 88 | //extern void u256_from_compact(BIGNUM *vo, uint32_t c); 89 | 90 | #endif /* LIBBTC_VECTOR_H__ */ 91 | -------------------------------------------------------------------------------- /src/ecc_key.c: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | The MIT License (MIT) 4 | 5 | Copyright (c) 2015 Jonas Schnelli 6 | 7 | Permission is hereby granted, free of charge, to any person obtaining 8 | a copy of this software and associated documentation files (the "Software"), 9 | to deal in the Software without restriction, including without limitation 10 | the rights to use, copy, modify, merge, publish, distribute, sublicense, 11 | and/or sell copies of the Software, and to permit persons to whom the 12 | Software is furnished to do so, subject to the following conditions: 13 | 14 | The above copyright notice and this permission notice shall be included 15 | in all copies or substantial portions of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 18 | OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 19 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 20 | THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES 21 | OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 22 | ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 23 | OTHER DEALINGS IN THE SOFTWARE. 24 | 25 | */ 26 | 27 | #include "btc/ecc_key.h" 28 | 29 | #include 30 | #include 31 | #include 32 | #include 33 | 34 | #include "btc/ecc.h" 35 | 36 | #include "random.h" 37 | #include "utils.h" 38 | 39 | 40 | btc_key* btc_privkey_new() 41 | { 42 | btc_key *privkey = calloc(1, sizeof(*privkey)); 43 | memset(&privkey->privkey, 0, BTC_ECKEY_PKEY_LENGTH); 44 | 45 | do 46 | { 47 | random_bytes(privkey->privkey, BTC_ECKEY_PKEY_LENGTH, 0); 48 | } while(ecc_verify_privatekey(privkey->privkey) == 0); 49 | 50 | return privkey; 51 | } 52 | 53 | void btc_privkey_gen(btc_key *privkey) 54 | { 55 | do 56 | { 57 | random_bytes(privkey->privkey, BTC_ECKEY_PKEY_LENGTH, 0); 58 | } while(ecc_verify_privatekey(privkey->privkey) == 0); 59 | } 60 | 61 | 62 | void btc_privkey_free(btc_key *privkey) 63 | { 64 | memset(privkey->privkey, 0, BTC_ECKEY_PKEY_LENGTH); 65 | free(privkey); 66 | } 67 | 68 | 69 | btc_pubkey* btc_pubkey_new() 70 | { 71 | btc_pubkey *pubkey = calloc(1, sizeof(*pubkey)); 72 | memset(pubkey->pubkey, 0, BTC_ECKEY_UNCOMPRESSED_LENGTH); 73 | pubkey->compressed = false; 74 | 75 | return pubkey; 76 | } 77 | 78 | 79 | void btc_pubkey_free(btc_pubkey* pubkey) 80 | { 81 | memset(pubkey->pubkey, 0, BTC_ECKEY_UNCOMPRESSED_LENGTH); 82 | free(pubkey); 83 | } 84 | 85 | 86 | void btc_pubkey_from_key(btc_key *privkey, btc_pubkey* pubkey_inout) 87 | { 88 | ecc_get_pubkey(privkey->privkey, pubkey_inout->pubkey, BTC_ECKEY_PKEY_LENGTH, true); 89 | pubkey_inout->compressed = true; 90 | } 91 | 92 | 93 | bool btc_key_sign_hash(const btc_key *privkey, const uint8_t *hash, unsigned char *sigout, int *outlen) 94 | { 95 | return ecc_sign(privkey->privkey, hash, sigout, (size_t *)outlen); 96 | } 97 | 98 | 99 | bool btc_pubkey_verify_sig(const btc_pubkey *pubkey, const uint8_t *hash, unsigned char *sigder, int len) 100 | { 101 | return ecc_verify_sig(pubkey->pubkey, pubkey->compressed, hash, sigder, len); 102 | } 103 | -------------------------------------------------------------------------------- /src/secp256k1/README.md: -------------------------------------------------------------------------------- 1 | libsecp256k1 2 | ============ 3 | 4 | [![Build Status](https://travis-ci.org/bitcoin/secp256k1.svg?branch=master)](https://travis-ci.org/bitcoin/secp256k1) 5 | 6 | Optimized C library for EC operations on curve secp256k1. 7 | 8 | This library is a work in progress and is being used to research best practices. Use at your own risk. 9 | 10 | Features: 11 | * secp256k1 ECDSA signing/verification and key generation. 12 | * Adding/multiplying private/public keys. 13 | * Serialization/parsing of private keys, public keys, signatures. 14 | * Constant time, constant memory access signing and pubkey generation. 15 | * Derandomized DSA (via RFC6979 or with a caller provided function.) 16 | * Very efficient implementation. 17 | 18 | Implementation details 19 | ---------------------- 20 | 21 | * General 22 | * No runtime heap allocation. 23 | * Extensive testing infrastructure. 24 | * Structured to facilitate review and analysis. 25 | * Intended to be portable to any system with a C89 compiler and uint64_t support. 26 | * Expose only higher level interfaces to minimize the API surface and improve application security. ("Be difficult to use insecurely.") 27 | * Field operations 28 | * Optimized implementation of arithmetic modulo the curve's field size (2^256 - 0x1000003D1). 29 | * Using 5 52-bit limbs (including hand-optimized assembly for x86_64, by Diederik Huys). 30 | * Using 10 26-bit limbs. 31 | * Field inverses and square roots using a sliding window over blocks of 1s (by Peter Dettman). 32 | * Scalar operations 33 | * Optimized implementation without data-dependent branches of arithmetic modulo the curve's order. 34 | * Using 4 64-bit limbs (relying on __int128 support in the compiler). 35 | * Using 8 32-bit limbs. 36 | * Group operations 37 | * Point addition formula specifically simplified for the curve equation (y^2 = x^3 + 7). 38 | * Use addition between points in Jacobian and affine coordinates where possible. 39 | * Use a unified addition/doubling formula where necessary to avoid data-dependent branches. 40 | * Point/x comparison without a field inversion by comparison in the Jacobian coordinate space. 41 | * Point multiplication for verification (a*P + b*G). 42 | * Use wNAF notation for point multiplicands. 43 | * Use a much larger window for multiples of G, using precomputed multiples. 44 | * Use Shamir's trick to do the multiplication with the public key and the generator simultaneously. 45 | * Optionally (off by default) use secp256k1's efficiently-computable endomorphism to split the P multiplicand into 2 half-sized ones. 46 | * Point multiplication for signing 47 | * Use a precomputed table of multiples of powers of 16 multiplied with the generator, so general multiplication becomes a series of additions. 48 | * Access the table with branch-free conditional moves so memory access is uniform. 49 | * No data-dependent branches 50 | * The precomputed tables add and eventually subtract points for which no known scalar (private key) is known, preventing even an attacker with control over the private key used to control the data internally. 51 | 52 | Build steps 53 | ----------- 54 | 55 | libsecp256k1 is built using autotools: 56 | 57 | $ ./autogen.sh 58 | $ ./configure 59 | $ make 60 | $ ./tests 61 | $ sudo make install # optional 62 | -------------------------------------------------------------------------------- /configure.ac: -------------------------------------------------------------------------------- 1 | dnl require autoconf 2.68 (AS_ECHO/AS_ECHO_N) 2 | AC_PREREQ([2.68]) 3 | AC_INIT([libbtc],[0.1],[https://github.com/jonasschnelli/libbtc/issues],[libbtc]) 4 | AC_CONFIG_HEADERS([src/libbtc-config.h]) 5 | AC_CONFIG_AUX_DIR([build-aux]) 6 | AC_CONFIG_MACRO_DIR([build-aux/m4]) 7 | AC_CANONICAL_HOST 8 | AH_TOP([#ifndef LIBBTC_CONFIG_H]) 9 | AH_TOP([#define LIBBTC_CONFIG_H]) 10 | AH_BOTTOM([#endif /*LIBBTC_CONFIG_H*/]) 11 | AM_INIT_AUTOMAKE([no-define subdir-objects foreign]) 12 | AC_HEADER_STDBOOL 13 | LT_INIT 14 | 15 | PKG_PROG_PKG_CONFIG 16 | AC_PATH_TOOL(AR, ar) 17 | AC_PATH_TOOL(RANLIB, ranlib) 18 | AC_PATH_TOOL(STRIP, strip) 19 | AM_PROG_CC_C_O 20 | AC_PROG_CC_C99 21 | 22 | CFLAGS="$CFLAGS -W" 23 | 24 | warn_CFLAGS="-std=gnu99 -pedantic -Wno-unused-function -Wno-long-long -Wno-overlength-strings" 25 | saved_CFLAGS="$CFLAGS" 26 | CFLAGS="$CFLAGS $warn_CFLAGS" 27 | AC_MSG_CHECKING([if ${CC} supports ${warn_CFLAGS}]) 28 | AC_COMPILE_IFELSE([AC_LANG_SOURCE([[char foo;]])], 29 | [ AC_MSG_RESULT([yes]) ], 30 | [ AC_MSG_RESULT([no]) 31 | CFLAGS="$saved_CFLAGS" 32 | ]) 33 | 34 | # Enable debug 35 | AC_ARG_ENABLE([debug], 36 | [AS_HELP_STRING([--enable-debug], 37 | [use debug compiler flags and macros (default is no)])], 38 | [enable_debug=$enableval], 39 | [enable_debug=no]) 40 | 41 | if test "x$enable_debug" = xyes; then 42 | CFLAGS="$CFLAGS -g3 -O0 -DDEBUG" 43 | CXXFLAGS="$CXXFLAGS -g3 -O0 -DDEBUG" 44 | AC_DEFINE_UNQUOTED([ENABLE_DEBUG],[1],[Define to 1 to enable debung output]) 45 | fi 46 | 47 | # check for bool type 48 | AC_CHECK_TYPE([bool],[ 49 | AC_DEFINE(HAVE_BOOL_T, 1, 50 | [Define to 1 if bool is an available type.]) 51 | ], ,[ 52 | #ifdef HAVE_SYS_TYPES_H 53 | #include 54 | #endif 55 | #ifdef HAVE_STDBOOL_H 56 | #include 57 | #endif 58 | ]) 59 | 60 | AC_ARG_ENABLE(tests, 61 | AS_HELP_STRING([--enable-tests],[compile tests (default is yes)]), 62 | [use_tests=$enableval], 63 | [use_tests=yes]) 64 | 65 | AC_MSG_CHECKING([for __builtin_expect]) 66 | AC_COMPILE_IFELSE([AC_LANG_SOURCE([[void myfunc() {__builtin_expect(0,0);}]])], 67 | [ AC_MSG_RESULT([yes]);AC_DEFINE(HAVE_BUILTIN_EXPECT,1,[Define this symbol if __builtin_expect is available]) ], 68 | [ AC_MSG_RESULT([no]) 69 | ]) 70 | 71 | m4_include(m4/macros/with.m4) 72 | ARG_WITH_SET([random-device], [/dev/urandom], [set the device to read random data from]) 73 | if test "x$random_device" = x"/dev/urandom"; then 74 | AC_DEFINE_UNQUOTED([FILE_RANDOM],[1],[Define to 1 to enable random retrieving over filehandle]) 75 | AC_DEFINE([RANDOM_DEVICE],["/dev/urandom"],[Define to set random file handle]) 76 | fi 77 | if test "x$random_device" = x"/dev/random"; then 78 | AC_DEFINE_UNQUOTED([FILE_RANDOM],[1],[Define to 1 to enable /dev/random as random device]) 79 | AC_DEFINE([RANDOM_DEVICE],["/dev/random"],[Define to set random file handle]) 80 | fi 81 | 82 | AC_CONFIG_FILES([Makefile libbtc.pc]) 83 | AC_SUBST(LIBTOOL_APP_LDFLAGS) 84 | AC_SUBST(BUILD_EXEEXT) 85 | AM_CONDITIONAL([USE_TESTS], [test x"$use_tests" != x"no"]) 86 | 87 | AC_CONFIG_SUBDIRS([src/secp256k1]) 88 | 89 | dnl make sure nothing new is exported so that we don't break the cache 90 | PKGCONFIG_PATH_TEMP="$PKG_CONFIG_PATH" 91 | unset PKG_CONFIG_PATH 92 | PKG_CONFIG_PATH="$PKGCONFIG_PATH_TEMP" 93 | 94 | AC_OUTPUT 95 | -------------------------------------------------------------------------------- /src/secp256k1/src/util.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2013, 2014 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_UTIL_H_ 8 | #define _SECP256K1_UTIL_H_ 9 | 10 | #if defined HAVE_CONFIG_H 11 | #include "libsecp256k1-config.h" 12 | #endif 13 | 14 | #include 15 | #include 16 | #include 17 | 18 | typedef struct { 19 | void (*fn)(const char *text, void* data); 20 | const void* data; 21 | } secp256k1_callback; 22 | 23 | static SECP256K1_INLINE void secp256k1_callback_call(const secp256k1_callback * const cb, const char * const text) { 24 | cb->fn(text, (void*)cb->data); 25 | } 26 | 27 | #ifdef DETERMINISTIC 28 | #define TEST_FAILURE(msg) do { \ 29 | fprintf(stderr, "%s\n", msg); \ 30 | abort(); \ 31 | } while(0); 32 | #else 33 | #define TEST_FAILURE(msg) do { \ 34 | fprintf(stderr, "%s:%d: %s\n", __FILE__, __LINE__, msg); \ 35 | abort(); \ 36 | } while(0) 37 | #endif 38 | 39 | #ifdef HAVE_BUILTIN_EXPECT 40 | #define EXPECT(x,c) __builtin_expect((x),(c)) 41 | #else 42 | #define EXPECT(x,c) (x) 43 | #endif 44 | 45 | #ifdef DETERMINISTIC 46 | #define CHECK(cond) do { \ 47 | if (EXPECT(!(cond), 0)) { \ 48 | TEST_FAILURE("test condition failed"); \ 49 | } \ 50 | } while(0) 51 | #else 52 | #define CHECK(cond) do { \ 53 | if (EXPECT(!(cond), 0)) { \ 54 | TEST_FAILURE("test condition failed: " #cond); \ 55 | } \ 56 | } while(0) 57 | #endif 58 | 59 | /* Like assert(), but when VERIFY is defined, and side-effect safe. */ 60 | #ifdef VERIFY 61 | #define VERIFY_CHECK CHECK 62 | #define VERIFY_SETUP(stmt) do { stmt; } while(0) 63 | #else 64 | #define VERIFY_CHECK(cond) do { (void)(cond); } while(0) 65 | #define VERIFY_SETUP(stmt) 66 | #endif 67 | 68 | static SECP256K1_INLINE void *checked_malloc(const secp256k1_callback* cb, size_t size) { 69 | void *ret = malloc(size); 70 | if (ret == NULL) { 71 | secp256k1_callback_call(cb, "Out of memory"); 72 | } 73 | return ret; 74 | } 75 | 76 | /* Macro for restrict, when available and not in a VERIFY build. */ 77 | #if defined(SECP256K1_BUILD) && defined(VERIFY) 78 | # define SECP256K1_RESTRICT 79 | #else 80 | # if (!defined(__STDC_VERSION__) || (__STDC_VERSION__ < 199901L) ) 81 | # if SECP256K1_GNUC_PREREQ(3,0) 82 | # define SECP256K1_RESTRICT __restrict__ 83 | # elif (defined(_MSC_VER) && _MSC_VER >= 1400) 84 | # define SECP256K1_RESTRICT __restrict 85 | # else 86 | # define SECP256K1_RESTRICT 87 | # endif 88 | # else 89 | # define SECP256K1_RESTRICT restrict 90 | # endif 91 | #endif 92 | 93 | #if defined(_WIN32) 94 | # define I64FORMAT "I64d" 95 | # define I64uFORMAT "I64u" 96 | #else 97 | # define I64FORMAT "lld" 98 | # define I64uFORMAT "llu" 99 | #endif 100 | 101 | #if defined(HAVE___INT128) 102 | # if defined(__GNUC__) 103 | # define SECP256K1_GNUC_EXT __extension__ 104 | # else 105 | # define SECP256K1_GNUC_EXT 106 | # endif 107 | SECP256K1_GNUC_EXT typedef unsigned __int128 uint128_t; 108 | #endif 109 | 110 | #endif 111 | -------------------------------------------------------------------------------- /include/btc/tx.h: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | The MIT License (MIT) 4 | 5 | Copyright (c) 2015 Jonas Schnelli 6 | 7 | Permission is hereby granted, free of charge, to any person obtaining 8 | a copy of this software and associated documentation files (the "Software"), 9 | to deal in the Software without restriction, including without limitation 10 | the rights to use, copy, modify, merge, publish, distribute, sublicense, 11 | and/or sell copies of the Software, and to permit persons to whom the 12 | Software is furnished to do so, subject to the following conditions: 13 | 14 | The above copyright notice and this permission notice shall be included 15 | in all copies or substantial portions of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 18 | OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 19 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 20 | THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES 21 | OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 22 | ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 23 | OTHER DEALINGS IN THE SOFTWARE. 24 | 25 | */ 26 | 27 | 28 | #ifndef __LIBBTC_TX_H__ 29 | #define __LIBBTC_TX_H__ 30 | 31 | #include "btc.h" 32 | 33 | #include 34 | #include 35 | #include 36 | 37 | #include "cstr.h" 38 | #include "vector.h" 39 | 40 | typedef uint8_t uint256[32]; 41 | 42 | 43 | typedef struct btc_script_ 44 | { 45 | int* data; 46 | size_t limit; // Total size of the vector 47 | size_t current; //Number of vectors in it at present 48 | } btc_script; 49 | 50 | typedef struct btc_tx_outpoint_ 51 | { 52 | uint256 hash; 53 | uint32_t n; 54 | } btc_tx_outpoint; 55 | 56 | typedef struct btc_tx_in_ 57 | { 58 | btc_tx_outpoint prevout; 59 | cstring *script_sig; 60 | uint32_t sequence; 61 | } btc_tx_in; 62 | 63 | typedef struct btc_tx_out_ 64 | { 65 | int64_t value; 66 | cstring *script_pubkey; 67 | } btc_tx_out; 68 | 69 | typedef struct btc_tx_ 70 | { 71 | uint32_t version; 72 | vector *vin; 73 | vector *vout; 74 | uint32_t locktime; 75 | } btc_tx; 76 | 77 | 78 | //!create a new tx input 79 | LIBBTC_API btc_tx_in* btc_tx_in_new(); 80 | LIBBTC_API void btc_tx_in_free(btc_tx_in *tx_in); 81 | LIBBTC_API void btc_tx_in_copy(btc_tx_in *dest, const btc_tx_in *src); 82 | 83 | //!create a new tx output 84 | LIBBTC_API btc_tx_out* btc_tx_out_new(); 85 | LIBBTC_API void btc_tx_out_free(btc_tx_out *tx_out); 86 | LIBBTC_API void btc_tx_out_copy(btc_tx_out *dest, const btc_tx_out *src); 87 | 88 | //!create a new tx input 89 | LIBBTC_API btc_tx* btc_tx_new(); 90 | LIBBTC_API void btc_tx_free(btc_tx *tx); 91 | LIBBTC_API void btc_tx_copy(btc_tx *dest, const btc_tx *src); 92 | 93 | //!deserialize/parse a p2p serialized bitcoin transaction 94 | LIBBTC_API int btc_tx_deserialize(const unsigned char *tx_serialized, size_t inlen, btc_tx *tx); 95 | 96 | //!serialize a lbc bitcoin data structure into a p2p serialized buffer 97 | LIBBTC_API void btc_tx_serialize(cstring *s, const btc_tx *tx); 98 | 99 | LIBBTC_API bool btc_tx_sighash(const btc_tx *tx_to, const cstring *fromPubKey, unsigned int in_num, int hashtype, uint8_t *hash); 100 | 101 | #endif //__LIBBTC_TX_H__ 102 | -------------------------------------------------------------------------------- /test/vector_tests.c: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2015 Jonas Schnelli * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | #include "utils.h" 14 | #include "vector.h" 15 | 16 | struct teststruct { 17 | void *dummy1; 18 | void *dummy2; 19 | }; 20 | 21 | void free_dummy(void *data) 22 | { 23 | free(((struct teststruct *)data)->dummy1); 24 | free(((struct teststruct *)data)->dummy2); 25 | free((struct teststruct *)data); 26 | } 27 | 28 | void test_vector() 29 | { 30 | bool res; 31 | char str0[] = "string"; 32 | char str1[] = "rumba"; 33 | 34 | vector *vec = vector_new(10, NULL); 35 | assert(vec != NULL); 36 | assert(vec->len == 0); 37 | assert(vec->alloc > 0); 38 | 39 | res = vector_add(vec, str0); 40 | assert(res == true); 41 | assert(vec->len == 1); 42 | 43 | res = vector_add(vec, str1); 44 | assert(res == true); 45 | assert(vec->len == 2); 46 | 47 | assert(vector_find(vec, str0) == 0); 48 | assert(vector_find(vec, "test") == -1); 49 | assert(vector_find(vec, str1) == 1); 50 | 51 | assert(strcmp(vector_idx(vec, 0), "string") == 0); 52 | assert(strcmp(vector_idx(vec, 1), "rumba") == 0); 53 | 54 | vector_remove_idx(vec,0); 55 | assert(res == true); 56 | assert(strcmp(vector_idx(vec, 0), "rumba") == 0); 57 | 58 | vector_free(vec, true); 59 | 60 | vec = vector_new(10, free); 61 | res = vector_add(vec, strdup("TEST0")); assert(res == true); 62 | res = vector_add(vec, strdup("TEST1")); assert(res == true); 63 | 64 | char *a_str = strdup("TEST2"); 65 | res = vector_add(vec, a_str); assert(res == true); 66 | assert(vec->len == 3); 67 | res = vector_remove(vec, a_str); assert(res == true); 68 | assert(vec->len == 2); 69 | vector_free(vec, true); 70 | 71 | 72 | /* test resize */ 73 | vec = vector_new(1, free); 74 | res = vector_resize(vec, 30); assert(res == true); 75 | res = vector_resize(vec, 30); assert(res == true); 76 | char str[80]; 77 | int i; 78 | for (i=0;i<20;i++) 79 | { 80 | sprintf(str, "TEST%d", i); 81 | res = vector_add(vec, strdup(str)); assert(res == true); 82 | assert(vec->len == (size_t)i+1); 83 | } 84 | 85 | res = vector_resize(vec, 5); assert(res == true); 86 | assert(strcmp(vector_idx(vec, 0), "TEST0") == 0); 87 | assert(strcmp(vector_idx(vec, 4), "TEST4") == 0); 88 | assert(vector_idx(vec, 5) == NULL); 89 | 90 | vector_remove_range(vec, 0, 4); 91 | assert(strcmp(vector_idx(vec, 0), "TEST4") == 0); 92 | vector_free(vec, true); 93 | 94 | 95 | /* test custom free callback handler */ 96 | struct teststruct *some_data = calloc(1,sizeof(struct teststruct)); 97 | some_data->dummy1 = calloc(1,10); 98 | some_data->dummy2 = calloc(1,10); 99 | 100 | vec = vector_new(1, free_dummy); 101 | vector_add(vec, some_data); 102 | vector_free(vec, true); 103 | } 104 | -------------------------------------------------------------------------------- /src/portable_endian.h: -------------------------------------------------------------------------------- 1 | // "License": Public Domain 2 | // I, Mathias Panzenböck, place this file hereby into the public domain. Use it at your own risk for whatever you like. 3 | // In case there are jurisdictions that don't support putting things in the public domain you can also consider it to 4 | // be "dual licensed" under the BSD, MIT and Apache licenses, if you want to. This code is trivial anyway. Consider it 5 | // an example on how to get the endian conversion functions on different platforms. 6 | 7 | #ifndef PORTABLE_ENDIAN_H__ 8 | #define PORTABLE_ENDIAN_H__ 9 | 10 | #if (defined(_WIN16) || defined(_WIN32) || defined(_WIN64)) && !defined(__WINDOWS__) 11 | 12 | # define __WINDOWS__ 13 | 14 | #endif 15 | 16 | #if defined(__linux__) || defined(__CYGWIN__) 17 | 18 | # include 19 | 20 | #elif defined(__APPLE__) 21 | 22 | # include 23 | 24 | # define htobe16(x) OSSwapHostToBigInt16(x) 25 | # define htole16(x) OSSwapHostToLittleInt16(x) 26 | # define be16toh(x) OSSwapBigToHostInt16(x) 27 | # define le16toh(x) OSSwapLittleToHostInt16(x) 28 | 29 | # define htobe32(x) OSSwapHostToBigInt32(x) 30 | # define htole32(x) OSSwapHostToLittleInt32(x) 31 | # define be32toh(x) OSSwapBigToHostInt32(x) 32 | # define le32toh(x) OSSwapLittleToHostInt32(x) 33 | 34 | # define htobe64(x) OSSwapHostToBigInt64(x) 35 | # define htole64(x) OSSwapHostToLittleInt64(x) 36 | # define be64toh(x) OSSwapBigToHostInt64(x) 37 | # define le64toh(x) OSSwapLittleToHostInt64(x) 38 | 39 | # define __BYTE_ORDER BYTE_ORDER 40 | # define __BIG_ENDIAN BIG_ENDIAN 41 | # define __LITTLE_ENDIAN LITTLE_ENDIAN 42 | # define __PDP_ENDIAN PDP_ENDIAN 43 | 44 | #elif defined(__OpenBSD__) 45 | 46 | # include 47 | 48 | #elif defined(__NetBSD__) || defined(__FreeBSD__) || defined(__DragonFly__) 49 | 50 | # include 51 | 52 | # define be16toh(x) betoh16(x) 53 | # define le16toh(x) letoh16(x) 54 | 55 | # define be32toh(x) betoh32(x) 56 | # define le32toh(x) letoh32(x) 57 | 58 | # define be64toh(x) betoh64(x) 59 | # define le64toh(x) letoh64(x) 60 | 61 | #elif defined(__WINDOWS__) 62 | 63 | # include 64 | # include 65 | 66 | # if BYTE_ORDER == LITTLE_ENDIAN 67 | 68 | # define htobe16(x) htons(x) 69 | # define htole16(x) (x) 70 | # define be16toh(x) ntohs(x) 71 | # define le16toh(x) (x) 72 | 73 | # define htobe32(x) htonl(x) 74 | # define htole32(x) (x) 75 | # define be32toh(x) ntohl(x) 76 | # define le32toh(x) (x) 77 | 78 | # define htobe64(x) htonll(x) 79 | # define htole64(x) (x) 80 | # define be64toh(x) ntohll(x) 81 | # define le64toh(x) (x) 82 | 83 | # elif BYTE_ORDER == BIG_ENDIAN 84 | 85 | /* that would be xbox 360 */ 86 | # define htobe16(x) (x) 87 | # define htole16(x) __builtin_bswap16(x) 88 | # define be16toh(x) (x) 89 | # define le16toh(x) __builtin_bswap16(x) 90 | 91 | # define htobe32(x) (x) 92 | # define htole32(x) __builtin_bswap32(x) 93 | # define be32toh(x) (x) 94 | # define le32toh(x) __builtin_bswap32(x) 95 | 96 | # define htobe64(x) (x) 97 | # define htole64(x) __builtin_bswap64(x) 98 | # define be64toh(x) (x) 99 | # define le64toh(x) __builtin_bswap64(x) 100 | 101 | # else 102 | 103 | # error byte order not supported 104 | 105 | # endif 106 | 107 | # define __BYTE_ORDER BYTE_ORDER 108 | # define __BIG_ENDIAN BIG_ENDIAN 109 | # define __LITTLE_ENDIAN LITTLE_ENDIAN 110 | # define __PDP_ENDIAN PDP_ENDIAN 111 | 112 | #else 113 | 114 | # error platform not supported 115 | 116 | #endif 117 | 118 | #endif 119 | -------------------------------------------------------------------------------- /src/secp256k1/Makefile.am: -------------------------------------------------------------------------------- 1 | ACLOCAL_AMFLAGS = -I build-aux/m4 2 | 3 | lib_LTLIBRARIES = libsecp256k1.la 4 | include_HEADERS = include/secp256k1.h 5 | noinst_HEADERS = 6 | noinst_HEADERS += src/scalar.h 7 | noinst_HEADERS += src/scalar_4x64.h 8 | noinst_HEADERS += src/scalar_8x32.h 9 | noinst_HEADERS += src/scalar_impl.h 10 | noinst_HEADERS += src/scalar_4x64_impl.h 11 | noinst_HEADERS += src/scalar_8x32_impl.h 12 | noinst_HEADERS += src/group.h 13 | noinst_HEADERS += src/group_impl.h 14 | noinst_HEADERS += src/num_gmp.h 15 | noinst_HEADERS += src/num_gmp_impl.h 16 | noinst_HEADERS += src/ecdsa.h 17 | noinst_HEADERS += src/ecdsa_impl.h 18 | noinst_HEADERS += src/eckey.h 19 | noinst_HEADERS += src/eckey_impl.h 20 | noinst_HEADERS += src/ecmult.h 21 | noinst_HEADERS += src/ecmult_impl.h 22 | noinst_HEADERS += src/ecmult_const.h 23 | noinst_HEADERS += src/ecmult_const_impl.h 24 | noinst_HEADERS += src/ecmult_gen.h 25 | noinst_HEADERS += src/ecmult_gen_impl.h 26 | noinst_HEADERS += src/num.h 27 | noinst_HEADERS += src/num_impl.h 28 | noinst_HEADERS += src/field_10x26.h 29 | noinst_HEADERS += src/field_10x26_impl.h 30 | noinst_HEADERS += src/field_5x52.h 31 | noinst_HEADERS += src/field_5x52_impl.h 32 | noinst_HEADERS += src/field_5x52_int128_impl.h 33 | noinst_HEADERS += src/field_5x52_asm_impl.h 34 | noinst_HEADERS += src/java/org_bitcoin_NativeSecp256k1.h 35 | noinst_HEADERS += src/util.h 36 | noinst_HEADERS += src/testrand.h 37 | noinst_HEADERS += src/testrand_impl.h 38 | noinst_HEADERS += src/hash.h 39 | noinst_HEADERS += src/hash_impl.h 40 | noinst_HEADERS += src/field.h 41 | noinst_HEADERS += src/field_impl.h 42 | noinst_HEADERS += src/bench.h 43 | 44 | pkgconfigdir = $(libdir)/pkgconfig 45 | pkgconfig_DATA = libsecp256k1.pc 46 | 47 | libsecp256k1_la_SOURCES = src/secp256k1.c 48 | libsecp256k1_la_CPPFLAGS = -I$(top_srcdir)/include -I$(top_srcdir)/src $(SECP_INCLUDES) 49 | libsecp256k1_la_LIBADD = $(SECP_LIBS) 50 | 51 | 52 | noinst_PROGRAMS = 53 | if USE_BENCHMARK 54 | noinst_PROGRAMS += bench_verify bench_sign bench_internal 55 | bench_verify_SOURCES = src/bench_verify.c 56 | bench_verify_LDADD = libsecp256k1.la $(SECP_LIBS) 57 | bench_sign_SOURCES = src/bench_sign.c 58 | bench_sign_LDADD = libsecp256k1.la $(SECP_LIBS) 59 | bench_internal_SOURCES = src/bench_internal.c 60 | bench_internal_LDADD = $(SECP_LIBS) 61 | bench_internal_CPPFLAGS = $(SECP_INCLUDES) 62 | endif 63 | 64 | if USE_TESTS 65 | noinst_PROGRAMS += tests 66 | tests_SOURCES = src/tests.c 67 | tests_CPPFLAGS = -DVERIFY -I$(top_srcdir)/src $(SECP_INCLUDES) $(SECP_TEST_INCLUDES) 68 | tests_LDADD = $(SECP_LIBS) $(SECP_TEST_LIBS) 69 | tests_LDFLAGS = -static 70 | TESTS = tests 71 | endif 72 | 73 | if USE_ECMULT_STATIC_PRECOMPUTATION 74 | CPPFLAGS_FOR_BUILD +=-I$(top_srcdir)/ 75 | CFLAGS_FOR_BUILD += -Wall -Wextra -Wno-unused-function 76 | 77 | gen_context_OBJECTS = gen_context.o 78 | gen_context_BIN = gen_context$(BUILD_EXEEXT) 79 | gen_%.o: src/gen_%.c 80 | $(CC_FOR_BUILD) $(CPPFLAGS_FOR_BUILD) $(CFLAGS_FOR_BUILD) -c $< -o $@ 81 | 82 | $(gen_context_BIN): $(gen_context_OBJECTS) 83 | $(CC_FOR_BUILD) $^ -o $@ 84 | 85 | $(libsecp256k1_la_OBJECTS): src/ecmult_static_context.h 86 | $(tests_OBJECTS): src/ecmult_static_context.h 87 | $(bench_internal_OBJECTS): src/ecmult_static_context.h 88 | 89 | src/ecmult_static_context.h: $(gen_context_BIN) 90 | ./$(gen_context_BIN) 91 | 92 | CLEANFILES = $(gen_context_BIN) src/ecmult_static_context.h 93 | endif 94 | 95 | EXTRA_DIST = autogen.sh src/gen_context.c src/basic-config.h 96 | 97 | if ENABLE_MODULE_ECDH 98 | include src/modules/ecdh/Makefile.am.include 99 | endif 100 | 101 | if ENABLE_MODULE_SCHNORR 102 | include src/modules/schnorr/Makefile.am.include 103 | endif 104 | 105 | if ENABLE_MODULE_RECOVERY 106 | include src/modules/recovery/Makefile.am.include 107 | endif 108 | -------------------------------------------------------------------------------- /src/ecc_libsecp256k1.c: -------------------------------------------------------------------------------- 1 | #include "secp256k1/include/secp256k1.h" 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | #include "btc/btc.h" 8 | 9 | #include "random.h" 10 | 11 | static secp256k1_context* secp256k1_ctx = NULL; 12 | 13 | void ecc_start(void) 14 | { 15 | secp256k1_ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); 16 | assert(secp256k1_ctx != NULL); 17 | 18 | uint8_t seed[32]; 19 | random_bytes(seed, 32, 0); 20 | int ret = secp256k1_context_randomize(secp256k1_ctx, seed); 21 | assert(ret); 22 | } 23 | 24 | 25 | void ecc_stop(void) 26 | { 27 | secp256k1_context *ctx = secp256k1_ctx; 28 | secp256k1_ctx = NULL; 29 | 30 | if (ctx) { 31 | secp256k1_context_destroy(ctx); 32 | } 33 | } 34 | 35 | 36 | void ecc_get_pubkey(const uint8_t *private_key, uint8_t *public_key, 37 | int public_key_len, int compressed) 38 | { 39 | secp256k1_pubkey pubkey; 40 | assert(secp256k1_ctx); 41 | 42 | memset(public_key, 0, public_key_len); 43 | 44 | if (!secp256k1_ec_pubkey_create(secp256k1_ctx, &pubkey, (const unsigned char *)private_key)) { 45 | return; 46 | } 47 | 48 | if (!secp256k1_ec_pubkey_serialize(secp256k1_ctx, public_key, (size_t *)&public_key_len, &pubkey, 49 | compressed)) { 50 | return; 51 | } 52 | 53 | return; 54 | } 55 | 56 | 57 | void ecc_get_public_key65(const uint8_t *private_key, uint8_t *public_key) 58 | { 59 | ecc_get_pubkey(private_key, public_key, 65, 0); 60 | } 61 | 62 | 63 | void ecc_get_public_key33(const uint8_t *private_key, uint8_t *public_key) 64 | { 65 | ecc_get_pubkey(private_key, public_key, 33, 1); 66 | } 67 | 68 | bool ecc_private_key_tweak_add(uint8_t *private_key, const uint8_t *tweak) 69 | { 70 | assert(secp256k1_ctx); 71 | return secp256k1_ec_privkey_tweak_add(secp256k1_ctx, (unsigned char *)private_key, (const unsigned char *)tweak); 72 | } 73 | 74 | bool ecc_public_key_tweak_add(uint8_t *public_key_inout, const uint8_t *tweak) 75 | { 76 | int out; 77 | secp256k1_pubkey pubkey; 78 | 79 | assert(secp256k1_ctx); 80 | if (!secp256k1_ec_pubkey_parse(secp256k1_ctx, &pubkey, public_key_inout, 33)) 81 | return false; 82 | 83 | if (!secp256k1_ec_pubkey_tweak_add(secp256k1_ctx, &pubkey, (const unsigned char *)tweak)) 84 | return false; 85 | 86 | if (!secp256k1_ec_pubkey_serialize(secp256k1_ctx, public_key_inout, (size_t *)&out, &pubkey, 87 | SECP256K1_EC_COMPRESSED)) 88 | return false; 89 | 90 | return true; 91 | } 92 | 93 | 94 | bool ecc_verify_privatekey(const uint8_t *private_key) 95 | { 96 | assert(secp256k1_ctx); 97 | return secp256k1_ec_seckey_verify(secp256k1_ctx, (const unsigned char *)private_key); 98 | } 99 | 100 | bool ecc_verify_pubkey(const uint8_t *public_key, int compressed) 101 | { 102 | secp256k1_pubkey pubkey; 103 | 104 | assert(secp256k1_ctx); 105 | if (!secp256k1_ec_pubkey_parse(secp256k1_ctx, &pubkey, public_key, compressed ? 33 : 65)) 106 | { 107 | memset(&pubkey, 0, sizeof(pubkey)); 108 | return false; 109 | } 110 | 111 | memset(&pubkey, 0, sizeof(pubkey)); 112 | return true; 113 | } 114 | 115 | bool ecc_sign(const uint8_t *private_key, const uint8_t *hash, unsigned char *sigder, size_t *outlen) 116 | { 117 | assert(secp256k1_ctx); 118 | 119 | secp256k1_ecdsa_signature sig; 120 | if (!secp256k1_ecdsa_sign(secp256k1_ctx, &sig, hash, private_key, secp256k1_nonce_function_rfc6979, NULL)) 121 | return false; 122 | 123 | if (secp256k1_ecdsa_signature_serialize_der(secp256k1_ctx, sigder, outlen, &sig)) 124 | return false; 125 | 126 | return true; 127 | } 128 | 129 | bool ecc_verify_sig(const uint8_t *public_key, int compressed, const uint8_t *hash, unsigned char *sigder, size_t siglen) 130 | { 131 | assert(secp256k1_ctx); 132 | 133 | secp256k1_ecdsa_signature sig; 134 | secp256k1_pubkey pubkey; 135 | 136 | if (!secp256k1_ec_pubkey_parse(secp256k1_ctx, &pubkey, public_key, compressed ? 33 : 65)) 137 | return false; 138 | 139 | if (!secp256k1_ecdsa_signature_parse_der(secp256k1_ctx, &sig, sigder, siglen)) 140 | return false; 141 | 142 | return secp256k1_ecdsa_verify(secp256k1_ctx, &sig, hash, &pubkey); 143 | } 144 | -------------------------------------------------------------------------------- /src/secp256k1/build-aux/m4/ax_prog_cc_for_build.m4: -------------------------------------------------------------------------------- 1 | # =========================================================================== 2 | # http://www.gnu.org/software/autoconf-archive/ax_prog_cc_for_build.html 3 | # =========================================================================== 4 | # 5 | # SYNOPSIS 6 | # 7 | # AX_PROG_CC_FOR_BUILD 8 | # 9 | # DESCRIPTION 10 | # 11 | # This macro searches for a C compiler that generates native executables, 12 | # that is a C compiler that surely is not a cross-compiler. This can be 13 | # useful if you have to generate source code at compile-time like for 14 | # example GCC does. 15 | # 16 | # The macro sets the CC_FOR_BUILD and CPP_FOR_BUILD macros to anything 17 | # needed to compile or link (CC_FOR_BUILD) and preprocess (CPP_FOR_BUILD). 18 | # The value of these variables can be overridden by the user by specifying 19 | # a compiler with an environment variable (like you do for standard CC). 20 | # 21 | # It also sets BUILD_EXEEXT and BUILD_OBJEXT to the executable and object 22 | # file extensions for the build platform, and GCC_FOR_BUILD to `yes' if 23 | # the compiler we found is GCC. All these variables but GCC_FOR_BUILD are 24 | # substituted in the Makefile. 25 | # 26 | # LICENSE 27 | # 28 | # Copyright (c) 2008 Paolo Bonzini 29 | # 30 | # Copying and distribution of this file, with or without modification, are 31 | # permitted in any medium without royalty provided the copyright notice 32 | # and this notice are preserved. This file is offered as-is, without any 33 | # warranty. 34 | 35 | #serial 8 36 | 37 | AU_ALIAS([AC_PROG_CC_FOR_BUILD], [AX_PROG_CC_FOR_BUILD]) 38 | AC_DEFUN([AX_PROG_CC_FOR_BUILD], [dnl 39 | AC_REQUIRE([AC_PROG_CC])dnl 40 | AC_REQUIRE([AC_PROG_CPP])dnl 41 | AC_REQUIRE([AC_EXEEXT])dnl 42 | AC_REQUIRE([AC_CANONICAL_HOST])dnl 43 | 44 | dnl Use the standard macros, but make them use other variable names 45 | dnl 46 | pushdef([ac_cv_prog_CPP], ac_cv_build_prog_CPP)dnl 47 | pushdef([ac_cv_prog_gcc], ac_cv_build_prog_gcc)dnl 48 | pushdef([ac_cv_prog_cc_works], ac_cv_build_prog_cc_works)dnl 49 | pushdef([ac_cv_prog_cc_cross], ac_cv_build_prog_cc_cross)dnl 50 | pushdef([ac_cv_prog_cc_g], ac_cv_build_prog_cc_g)dnl 51 | pushdef([ac_cv_exeext], ac_cv_build_exeext)dnl 52 | pushdef([ac_cv_objext], ac_cv_build_objext)dnl 53 | pushdef([ac_exeext], ac_build_exeext)dnl 54 | pushdef([ac_objext], ac_build_objext)dnl 55 | pushdef([CC], CC_FOR_BUILD)dnl 56 | pushdef([CPP], CPP_FOR_BUILD)dnl 57 | pushdef([CFLAGS], CFLAGS_FOR_BUILD)dnl 58 | pushdef([CPPFLAGS], CPPFLAGS_FOR_BUILD)dnl 59 | pushdef([LDFLAGS], LDFLAGS_FOR_BUILD)dnl 60 | pushdef([host], build)dnl 61 | pushdef([host_alias], build_alias)dnl 62 | pushdef([host_cpu], build_cpu)dnl 63 | pushdef([host_vendor], build_vendor)dnl 64 | pushdef([host_os], build_os)dnl 65 | pushdef([ac_cv_host], ac_cv_build)dnl 66 | pushdef([ac_cv_host_alias], ac_cv_build_alias)dnl 67 | pushdef([ac_cv_host_cpu], ac_cv_build_cpu)dnl 68 | pushdef([ac_cv_host_vendor], ac_cv_build_vendor)dnl 69 | pushdef([ac_cv_host_os], ac_cv_build_os)dnl 70 | pushdef([ac_cpp], ac_build_cpp)dnl 71 | pushdef([ac_compile], ac_build_compile)dnl 72 | pushdef([ac_link], ac_build_link)dnl 73 | 74 | save_cross_compiling=$cross_compiling 75 | save_ac_tool_prefix=$ac_tool_prefix 76 | cross_compiling=no 77 | ac_tool_prefix= 78 | 79 | AC_PROG_CC 80 | AC_PROG_CPP 81 | AC_EXEEXT 82 | 83 | ac_tool_prefix=$save_ac_tool_prefix 84 | cross_compiling=$save_cross_compiling 85 | 86 | dnl Restore the old definitions 87 | dnl 88 | popdef([ac_link])dnl 89 | popdef([ac_compile])dnl 90 | popdef([ac_cpp])dnl 91 | popdef([ac_cv_host_os])dnl 92 | popdef([ac_cv_host_vendor])dnl 93 | popdef([ac_cv_host_cpu])dnl 94 | popdef([ac_cv_host_alias])dnl 95 | popdef([ac_cv_host])dnl 96 | popdef([host_os])dnl 97 | popdef([host_vendor])dnl 98 | popdef([host_cpu])dnl 99 | popdef([host_alias])dnl 100 | popdef([host])dnl 101 | popdef([LDFLAGS])dnl 102 | popdef([CPPFLAGS])dnl 103 | popdef([CFLAGS])dnl 104 | popdef([CPP])dnl 105 | popdef([CC])dnl 106 | popdef([ac_objext])dnl 107 | popdef([ac_exeext])dnl 108 | popdef([ac_cv_objext])dnl 109 | popdef([ac_cv_exeext])dnl 110 | popdef([ac_cv_prog_cc_g])dnl 111 | popdef([ac_cv_prog_cc_cross])dnl 112 | popdef([ac_cv_prog_cc_works])dnl 113 | popdef([ac_cv_prog_gcc])dnl 114 | popdef([ac_cv_prog_CPP])dnl 115 | 116 | dnl Finally, set Makefile variables 117 | dnl 118 | BUILD_EXEEXT=$ac_build_exeext 119 | BUILD_OBJEXT=$ac_build_objext 120 | AC_SUBST(BUILD_EXEEXT)dnl 121 | AC_SUBST(BUILD_OBJEXT)dnl 122 | AC_SUBST([CFLAGS_FOR_BUILD])dnl 123 | AC_SUBST([CPPFLAGS_FOR_BUILD])dnl 124 | AC_SUBST([LDFLAGS_FOR_BUILD])dnl 125 | ]) 126 | -------------------------------------------------------------------------------- /test/utest.h: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright (c) 2015 Douglas J. Bakkum 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining 6 | a copy of this software and associated documentation files (the "Software"), 7 | to deal in the Software without restriction, including without limitation 8 | the rights to use, copy, modify, merge, publish, distribute, sublicense, 9 | and/or sell copies of the Software, and to permit persons to whom the 10 | Software is furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included 13 | in all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 16 | OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 18 | THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES 19 | OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 20 | ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 21 | OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | */ 24 | 25 | 26 | /* 27 | 28 | // 29 | // Macros for light weight unit testing based on 30 | // minunit.h from http://www.jera.com/techinfo/jtns/jtn002.html 31 | // 32 | // Example code: 33 | // 34 | 35 | #include "utest.h" 36 | 37 | int U_TESTS_RUN = 0; 38 | int U_TESTS_FAIL = 0; 39 | 40 | static void test_str(void) { 41 | char * str = "hello"; 42 | u_assert_str_eq(str, "hello"); 43 | u_assert_str_eq(str, "hellooo"); 44 | return; 45 | } 46 | 47 | static void test_int(void) { 48 | int i = 7; 49 | u_assert_int_eq(i, 7); 50 | u_assert_int_eq(i, 8); 51 | return; 52 | } 53 | 54 | static void test_mem(void) { 55 | char * str = "hello"; 56 | u_assert_mem_eq(str, "hello", 5); 57 | u_assert_mem_eq(str, "hellooo", 5); 58 | u_assert_mem_eq(str, "helooo", 5); 59 | return; 60 | } 61 | 62 | 63 | int main(void) 64 | { 65 | u_run_test(test_str); 66 | u_run_test(test_mem); 67 | u_run_test(test_int); 68 | if (!U_TESTS_FAIL) { 69 | printf("\nALL TESTS PASSED\n\n"); 70 | } 71 | return U_TESTS_FAIL; 72 | } 73 | */ 74 | 75 | 76 | #ifndef _UTEST_H_ 77 | #define _UTEST_H_ 78 | #include 79 | #include 80 | 81 | #define u_run_test(TEST) do {\ 82 | int f_ = U_TESTS_FAIL; \ 83 | TEST(); U_TESTS_RUN++; \ 84 | if (f_ == U_TESTS_FAIL) { \ 85 | printf("PASSED - %s()\n", #TEST); };\ 86 | } while (0) 87 | 88 | #define u_assert_int_eq(R,E) {\ 89 | int r_ = (R); \ 90 | int e_ = (E); \ 91 | do { if (r_!=e_) { \ 92 | printf("FAILED - %s() - Line %d\n", __func__, __LINE__);\ 93 | printf("\tExpect: \t%d\n", e_);\ 94 | printf("\tReceive:\t%d\n", r_);\ 95 | U_TESTS_FAIL++;\ 96 | return; }; \ 97 | } while(0); } 98 | 99 | #define u_assert_str_eq(R,E) {\ 100 | const char * r_ = (R); \ 101 | const char * e_ = (E); \ 102 | do { if (strcmp(r_,e_)) { \ 103 | printf("FAILED - %s() - Line %d\n", __func__, __LINE__);\ 104 | printf("\tExpect: \t%s\n", e_);\ 105 | printf("\tReceive:\t%s\n", r_);\ 106 | U_TESTS_FAIL++;\ 107 | return; }; \ 108 | } while(0); } 109 | 110 | #define u_assert_str_not_eq(R,E) {\ 111 | const char * r_ = (R); \ 112 | const char * e_ = (E); \ 113 | do { if (!strcmp(r_,e_)) { \ 114 | printf("FAILED - %s() - Line %d\n", __func__, __LINE__);\ 115 | printf("\tNot expect:\t%s\n", e_);\ 116 | printf("\tReceive:\t%s\n", r_);\ 117 | U_TESTS_FAIL++;\ 118 | return; }; \ 119 | } while(0); } 120 | 121 | #define u_assert_str_has(R,E) {\ 122 | const char * r_ = (R); \ 123 | const char * e_ = (E); \ 124 | do { if (!strstr(r_,e_)) { \ 125 | printf("FAILED - %s() - Line %d\n", __func__, __LINE__);\ 126 | printf("\tExpect: \t%s\n", e_);\ 127 | printf("\tReceive:\t%s\n", r_);\ 128 | U_TESTS_FAIL++;\ 129 | return; }; \ 130 | } while(0); } 131 | 132 | #define u_assert_str_has_not(R,E) {\ 133 | const char * r_ = (R); \ 134 | const char * e_ = (E); \ 135 | do { if (strstr(r_,e_)) { \ 136 | printf("FAILED - %s() - Line %d\n", __func__, __LINE__);\ 137 | printf("\tNot expect:\t%s\n", e_);\ 138 | printf("\tReceive:\t%s\n", r_);\ 139 | U_TESTS_FAIL++;\ 140 | return; }; \ 141 | } while(0); } 142 | 143 | #define u_assert_mem_eq(R,E,L) {\ 144 | const void * r_ = (R); \ 145 | const void * e_ = (E); \ 146 | size_t l_ = (L); \ 147 | do { if (memcmp(r_,e_,l_)) { \ 148 | printf("FAILED - %s() - Line %d\n", __func__, __LINE__);\ 149 | printf("\tExpect: \t%s\n", utils_uint8_to_hex(e_,l_));\ 150 | printf("\tReceive:\t%s\n", utils_uint8_to_hex(r_,l_));\ 151 | U_TESTS_FAIL++;\ 152 | return; }; \ 153 | } while(0); } 154 | 155 | extern int U_TESTS_RUN; 156 | extern int U_TESTS_FAIL; 157 | 158 | #endif 159 | -------------------------------------------------------------------------------- /src/secp256k1/src/scalar.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2014 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_SCALAR_ 8 | #define _SECP256K1_SCALAR_ 9 | 10 | #include "num.h" 11 | 12 | #if defined HAVE_CONFIG_H 13 | #include "libsecp256k1-config.h" 14 | #endif 15 | 16 | #if defined(USE_SCALAR_4X64) 17 | #include "scalar_4x64.h" 18 | #elif defined(USE_SCALAR_8X32) 19 | #include "scalar_8x32.h" 20 | #else 21 | #error "Please select scalar implementation" 22 | #endif 23 | 24 | /** Clear a scalar to prevent the leak of sensitive data. */ 25 | static void secp256k1_scalar_clear(secp256k1_scalar *r); 26 | 27 | /** Access bits from a scalar. All requested bits must belong to the same 32-bit limb. */ 28 | static unsigned int secp256k1_scalar_get_bits(const secp256k1_scalar *a, unsigned int offset, unsigned int count); 29 | 30 | /** Access bits from a scalar. Not constant time. */ 31 | static unsigned int secp256k1_scalar_get_bits_var(const secp256k1_scalar *a, unsigned int offset, unsigned int count); 32 | 33 | /** Set a scalar from a big endian byte array. */ 34 | static void secp256k1_scalar_set_b32(secp256k1_scalar *r, const unsigned char *bin, int *overflow); 35 | 36 | /** Set a scalar to an unsigned integer. */ 37 | static void secp256k1_scalar_set_int(secp256k1_scalar *r, unsigned int v); 38 | 39 | /** Convert a scalar to a byte array. */ 40 | static void secp256k1_scalar_get_b32(unsigned char *bin, const secp256k1_scalar* a); 41 | 42 | /** Add two scalars together (modulo the group order). Returns whether it overflowed. */ 43 | static int secp256k1_scalar_add(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b); 44 | 45 | /** Conditionally add a power of two to a scalar. The result is not allowed to overflow. */ 46 | static void secp256k1_scalar_cadd_bit(secp256k1_scalar *r, unsigned int bit, int flag); 47 | 48 | /** Multiply two scalars (modulo the group order). */ 49 | static void secp256k1_scalar_mul(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b); 50 | 51 | /** Shift a scalar right by some amount strictly between 0 and 16, returning 52 | * the low bits that were shifted off */ 53 | static int secp256k1_scalar_shr_int(secp256k1_scalar *r, int n); 54 | 55 | /** Compute the square of a scalar (modulo the group order). */ 56 | static void secp256k1_scalar_sqr(secp256k1_scalar *r, const secp256k1_scalar *a); 57 | 58 | /** Compute the inverse of a scalar (modulo the group order). */ 59 | static void secp256k1_scalar_inverse(secp256k1_scalar *r, const secp256k1_scalar *a); 60 | 61 | /** Compute the inverse of a scalar (modulo the group order), without constant-time guarantee. */ 62 | static void secp256k1_scalar_inverse_var(secp256k1_scalar *r, const secp256k1_scalar *a); 63 | 64 | /** Compute the complement of a scalar (modulo the group order). */ 65 | static void secp256k1_scalar_negate(secp256k1_scalar *r, const secp256k1_scalar *a); 66 | 67 | /** Check whether a scalar equals zero. */ 68 | static int secp256k1_scalar_is_zero(const secp256k1_scalar *a); 69 | 70 | /** Check whether a scalar equals one. */ 71 | static int secp256k1_scalar_is_one(const secp256k1_scalar *a); 72 | 73 | /** Check whether a scalar, considered as an nonnegative integer, is even. */ 74 | static int secp256k1_scalar_is_even(const secp256k1_scalar *a); 75 | 76 | /** Check whether a scalar is higher than the group order divided by 2. */ 77 | static int secp256k1_scalar_is_high(const secp256k1_scalar *a); 78 | 79 | /** Conditionally negate a number, in constant time. 80 | * Returns -1 if the number was negated, 1 otherwise */ 81 | static int secp256k1_scalar_cond_negate(secp256k1_scalar *a, int flag); 82 | 83 | #ifndef USE_NUM_NONE 84 | /** Convert a scalar to a number. */ 85 | static void secp256k1_scalar_get_num(secp256k1_num *r, const secp256k1_scalar *a); 86 | 87 | /** Get the order of the group as a number. */ 88 | static void secp256k1_scalar_order_get_num(secp256k1_num *r); 89 | #endif 90 | 91 | /** Compare two scalars. */ 92 | static int secp256k1_scalar_eq(const secp256k1_scalar *a, const secp256k1_scalar *b); 93 | 94 | #ifdef USE_ENDOMORPHISM 95 | /** Find r1 and r2 such that r1+r2*2^128 = a. */ 96 | static void secp256k1_scalar_split_128(secp256k1_scalar *r1, secp256k1_scalar *r2, const secp256k1_scalar *a); 97 | /** Find r1 and r2 such that r1+r2*lambda = a, and r1 and r2 are maximum 128 bits long (see secp256k1_gej_mul_lambda). */ 98 | static void secp256k1_scalar_split_lambda(secp256k1_scalar *r1, secp256k1_scalar *r2, const secp256k1_scalar *a); 99 | #endif 100 | 101 | /** Multiply a and b (without taking the modulus!), divide by 2**shift, and round to the nearest integer. Shift must be at least 256. */ 102 | static void secp256k1_scalar_mul_shift_var(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b, unsigned int shift); 103 | 104 | #endif 105 | -------------------------------------------------------------------------------- /src/secp256k1/include/secp256k1_recovery.h: -------------------------------------------------------------------------------- 1 | #ifndef _SECP256K1_RECOVERY_ 2 | # define _SECP256K1_RECOVERY_ 3 | 4 | # include "secp256k1.h" 5 | 6 | # ifdef __cplusplus 7 | extern "C" { 8 | # endif 9 | 10 | /** Opaque data structured that holds a parsed ECDSA signature, 11 | * supporting pubkey recovery. 12 | * 13 | * The exact representation of data inside is implementation defined and not 14 | * guaranteed to be portable between different platforms or versions. It is 15 | * however guaranteed to be 65 bytes in size, and can be safely copied/moved. 16 | * If you need to convert to a format suitable for storage or transmission, use 17 | * the secp256k1_ecdsa_signature_serialize_* and 18 | * secp256k1_ecdsa_signature_serialize_* functions. 19 | * 20 | * Furthermore, it is guaranteed to identical signatures (including their 21 | * recoverability) will have identical representation, so they can be 22 | * memcmp'ed. 23 | */ 24 | typedef struct { 25 | unsigned char data[65]; 26 | } secp256k1_ecdsa_recoverable_signature; 27 | 28 | /** Parse a compact ECDSA signature (64 bytes + recovery id). 29 | * 30 | * Returns: 1 when the signature could be parsed, 0 otherwise 31 | * Args: ctx: a secp256k1 context object 32 | * Out: sig: a pointer to a signature object 33 | * In: input64: a pointer to a 64-byte compact signature 34 | * recid: the recovery id (0, 1, 2 or 3) 35 | */ 36 | SECP256K1_API int secp256k1_ecdsa_recoverable_signature_parse_compact( 37 | const secp256k1_context* ctx, 38 | secp256k1_ecdsa_recoverable_signature* sig, 39 | const unsigned char *input64, 40 | int recid 41 | ) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3); 42 | 43 | /** Convert a recoverable signature into a normal signature. 44 | * 45 | * Returns: 1 46 | * Out: sig: a pointer to a normal signature (cannot be NULL). 47 | * In: sigin: a pointer to a recoverable signature (cannot be NULL). 48 | */ 49 | SECP256K1_API int secp256k1_ecdsa_recoverable_signature_convert( 50 | const secp256k1_context* ctx, 51 | secp256k1_ecdsa_signature* sig, 52 | const secp256k1_ecdsa_recoverable_signature* sigin 53 | ) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3); 54 | 55 | /** Serialize an ECDSA signature in compact format (64 bytes + recovery id). 56 | * 57 | * Returns: 1 58 | * Args: ctx: a secp256k1 context object 59 | * Out: output64: a pointer to a 64-byte array of the compact signature (cannot be NULL) 60 | * recid: a pointer to an integer to hold the recovery id (can be NULL). 61 | * In: sig: a pointer to an initialized signature object (cannot be NULL) 62 | */ 63 | SECP256K1_API int secp256k1_ecdsa_recoverable_signature_serialize_compact( 64 | const secp256k1_context* ctx, 65 | unsigned char *output64, 66 | int *recid, 67 | const secp256k1_ecdsa_recoverable_signature* sig 68 | ) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(4); 69 | 70 | /** Create a recoverable ECDSA signature. 71 | * 72 | * Returns: 1: signature created 73 | * 0: the nonce generation function failed, or the private key was invalid. 74 | * Args: ctx: pointer to a context object, initialized for signing (cannot be NULL) 75 | * Out: sig: pointer to an array where the signature will be placed (cannot be NULL) 76 | * In: msg32: the 32-byte message hash being signed (cannot be NULL) 77 | * seckey: pointer to a 32-byte secret key (cannot be NULL) 78 | * noncefp:pointer to a nonce generation function. If NULL, secp256k1_nonce_function_default is used 79 | * ndata: pointer to arbitrary data used by the nonce generation function (can be NULL) 80 | */ 81 | SECP256K1_API int secp256k1_ecdsa_sign_recoverable( 82 | const secp256k1_context* ctx, 83 | secp256k1_ecdsa_recoverable_signature *sig, 84 | const unsigned char *msg32, 85 | const unsigned char *seckey, 86 | secp256k1_nonce_function noncefp, 87 | const void *ndata 88 | ) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4); 89 | 90 | /** Recover an ECDSA public key from a signature. 91 | * 92 | * Returns: 1: public key successfully recovered (which guarantees a correct signature). 93 | * 0: otherwise. 94 | * Args: ctx: pointer to a context object, initialized for verification (cannot be NULL) 95 | * Out: pubkey: pointer to the recoved public key (cannot be NULL) 96 | * In: sig: pointer to initialized signature that supports pubkey recovery (cannot be NULL) 97 | * msg32: the 32-byte message hash assumed to be signed (cannot be NULL) 98 | */ 99 | SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ecdsa_recover( 100 | const secp256k1_context* ctx, 101 | secp256k1_pubkey *pubkey, 102 | const secp256k1_ecdsa_recoverable_signature *sig, 103 | const unsigned char *msg32 104 | ) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4); 105 | 106 | # ifdef __cplusplus 107 | } 108 | # endif 109 | 110 | #endif 111 | -------------------------------------------------------------------------------- /src/vector.c: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | The MIT License (MIT) 4 | 5 | Copyright (c) 2015 Jonas Schnelli 6 | 7 | Permission is hereby granted, free of charge, to any person obtaining 8 | a copy of this software and associated documentation files (the "Software"), 9 | to deal in the Software without restriction, including without limitation 10 | the rights to use, copy, modify, merge, publish, distribute, sublicense, 11 | and/or sell copies of the Software, and to permit persons to whom the 12 | Software is furnished to do so, subject to the following conditions: 13 | 14 | The above copyright notice and this permission notice shall be included 15 | in all copies or substantial portions of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 18 | OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 19 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 20 | THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES 21 | OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 22 | ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 23 | OTHER DEALINGS IN THE SOFTWARE. 24 | 25 | */ 26 | 27 | #include "vector.h" 28 | 29 | #include 30 | 31 | vector *vector_new(size_t res, void (*free_f)(void *)) 32 | { 33 | vector *vec = calloc(1, sizeof(vector)); 34 | if (!vec) 35 | return NULL; 36 | 37 | vec->alloc = 8; 38 | while (vec->alloc < res) 39 | vec->alloc *= 2; 40 | 41 | vec->elem_free_f = free_f; 42 | vec->data = malloc(vec->alloc * sizeof(void *)); 43 | if (!vec->data) { 44 | free(vec); 45 | return NULL; 46 | } 47 | 48 | return vec; 49 | } 50 | 51 | static void vector_free_data(vector *vec) 52 | { 53 | if (!vec->data) 54 | return; 55 | 56 | if (vec->elem_free_f) { 57 | unsigned int i; 58 | for (i = 0; i < vec->len; i++) 59 | if (vec->data[i]) { 60 | vec->elem_free_f(vec->data[i]); 61 | vec->data[i] = NULL; 62 | } 63 | } 64 | 65 | free(vec->data); 66 | vec->data = NULL; 67 | vec->alloc = 0; 68 | vec->len = 0; 69 | } 70 | 71 | void vector_free(vector *vec, bool free_array) 72 | { 73 | if (!vec) 74 | return; 75 | 76 | if (free_array) 77 | vector_free_data(vec); 78 | 79 | memset(vec, 0, sizeof(*vec)); 80 | free(vec); 81 | } 82 | 83 | static bool vector_grow(vector *vec, size_t min_sz) 84 | { 85 | size_t new_alloc = vec->alloc; 86 | while (new_alloc < min_sz) 87 | new_alloc *= 2; 88 | 89 | if (vec->alloc == new_alloc) 90 | return true; 91 | 92 | void *new_data = realloc(vec->data, new_alloc * sizeof(void *)); 93 | if (!new_data) 94 | return false; 95 | 96 | vec->data = new_data; 97 | vec->alloc = new_alloc; 98 | return true; 99 | } 100 | 101 | ssize_t vector_find(vector *vec, void *data) 102 | { 103 | if (vec && vec->len) { 104 | size_t i; 105 | for (i = 0; i < vec->len; i++) 106 | if (vec->data[i] == data) 107 | return (ssize_t) i; 108 | } 109 | 110 | return -1; 111 | } 112 | 113 | bool vector_add(vector *vec, void *data) 114 | { 115 | if (vec->len == vec->alloc) 116 | if (!vector_grow(vec, vec->len + 1)) 117 | return false; 118 | 119 | vec->data[vec->len] = data; 120 | vec->len++; 121 | return true; 122 | } 123 | 124 | void vector_remove_range(vector *vec, size_t pos, size_t len) 125 | { 126 | if (!vec || ((pos+len) > vec->len)) 127 | return; 128 | 129 | if (vec->elem_free_f) { 130 | unsigned int i, count; 131 | for (i = pos, count = 0; count < len; i++, count++) 132 | vec->elem_free_f(vec->data[i]); 133 | } 134 | 135 | memmove(&vec->data[pos], &vec->data[pos + len], 136 | (vec->len - pos - len) * sizeof(void *)); 137 | vec->len -= len; 138 | } 139 | 140 | void vector_remove_idx(vector *vec, size_t pos) 141 | { 142 | vector_remove_range(vec, pos, 1); 143 | } 144 | 145 | bool vector_remove(vector *vec, void *data) 146 | { 147 | ssize_t idx = vector_find(vec, data); 148 | if (idx < 0) 149 | return false; 150 | 151 | vector_remove_idx(vec, idx); 152 | return true; 153 | } 154 | 155 | bool vector_resize(vector *vec, size_t newsz) 156 | { 157 | unsigned int i; 158 | 159 | /* same size */ 160 | if (newsz == vec->len) 161 | return true; 162 | 163 | /* truncate */ 164 | else if (newsz < vec->len) { 165 | size_t del_count = vec->len - newsz; 166 | 167 | for (i = (vec->len - del_count); i < vec->len; i++) { 168 | if (vec->elem_free_f) 169 | vec->elem_free_f(vec->data[i]); 170 | vec->data[i] = NULL; 171 | } 172 | 173 | vec->len = newsz; 174 | return true; 175 | } 176 | 177 | /* last possibility: grow */ 178 | if (!vector_grow(vec, newsz)) 179 | return false; 180 | 181 | /* set new elements to NULL */ 182 | for (i = vec->len; i < newsz; i++) 183 | vec->data[i] = NULL; 184 | 185 | return true; 186 | } 187 | 188 | -------------------------------------------------------------------------------- /src/serialize.c: -------------------------------------------------------------------------------- 1 | /* Copyright 2012 exMULTI, Inc. 2 | * Distributed under the MIT/X11 software license, see the accompanying 3 | * file COPYING or http://www.opensource.org/licenses/mit-license.php. 4 | */ 5 | 6 | #include "serialize.h" 7 | 8 | #include 9 | #include 10 | 11 | #include "cstr.h" 12 | 13 | void ser_bytes(cstring *s, const void *p, size_t len) 14 | { 15 | cstr_append_buf(s, p, len); 16 | } 17 | 18 | void ser_u16(cstring *s, uint16_t v_) 19 | { 20 | uint16_t v = htole16(v_); 21 | cstr_append_buf(s, &v, sizeof(v)); 22 | } 23 | 24 | void ser_u32(cstring *s, uint32_t v_) 25 | { 26 | uint32_t v = htole32(v_); 27 | cstr_append_buf(s, &v, sizeof(v)); 28 | } 29 | 30 | void ser_u64(cstring *s, uint64_t v_) 31 | { 32 | uint64_t v = htole64(v_); 33 | cstr_append_buf(s, &v, sizeof(v)); 34 | } 35 | 36 | void ser_varlen(cstring *s, uint32_t vlen) 37 | { 38 | unsigned char c; 39 | 40 | if (vlen < 253) { 41 | c = vlen; 42 | ser_bytes(s, &c, 1); 43 | } 44 | 45 | else if (vlen < 0x10000) { 46 | c = 253; 47 | ser_bytes(s, &c, 1); 48 | ser_u16(s, (uint16_t) vlen); 49 | } 50 | 51 | else { 52 | c = 254; 53 | ser_bytes(s, &c, 1); 54 | ser_u32(s, vlen); 55 | } 56 | 57 | /* u64 case intentionally not implemented */ 58 | } 59 | 60 | void ser_str(cstring *s, const char *s_in, size_t maxlen) 61 | { 62 | size_t slen = strnlen(s_in, maxlen); 63 | 64 | ser_varlen(s, slen); 65 | ser_bytes(s, s_in, slen); 66 | } 67 | 68 | void ser_varstr(cstring *s, cstring *s_in) 69 | { 70 | if (!s_in || !s_in->len) { 71 | ser_varlen(s, 0); 72 | return; 73 | } 74 | 75 | ser_varlen(s, s_in->len); 76 | ser_bytes(s, s_in->str, s_in->len); 77 | } 78 | 79 | void ser_u256_vector(cstring *s, vector *vec) 80 | { 81 | unsigned int vec_len = vec ? vec->len : 0; 82 | 83 | ser_varlen(s, vec_len); 84 | 85 | unsigned int i; 86 | for (i = 0; i < vec_len; i++) { 87 | uint8_t *av = vector_idx(vec, i); 88 | ser_u256(s, av); 89 | } 90 | } 91 | 92 | bool deser_skip(struct const_buffer *buf, size_t len) 93 | { 94 | if (buf->len < len) 95 | return false; 96 | 97 | buf->p += len; 98 | buf->len -= len; 99 | 100 | return true; 101 | } 102 | 103 | bool deser_bytes(void *po, struct const_buffer *buf, size_t len) 104 | { 105 | if (buf->len < len) 106 | return false; 107 | 108 | memcpy(po, buf->p, len); 109 | buf->p += len; 110 | buf->len -= len; 111 | 112 | return true; 113 | } 114 | 115 | bool deser_u16(uint16_t *vo, struct const_buffer *buf) 116 | { 117 | uint16_t v; 118 | 119 | if (!deser_bytes(&v, buf, sizeof(v))) 120 | return false; 121 | 122 | *vo = le16toh(v); 123 | return true; 124 | } 125 | 126 | bool deser_u32(uint32_t *vo, struct const_buffer *buf) 127 | { 128 | uint32_t v; 129 | 130 | if (!deser_bytes(&v, buf, sizeof(v))) 131 | return false; 132 | 133 | *vo = le32toh(v); 134 | return true; 135 | } 136 | 137 | bool deser_u64(uint64_t *vo, struct const_buffer *buf) 138 | { 139 | uint64_t v; 140 | 141 | if (!deser_bytes(&v, buf, sizeof(v))) 142 | return false; 143 | 144 | *vo = le64toh(v); 145 | return true; 146 | } 147 | 148 | bool deser_varlen(uint32_t *lo, struct const_buffer *buf) 149 | { 150 | uint32_t len; 151 | 152 | unsigned char c; 153 | if (!deser_bytes(&c, buf, 1)) return false; 154 | 155 | if (c == 253) { 156 | uint16_t v16; 157 | if (!deser_u16(&v16, buf)) return false; 158 | len = v16; 159 | } 160 | else if (c == 254) { 161 | uint32_t v32; 162 | if (!deser_u32(&v32, buf)) return false; 163 | len = v32; 164 | } 165 | else if (c == 255) { 166 | uint64_t v64; 167 | if (!deser_u64(&v64, buf)) return false; 168 | len = (uint32_t) v64; /* WARNING: truncate */ 169 | } 170 | else 171 | len = c; 172 | 173 | *lo = len; 174 | return true; 175 | } 176 | 177 | bool deser_str(char *so, struct const_buffer *buf, size_t maxlen) 178 | { 179 | uint32_t len; 180 | if (!deser_varlen(&len, buf)) return false; 181 | 182 | /* if input larger than buffer, truncate copy, skip remainder */ 183 | uint32_t skip_len = 0; 184 | if (len > maxlen) { 185 | skip_len = len - maxlen; 186 | len = maxlen; 187 | } 188 | 189 | if (!deser_bytes(so, buf, len)) return false; 190 | if (!deser_skip(buf, skip_len)) return false; 191 | 192 | /* add C string null */ 193 | if (len < maxlen) 194 | so[len] = 0; 195 | else 196 | so[maxlen - 1] = 0; 197 | 198 | return true; 199 | } 200 | 201 | bool deser_varstr(cstring **so, struct const_buffer *buf) 202 | { 203 | if (*so) { 204 | cstr_free(*so, true); 205 | *so = NULL; 206 | } 207 | 208 | uint32_t len; 209 | if (!deser_varlen(&len, buf)) return false; 210 | 211 | if (buf->len < len) 212 | return false; 213 | 214 | cstring *s = cstr_new_sz(len); 215 | cstr_append_buf(s, buf->p, len); 216 | 217 | buf->p += len; 218 | buf->len -= len; 219 | 220 | *so = s; 221 | 222 | return true; 223 | } 224 | 225 | bool deser_u256_vector(vector **vo, struct const_buffer *buf) 226 | { 227 | vector *vec = *vo; 228 | if (vec) { 229 | vector_free(vec, true); 230 | *vo = vec = NULL; 231 | } 232 | 233 | uint32_t vlen; 234 | if (!deser_varlen(&vlen, buf)) return false; 235 | 236 | if (!vlen) 237 | return true; 238 | 239 | vec = vector_new(vlen, free); 240 | if (!vec) 241 | return false; 242 | 243 | unsigned int i; 244 | for (i = 0; i < vlen; i++) { 245 | uint8_t *n = malloc(32); 246 | 247 | if (!deser_u256(n, buf)) { 248 | free(n); 249 | goto err_out; 250 | } 251 | 252 | vector_add(vec, n); 253 | } 254 | 255 | *vo = vec; 256 | return true; 257 | 258 | err_out: 259 | vector_free(vec, true); 260 | return false; 261 | } 262 | -------------------------------------------------------------------------------- /src/script.h: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | The MIT License (MIT) 4 | 5 | Copyright (c) 2015 Jonas Schnelli 6 | 7 | Permission is hereby granted, free of charge, to any person obtaining 8 | a copy of this software and associated documentation files (the "Software"), 9 | to deal in the Software without restriction, including without limitation 10 | the rights to use, copy, modify, merge, publish, distribute, sublicense, 11 | and/or sell copies of the Software, and to permit persons to whom the 12 | Software is furnished to do so, subject to the following conditions: 13 | 14 | The above copyright notice and this permission notice shall be included 15 | in all copies or substantial portions of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 18 | OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 19 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 20 | THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES 21 | OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 22 | ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 23 | OTHER DEALINGS IN THE SOFTWARE. 24 | 25 | */ 26 | 27 | 28 | #include "cstr.h" 29 | #include "vector.h" 30 | 31 | /** Signature hash types/flags */ 32 | enum 33 | { 34 | SIGHASH_ALL = 1, 35 | SIGHASH_NONE = 2, 36 | SIGHASH_SINGLE = 3, 37 | SIGHASH_ANYONECANPAY = 0x80, 38 | }; 39 | 40 | /** Script opcodes */ 41 | enum opcodetype 42 | { 43 | // push value 44 | OP_0 = 0x00, 45 | OP_FALSE = OP_0, 46 | OP_PUSHDATA1 = 0x4c, 47 | OP_PUSHDATA2 = 0x4d, 48 | OP_PUSHDATA4 = 0x4e, 49 | OP_1NEGATE = 0x4f, 50 | OP_RESERVED = 0x50, 51 | OP_1 = 0x51, 52 | OP_TRUE=OP_1, 53 | OP_2 = 0x52, 54 | OP_3 = 0x53, 55 | OP_4 = 0x54, 56 | OP_5 = 0x55, 57 | OP_6 = 0x56, 58 | OP_7 = 0x57, 59 | OP_8 = 0x58, 60 | OP_9 = 0x59, 61 | OP_10 = 0x5a, 62 | OP_11 = 0x5b, 63 | OP_12 = 0x5c, 64 | OP_13 = 0x5d, 65 | OP_14 = 0x5e, 66 | OP_15 = 0x5f, 67 | OP_16 = 0x60, 68 | 69 | // control 70 | OP_NOP = 0x61, 71 | OP_VER = 0x62, 72 | OP_IF = 0x63, 73 | OP_NOTIF = 0x64, 74 | OP_VERIF = 0x65, 75 | OP_VERNOTIF = 0x66, 76 | OP_ELSE = 0x67, 77 | OP_ENDIF = 0x68, 78 | OP_VERIFY = 0x69, 79 | OP_RETURN = 0x6a, 80 | 81 | // stack ops 82 | OP_TOALTSTACK = 0x6b, 83 | OP_FROMALTSTACK = 0x6c, 84 | OP_2DROP = 0x6d, 85 | OP_2DUP = 0x6e, 86 | OP_3DUP = 0x6f, 87 | OP_2OVER = 0x70, 88 | OP_2ROT = 0x71, 89 | OP_2SWAP = 0x72, 90 | OP_IFDUP = 0x73, 91 | OP_DEPTH = 0x74, 92 | OP_DROP = 0x75, 93 | OP_DUP = 0x76, 94 | OP_NIP = 0x77, 95 | OP_OVER = 0x78, 96 | OP_PICK = 0x79, 97 | OP_ROLL = 0x7a, 98 | OP_ROT = 0x7b, 99 | OP_SWAP = 0x7c, 100 | OP_TUCK = 0x7d, 101 | 102 | // splice ops 103 | OP_CAT = 0x7e, 104 | OP_SUBSTR = 0x7f, 105 | OP_LEFT = 0x80, 106 | OP_RIGHT = 0x81, 107 | OP_SIZE = 0x82, 108 | 109 | // bit logic 110 | OP_INVERT = 0x83, 111 | OP_AND = 0x84, 112 | OP_OR = 0x85, 113 | OP_XOR = 0x86, 114 | OP_EQUAL = 0x87, 115 | OP_EQUALVERIFY = 0x88, 116 | OP_RESERVED1 = 0x89, 117 | OP_RESERVED2 = 0x8a, 118 | 119 | // numeric 120 | OP_1ADD = 0x8b, 121 | OP_1SUB = 0x8c, 122 | OP_2MUL = 0x8d, 123 | OP_2DIV = 0x8e, 124 | OP_NEGATE = 0x8f, 125 | OP_ABS = 0x90, 126 | OP_NOT = 0x91, 127 | OP_0NOTEQUAL = 0x92, 128 | 129 | OP_ADD = 0x93, 130 | OP_SUB = 0x94, 131 | OP_MUL = 0x95, 132 | OP_DIV = 0x96, 133 | OP_MOD = 0x97, 134 | OP_LSHIFT = 0x98, 135 | OP_RSHIFT = 0x99, 136 | 137 | OP_BOOLAND = 0x9a, 138 | OP_BOOLOR = 0x9b, 139 | OP_NUMEQUAL = 0x9c, 140 | OP_NUMEQUALVERIFY = 0x9d, 141 | OP_NUMNOTEQUAL = 0x9e, 142 | OP_LESSTHAN = 0x9f, 143 | OP_GREATERTHAN = 0xa0, 144 | OP_LESSTHANOREQUAL = 0xa1, 145 | OP_GREATERTHANOREQUAL = 0xa2, 146 | OP_MIN = 0xa3, 147 | OP_MAX = 0xa4, 148 | 149 | OP_WITHIN = 0xa5, 150 | 151 | // crypto 152 | OP_RIPEMD160 = 0xa6, 153 | OP_SHA1 = 0xa7, 154 | OP_SHA256 = 0xa8, 155 | OP_HASH160 = 0xa9, 156 | OP_HASH256 = 0xaa, 157 | OP_CODESEPARATOR = 0xab, 158 | OP_CHECKSIG = 0xac, 159 | OP_CHECKSIGVERIFY = 0xad, 160 | OP_CHECKMULTISIG = 0xae, 161 | OP_CHECKMULTISIGVERIFY = 0xaf, 162 | 163 | // expansion 164 | OP_NOP1 = 0xb0, 165 | OP_NOP2 = 0xb1, 166 | OP_CHECKLOCKTIMEVERIFY = OP_NOP2, 167 | OP_NOP3 = 0xb2, 168 | OP_NOP4 = 0xb3, 169 | OP_NOP5 = 0xb4, 170 | OP_NOP6 = 0xb5, 171 | OP_NOP7 = 0xb6, 172 | OP_NOP8 = 0xb7, 173 | OP_NOP9 = 0xb8, 174 | OP_NOP10 = 0xb9, 175 | 176 | 177 | // template matching params 178 | OP_SMALLINTEGER = 0xfa, 179 | OP_PUBKEYS = 0xfb, 180 | OP_PUBKEYHASH = 0xfd, 181 | OP_PUBKEY = 0xfe, 182 | 183 | OP_INVALIDOPCODE = 0xff, 184 | }; 185 | 186 | enum btc_tx_out_type 187 | { 188 | BTC_TX_NONSTANDARD, 189 | // 'standard' transaction types: 190 | BTC_TX_PUBKEY, 191 | BTC_TX_PUBKEYHASH, 192 | BTC_TX_SCRIPTHASH, 193 | BTC_TX_MULTISIG, 194 | }; 195 | 196 | typedef struct btc_script_op_ { 197 | enum opcodetype op; /* opcode found */ 198 | unsigned char *data; /* associated data, if any */ 199 | size_t datalen; 200 | } btc_script_op; 201 | 202 | //copy a script without the codeseperator ops 203 | bool btc_script_copy_without_op_codeseperator(const cstring *scriptin, cstring *scriptout); 204 | 205 | btc_script_op* btc_script_op_new(); 206 | void btc_script_op_free(btc_script_op *script_op); 207 | void btc_script_op_free_cb(void *data); 208 | bool btc_script_get_ops(const cstring *script_in, vector *ops_out); 209 | 210 | enum btc_tx_out_type btc_script_classify(vector *ops); 211 | -------------------------------------------------------------------------------- /contrib/github-merge.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # This script will locally construct a merge commit for a pull request on a 4 | # github repository, inspect it, sign it and optionally push it. 5 | 6 | # The following temporary branches are created/overwritten and deleted: 7 | # * pull/$PULL/base (the current master we're merging onto) 8 | # * pull/$PULL/head (the current state of the remote pull request) 9 | # * pull/$PULL/merge (github's merge) 10 | # * pull/$PULL/local-merge (our merge) 11 | 12 | # In case of a clean merge that is accepted by the user, the local branch with 13 | # name $BRANCH is overwritten with the merged result, and optionally pushed. 14 | 15 | REPO="$(git config --get githubmerge.repository)" 16 | if [[ "d$REPO" == "d" ]]; then 17 | echo "ERROR: No repository configured. Use this command to set:" >&2 18 | echo "git config githubmerge.repository /" >&2 19 | echo "In addition, you can set the following variables:" >&2 20 | echo "- githubmerge.host (default git@github.com)" >&2 21 | echo "- githubmerge.branch (default master)" >&2 22 | echo "- githubmerge.testcmd (default none)" >&2 23 | exit 1 24 | fi 25 | 26 | HOST="$(git config --get githubmerge.host)" 27 | if [[ "d$HOST" == "d" ]]; then 28 | HOST="git@github.com" 29 | fi 30 | 31 | BRANCH="$(git config --get githubmerge.branch)" 32 | if [[ "d$BRANCH" == "d" ]]; then 33 | BRANCH="master" 34 | fi 35 | 36 | TESTCMD="$(git config --get githubmerge.testcmd)" 37 | 38 | PULL="$1" 39 | 40 | if [[ "d$PULL" == "d" ]]; then 41 | echo "Usage: $0 pullnumber [branch]" >&2 42 | exit 2 43 | fi 44 | 45 | if [[ "d$2" != "d" ]]; then 46 | BRANCH="$2" 47 | fi 48 | 49 | # Initialize source branches. 50 | git checkout -q "$BRANCH" 51 | if git fetch -q "$HOST":"$REPO" "+refs/pull/$PULL/*:refs/heads/pull/$PULL/*"; then 52 | if ! git log -q -1 "refs/heads/pull/$PULL/head" >/dev/null 2>&1; then 53 | echo "ERROR: Cannot find head of pull request #$PULL on $HOST:$REPO." >&2 54 | exit 3 55 | fi 56 | if ! git log -q -1 "refs/heads/pull/$PULL/merge" >/dev/null 2>&1; then 57 | echo "ERROR: Cannot find merge of pull request #$PULL on $HOST:$REPO." >&2 58 | exit 3 59 | fi 60 | else 61 | echo "ERROR: Cannot find pull request #$PULL on $HOST:$REPO." >&2 62 | exit 3 63 | fi 64 | if git fetch -q "$HOST":"$REPO" +refs/heads/"$BRANCH":refs/heads/pull/"$PULL"/base; then 65 | true 66 | else 67 | echo "ERROR: Cannot find branch $BRANCH on $HOST:$REPO." >&2 68 | exit 3 69 | fi 70 | git checkout -q pull/"$PULL"/base 71 | git branch -q -D pull/"$PULL"/local-merge 2>/dev/null 72 | git checkout -q -b pull/"$PULL"/local-merge 73 | TMPDIR="$(mktemp -d -t ghmXXXXX)" 74 | 75 | function cleanup() { 76 | git checkout -q "$BRANCH" 77 | git branch -q -D pull/"$PULL"/head 2>/dev/null 78 | git branch -q -D pull/"$PULL"/base 2>/dev/null 79 | git branch -q -D pull/"$PULL"/merge 2>/dev/null 80 | git branch -q -D pull/"$PULL"/local-merge 2>/dev/null 81 | rm -rf "$TMPDIR" 82 | } 83 | 84 | # Create unsigned merge commit. 85 | ( 86 | echo "Merge pull request #$PULL" 87 | echo "" 88 | git log --no-merges --topo-order --pretty='format:%h %s (%an)' pull/"$PULL"/base..pull/"$PULL"/head 89 | )>"$TMPDIR/message" 90 | if git merge -q --commit --no-edit --no-ff -m "$(<"$TMPDIR/message")" pull/"$PULL"/head; then 91 | if [ "d$(git log --pretty='format:%s' -n 1)" != "dMerge pull request #$PULL" ]; then 92 | echo "ERROR: Creating merge failed (already merged?)." >&2 93 | cleanup 94 | exit 4 95 | fi 96 | else 97 | echo "ERROR: Cannot be merged cleanly." >&2 98 | git merge --abort 99 | cleanup 100 | exit 4 101 | fi 102 | 103 | # Run test command if configured. 104 | if [[ "d$TESTCMD" != "d" ]]; then 105 | # Go up to the repository's root. 106 | while [ ! -d .git ]; do cd ..; done 107 | if ! $TESTCMD; then 108 | echo "ERROR: Running $TESTCMD failed." >&2 109 | cleanup 110 | exit 5 111 | fi 112 | # Show the created merge. 113 | git diff pull/"$PULL"/merge..pull/"$PULL"/local-merge >"$TMPDIR"/diff 114 | git diff pull/"$PULL"/base..pull/"$PULL"/local-merge 115 | if [[ "$(<"$TMPDIR"/diff)" != "" ]]; then 116 | echo "WARNING: merge differs from github!" >&2 117 | read -p "Type 'ignore' to continue. " -r >&2 118 | if [[ "d$REPLY" =~ ^d[iI][gG][nN][oO][rR][eE]$ ]]; then 119 | echo "Difference with github ignored." >&2 120 | else 121 | cleanup 122 | exit 6 123 | fi 124 | fi 125 | read -p "Press 'd' to accept the diff. " -n 1 -r >&2 126 | echo 127 | if [[ "d$REPLY" =~ ^d[dD]$ ]]; then 128 | echo "Diff accepted." >&2 129 | else 130 | echo "ERROR: Diff rejected." >&2 131 | cleanup 132 | exit 6 133 | fi 134 | else 135 | # Verify the result. 136 | echo "Dropping you on a shell so you can try building/testing the merged source." >&2 137 | echo "Run 'git diff HEAD~' to show the changes being merged." >&2 138 | echo "Type 'exit' when done." >&2 139 | if [[ -f /etc/debian_version ]]; then # Show pull number in prompt on Debian default prompt 140 | export debian_chroot="$PULL" 141 | fi 142 | bash -i 143 | read -p "Press 'm' to accept the merge. " -n 1 -r >&2 144 | echo 145 | if [[ "d$REPLY" =~ ^d[Mm]$ ]]; then 146 | echo "Merge accepted." >&2 147 | else 148 | echo "ERROR: Merge rejected." >&2 149 | cleanup 150 | exit 7 151 | fi 152 | fi 153 | 154 | # Sign the merge commit. 155 | read -p "Press 's' to sign off on the merge. " -n 1 -r >&2 156 | echo 157 | if [[ "d$REPLY" =~ ^d[Ss]$ ]]; then 158 | if [[ "$(git config --get user.signingkey)" == "" ]]; then 159 | echo "ERROR: No GPG signing key set, not signing. Set one using:" >&2 160 | echo "git config --global user.signingkey " >&2 161 | cleanup 162 | exit 1 163 | else 164 | if ! git commit -q --gpg-sign --amend --no-edit; then 165 | echo "Error signing, exiting." 166 | cleanup 167 | exit 1 168 | fi 169 | fi 170 | else 171 | echo "Not signing off on merge, exiting." 172 | cleanup 173 | exit 1 174 | fi 175 | 176 | # Clean up temporary branches, and put the result in $BRANCH. 177 | git checkout -q "$BRANCH" 178 | git reset -q --hard pull/"$PULL"/local-merge 179 | cleanup 180 | 181 | # Push the result. 182 | read -p "Type 'push' to push the result to $HOST:$REPO, branch $BRANCH. " -r >&2 183 | if [[ "d$REPLY" =~ ^d[Pp][Uu][Ss][Hh]$ ]]; then 184 | git push "$HOST":"$REPO" refs/heads/"$BRANCH" 185 | fi 186 | -------------------------------------------------------------------------------- /src/secp256k1/src/field.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2013, 2014 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_FIELD_ 8 | #define _SECP256K1_FIELD_ 9 | 10 | /** Field element module. 11 | * 12 | * Field elements can be represented in several ways, but code accessing 13 | * it (and implementations) need to take certain properaties into account: 14 | * - Each field element can be normalized or not. 15 | * - Each field element has a magnitude, which represents how far away 16 | * its representation is away from normalization. Normalized elements 17 | * always have a magnitude of 1, but a magnitude of 1 doesn't imply 18 | * normality. 19 | */ 20 | 21 | #if defined HAVE_CONFIG_H 22 | #include "libsecp256k1-config.h" 23 | #endif 24 | 25 | #if defined(USE_FIELD_10X26) 26 | #include "field_10x26.h" 27 | #elif defined(USE_FIELD_5X52) 28 | #include "field_5x52.h" 29 | #else 30 | #error "Please select field implementation" 31 | #endif 32 | 33 | /** Normalize a field element. */ 34 | static void secp256k1_fe_normalize(secp256k1_fe *r); 35 | 36 | /** Weakly normalize a field element: reduce it magnitude to 1, but don't fully normalize. */ 37 | static void secp256k1_fe_normalize_weak(secp256k1_fe *r); 38 | 39 | /** Normalize a field element, without constant-time guarantee. */ 40 | static void secp256k1_fe_normalize_var(secp256k1_fe *r); 41 | 42 | /** Verify whether a field element represents zero i.e. would normalize to a zero value. The field 43 | * implementation may optionally normalize the input, but this should not be relied upon. */ 44 | static int secp256k1_fe_normalizes_to_zero(secp256k1_fe *r); 45 | 46 | /** Verify whether a field element represents zero i.e. would normalize to a zero value. The field 47 | * implementation may optionally normalize the input, but this should not be relied upon. */ 48 | static int secp256k1_fe_normalizes_to_zero_var(secp256k1_fe *r); 49 | 50 | /** Set a field element equal to a small integer. Resulting field element is normalized. */ 51 | static void secp256k1_fe_set_int(secp256k1_fe *r, int a); 52 | 53 | /** Verify whether a field element is zero. Requires the input to be normalized. */ 54 | static int secp256k1_fe_is_zero(const secp256k1_fe *a); 55 | 56 | /** Check the "oddness" of a field element. Requires the input to be normalized. */ 57 | static int secp256k1_fe_is_odd(const secp256k1_fe *a); 58 | 59 | /** Compare two field elements. Requires magnitude-1 inputs. */ 60 | static int secp256k1_fe_equal_var(const secp256k1_fe *a, const secp256k1_fe *b); 61 | 62 | /** Compare two field elements. Requires both inputs to be normalized */ 63 | static int secp256k1_fe_cmp_var(const secp256k1_fe *a, const secp256k1_fe *b); 64 | 65 | /** Set a field element equal to 32-byte big endian value. If successful, the resulting field element is normalized. */ 66 | static int secp256k1_fe_set_b32(secp256k1_fe *r, const unsigned char *a); 67 | 68 | /** Convert a field element to a 32-byte big endian value. Requires the input to be normalized */ 69 | static void secp256k1_fe_get_b32(unsigned char *r, const secp256k1_fe *a); 70 | 71 | /** Set a field element equal to the additive inverse of another. Takes a maximum magnitude of the input 72 | * as an argument. The magnitude of the output is one higher. */ 73 | static void secp256k1_fe_negate(secp256k1_fe *r, const secp256k1_fe *a, int m); 74 | 75 | /** Multiplies the passed field element with a small integer constant. Multiplies the magnitude by that 76 | * small integer. */ 77 | static void secp256k1_fe_mul_int(secp256k1_fe *r, int a); 78 | 79 | /** Adds a field element to another. The result has the sum of the inputs' magnitudes as magnitude. */ 80 | static void secp256k1_fe_add(secp256k1_fe *r, const secp256k1_fe *a); 81 | 82 | /** Sets a field element to be the product of two others. Requires the inputs' magnitudes to be at most 8. 83 | * The output magnitude is 1 (but not guaranteed to be normalized). */ 84 | static void secp256k1_fe_mul(secp256k1_fe *r, const secp256k1_fe *a, const secp256k1_fe * SECP256K1_RESTRICT b); 85 | 86 | /** Sets a field element to be the square of another. Requires the input's magnitude to be at most 8. 87 | * The output magnitude is 1 (but not guaranteed to be normalized). */ 88 | static void secp256k1_fe_sqr(secp256k1_fe *r, const secp256k1_fe *a); 89 | 90 | /** Sets a field element to be the (modular) square root (if any exist) of another. Requires the 91 | * input's magnitude to be at most 8. The output magnitude is 1 (but not guaranteed to be 92 | * normalized). Return value indicates whether a square root was found. */ 93 | static int secp256k1_fe_sqrt_var(secp256k1_fe *r, const secp256k1_fe *a); 94 | 95 | /** Sets a field element to be the (modular) inverse of another. Requires the input's magnitude to be 96 | * at most 8. The output magnitude is 1 (but not guaranteed to be normalized). */ 97 | static void secp256k1_fe_inv(secp256k1_fe *r, const secp256k1_fe *a); 98 | 99 | /** Potentially faster version of secp256k1_fe_inv, without constant-time guarantee. */ 100 | static void secp256k1_fe_inv_var(secp256k1_fe *r, const secp256k1_fe *a); 101 | 102 | /** Calculate the (modular) inverses of a batch of field elements. Requires the inputs' magnitudes to be 103 | * at most 8. The output magnitudes are 1 (but not guaranteed to be normalized). The inputs and 104 | * outputs must not overlap in memory. */ 105 | static void secp256k1_fe_inv_all_var(size_t len, secp256k1_fe *r, const secp256k1_fe *a); 106 | 107 | /** Convert a field element to the storage type. */ 108 | static void secp256k1_fe_to_storage(secp256k1_fe_storage *r, const secp256k1_fe *a); 109 | 110 | /** Convert a field element back from the storage type. */ 111 | static void secp256k1_fe_from_storage(secp256k1_fe *r, const secp256k1_fe_storage *a); 112 | 113 | /** If flag is true, set *r equal to *a; otherwise leave it. Constant-time. */ 114 | static void secp256k1_fe_storage_cmov(secp256k1_fe_storage *r, const secp256k1_fe_storage *a, int flag); 115 | 116 | /** If flag is true, set *r equal to *a; otherwise leave it. Constant-time. */ 117 | static void secp256k1_fe_cmov(secp256k1_fe *r, const secp256k1_fe *a, int flag); 118 | 119 | #endif 120 | -------------------------------------------------------------------------------- /src/secp256k1/src/modules/recovery/main_impl.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2013-2015 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef _SECP256K1_MODULE_RECOVERY_MAIN_ 8 | #define _SECP256K1_MODULE_RECOVERY_MAIN_ 9 | 10 | #include "include/secp256k1_recovery.h" 11 | 12 | static void secp256k1_ecdsa_recoverable_signature_load(const secp256k1_context* ctx, secp256k1_scalar* r, secp256k1_scalar* s, int* recid, const secp256k1_ecdsa_recoverable_signature* sig) { 13 | (void)ctx; 14 | if (sizeof(secp256k1_scalar) == 32) { 15 | /* When the secp256k1_scalar type is exactly 32 byte, use its 16 | * representation inside secp256k1_ecdsa_signature, as conversion is very fast. 17 | * Note that secp256k1_ecdsa_signature_save must use the same representation. */ 18 | memcpy(r, &sig->data[0], 32); 19 | memcpy(s, &sig->data[32], 32); 20 | } else { 21 | secp256k1_scalar_set_b32(r, &sig->data[0], NULL); 22 | secp256k1_scalar_set_b32(s, &sig->data[32], NULL); 23 | } 24 | *recid = sig->data[64]; 25 | } 26 | 27 | static void secp256k1_ecdsa_recoverable_signature_save(secp256k1_ecdsa_recoverable_signature* sig, const secp256k1_scalar* r, const secp256k1_scalar* s, int recid) { 28 | if (sizeof(secp256k1_scalar) == 32) { 29 | memcpy(&sig->data[0], r, 32); 30 | memcpy(&sig->data[32], s, 32); 31 | } else { 32 | secp256k1_scalar_get_b32(&sig->data[0], r); 33 | secp256k1_scalar_get_b32(&sig->data[32], s); 34 | } 35 | sig->data[64] = recid; 36 | } 37 | 38 | int secp256k1_ecdsa_recoverable_signature_parse_compact(const secp256k1_context* ctx, secp256k1_ecdsa_recoverable_signature* sig, const unsigned char *input64, int recid) { 39 | secp256k1_scalar r, s; 40 | int ret = 1; 41 | int overflow = 0; 42 | 43 | (void)ctx; 44 | ARG_CHECK(sig != NULL); 45 | ARG_CHECK(input64 != NULL); 46 | ARG_CHECK(recid >= 0 && recid <= 3); 47 | 48 | secp256k1_scalar_set_b32(&r, &input64[0], &overflow); 49 | ret &= !overflow; 50 | secp256k1_scalar_set_b32(&s, &input64[32], &overflow); 51 | ret &= !overflow; 52 | if (ret) { 53 | secp256k1_ecdsa_recoverable_signature_save(sig, &r, &s, recid); 54 | } else { 55 | memset(sig, 0, sizeof(*sig)); 56 | } 57 | return ret; 58 | } 59 | 60 | int secp256k1_ecdsa_recoverable_signature_serialize_compact(const secp256k1_context* ctx, unsigned char *output64, int *recid, const secp256k1_ecdsa_recoverable_signature* sig) { 61 | secp256k1_scalar r, s; 62 | 63 | (void)ctx; 64 | ARG_CHECK(output64 != NULL); 65 | ARG_CHECK(sig != NULL); 66 | 67 | secp256k1_ecdsa_recoverable_signature_load(ctx, &r, &s, recid, sig); 68 | secp256k1_scalar_get_b32(&output64[0], &r); 69 | secp256k1_scalar_get_b32(&output64[32], &s); 70 | return 1; 71 | } 72 | 73 | int secp256k1_ecdsa_recoverable_signature_convert(const secp256k1_context* ctx, secp256k1_ecdsa_signature* sig, const secp256k1_ecdsa_recoverable_signature* sigin) { 74 | secp256k1_scalar r, s; 75 | int recid; 76 | 77 | (void)ctx; 78 | ARG_CHECK(sig != NULL); 79 | ARG_CHECK(sigin != NULL); 80 | 81 | secp256k1_ecdsa_recoverable_signature_load(ctx, &r, &s, &recid, sigin); 82 | secp256k1_ecdsa_signature_save(sig, &r, &s); 83 | return 1; 84 | } 85 | 86 | int secp256k1_ecdsa_sign_recoverable(const secp256k1_context* ctx, secp256k1_ecdsa_recoverable_signature *signature, const unsigned char *msg32, const unsigned char *seckey, secp256k1_nonce_function noncefp, const void* noncedata) { 87 | secp256k1_scalar r, s; 88 | secp256k1_scalar sec, non, msg; 89 | int recid; 90 | int ret = 0; 91 | int overflow = 0; 92 | VERIFY_CHECK(ctx != NULL); 93 | ARG_CHECK(secp256k1_ecmult_gen_context_is_built(&ctx->ecmult_gen_ctx)); 94 | ARG_CHECK(msg32 != NULL); 95 | ARG_CHECK(signature != NULL); 96 | ARG_CHECK(seckey != NULL); 97 | if (noncefp == NULL) { 98 | noncefp = secp256k1_nonce_function_default; 99 | } 100 | 101 | secp256k1_scalar_set_b32(&sec, seckey, &overflow); 102 | /* Fail if the secret key is invalid. */ 103 | if (!overflow && !secp256k1_scalar_is_zero(&sec)) { 104 | unsigned int count = 0; 105 | secp256k1_scalar_set_b32(&msg, msg32, NULL); 106 | while (1) { 107 | unsigned char nonce32[32]; 108 | ret = noncefp(nonce32, seckey, msg32, NULL, (void*)noncedata, count); 109 | if (!ret) { 110 | break; 111 | } 112 | secp256k1_scalar_set_b32(&non, nonce32, &overflow); 113 | memset(nonce32, 0, 32); 114 | if (!secp256k1_scalar_is_zero(&non) && !overflow) { 115 | if (secp256k1_ecdsa_sig_sign(&ctx->ecmult_gen_ctx, &r, &s, &sec, &msg, &non, &recid)) { 116 | break; 117 | } 118 | } 119 | count++; 120 | } 121 | secp256k1_scalar_clear(&msg); 122 | secp256k1_scalar_clear(&non); 123 | secp256k1_scalar_clear(&sec); 124 | } 125 | if (ret) { 126 | secp256k1_ecdsa_recoverable_signature_save(signature, &r, &s, recid); 127 | } else { 128 | memset(signature, 0, sizeof(*signature)); 129 | } 130 | return ret; 131 | } 132 | 133 | int secp256k1_ecdsa_recover(const secp256k1_context* ctx, secp256k1_pubkey *pubkey, const secp256k1_ecdsa_recoverable_signature *signature, const unsigned char *msg32) { 134 | secp256k1_ge q; 135 | secp256k1_scalar r, s; 136 | secp256k1_scalar m; 137 | int recid; 138 | VERIFY_CHECK(ctx != NULL); 139 | ARG_CHECK(secp256k1_ecmult_context_is_built(&ctx->ecmult_ctx)); 140 | ARG_CHECK(msg32 != NULL); 141 | ARG_CHECK(signature != NULL); 142 | ARG_CHECK(pubkey != NULL); 143 | 144 | secp256k1_ecdsa_recoverable_signature_load(ctx, &r, &s, &recid, signature); 145 | ARG_CHECK(recid >= 0 && recid < 4); 146 | secp256k1_scalar_set_b32(&m, msg32, NULL); 147 | if (secp256k1_ecdsa_sig_recover(&ctx->ecmult_ctx, &r, &s, &q, &m, recid)) { 148 | secp256k1_pubkey_save(pubkey, &q); 149 | return 1; 150 | } else { 151 | memset(pubkey, 0, sizeof(*pubkey)); 152 | return 0; 153 | } 154 | } 155 | 156 | #endif 157 | -------------------------------------------------------------------------------- /src/aes.h: -------------------------------------------------------------------------------- 1 | /* 2 | --------------------------------------------------------------------------- 3 | Copyright (c) 1998-2008, Brian Gladman, Worcester, UK. All rights reserved. 4 | 5 | LICENSE TERMS 6 | 7 | The redistribution and use of this software (with or without changes) 8 | is allowed without the payment of fees or royalties provided that: 9 | 10 | 1. source code distributions include the above copyright notice, this 11 | list of conditions and the following disclaimer; 12 | 13 | 2. binary distributions include the above copyright notice, this list 14 | of conditions and the following disclaimer in their documentation; 15 | 16 | 3. the name of the copyright holder is not used to endorse products 17 | built using this software without specific written permission. 18 | 19 | DISCLAIMER 20 | 21 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 22 | * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 23 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 24 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES 25 | * OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 26 | * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 27 | * OTHER DEALINGS IN THE SOFTWARE. 28 | 29 | --------------------------------------------------------------------------- 30 | Issue 09/09/2006 31 | 32 | This is an AES implementation that uses only 8-bit byte operations on the 33 | cipher state. 34 | */ 35 | 36 | #ifndef AES_H 37 | #define AES_H 38 | 39 | #if 1 40 | # define AES_ENC_PREKEYED /* AES encryption with a precomputed key schedule */ 41 | #endif 42 | #if 1 43 | # define AES_DEC_PREKEYED /* AES decryption with a precomputed key schedule */ 44 | #endif 45 | #if 0 46 | # define AES_ENC_128_OTFK /* AES encryption with 'on the fly' 128 bit keying */ 47 | #endif 48 | #if 0 49 | # define AES_DEC_128_OTFK /* AES decryption with 'on the fly' 128 bit keying */ 50 | #endif 51 | #if 0 52 | # define AES_ENC_256_OTFK /* AES encryption with 'on the fly' 256 bit keying */ 53 | #endif 54 | #if 0 55 | # define AES_DEC_256_OTFK /* AES decryption with 'on the fly' 256 bit keying */ 56 | #endif 57 | 58 | #define N_ROW 4 59 | #define N_COL 4 60 | #define N_BLOCK (N_ROW * N_COL) 61 | #define N_MAX_ROUNDS 14 62 | 63 | typedef unsigned char uint_8t; 64 | 65 | typedef uint_8t return_type; 66 | 67 | /* Warning: The key length for 256 bit keys overflows a byte 68 | (see comment below) 69 | */ 70 | 71 | typedef uint_8t length_type; 72 | 73 | typedef struct { 74 | uint_8t ksch[(N_MAX_ROUNDS + 1) * N_BLOCK]; 75 | uint_8t rnd; 76 | } aes_context; 77 | 78 | /* The following calls are for a precomputed key schedule 79 | 80 | NOTE: If the length_type used for the key length is an 81 | unsigned 8-bit character, a key length of 256 bits must 82 | be entered as a length in bytes (valid inputs are hence 83 | 128, 192, 16, 24 and 32). 84 | */ 85 | 86 | #if defined( AES_ENC_PREKEYED ) || defined( AES_DEC_PREKEYED ) 87 | 88 | return_type aes_set_key( const unsigned char key[], 89 | length_type keylen, 90 | aes_context ctx[1] ); 91 | #endif 92 | 93 | #if defined( AES_ENC_PREKEYED ) 94 | 95 | return_type aes_encrypt( const unsigned char in[N_BLOCK], 96 | unsigned char out[N_BLOCK], 97 | const aes_context ctx[1] ); 98 | 99 | return_type aes_cbc_encrypt( const unsigned char *in, 100 | unsigned char *out, 101 | int n_block, 102 | unsigned char iv[N_BLOCK], 103 | const aes_context ctx[1] ); 104 | #endif 105 | 106 | #if defined( AES_DEC_PREKEYED ) 107 | 108 | return_type aes_decrypt( const unsigned char in[N_BLOCK], 109 | unsigned char out[N_BLOCK], 110 | const aes_context ctx[1] ); 111 | 112 | return_type aes_cbc_decrypt( const unsigned char *in, 113 | unsigned char *out, 114 | int n_block, 115 | unsigned char iv[N_BLOCK], 116 | const aes_context ctx[1] ); 117 | #endif 118 | 119 | /* The following calls are for 'on the fly' keying. In this case the 120 | encryption and decryption keys are different. 121 | 122 | The encryption subroutines take a key in an array of bytes in 123 | key[L] where L is 16, 24 or 32 bytes for key lengths of 128, 124 | 192, and 256 bits respectively. They then encrypts the input 125 | data, in[] with this key and put the reult in the output array 126 | out[]. In addition, the second key array, o_key[L], is used 127 | to output the key that is needed by the decryption subroutine 128 | to reverse the encryption operation. The two key arrays can 129 | be the same array but in this case the original key will be 130 | overwritten. 131 | 132 | In the same way, the decryption subroutines output keys that 133 | can be used to reverse their effect when used for encryption. 134 | 135 | Only 128 and 256 bit keys are supported in these 'on the fly' 136 | modes. 137 | */ 138 | 139 | #if defined( AES_ENC_128_OTFK ) 140 | void aes_encrypt_128( const unsigned char in[N_BLOCK], 141 | unsigned char out[N_BLOCK], 142 | const unsigned char key[N_BLOCK], 143 | uint_8t o_key[N_BLOCK] ); 144 | #endif 145 | 146 | #if defined( AES_DEC_128_OTFK ) 147 | void aes_decrypt_128( const unsigned char in[N_BLOCK], 148 | unsigned char out[N_BLOCK], 149 | const unsigned char key[N_BLOCK], 150 | unsigned char o_key[N_BLOCK] ); 151 | #endif 152 | 153 | #if defined( AES_ENC_256_OTFK ) 154 | void aes_encrypt_256( const unsigned char in[N_BLOCK], 155 | unsigned char out[N_BLOCK], 156 | const unsigned char key[2 * N_BLOCK], 157 | unsigned char o_key[2 * N_BLOCK] ); 158 | #endif 159 | 160 | #if defined( AES_DEC_256_OTFK ) 161 | void aes_decrypt_256( const unsigned char in[N_BLOCK], 162 | unsigned char out[N_BLOCK], 163 | const unsigned char key[2 * N_BLOCK], 164 | unsigned char o_key[2 * N_BLOCK] ); 165 | #endif 166 | 167 | 168 | #endif 169 | -------------------------------------------------------------------------------- /src/secp256k1/src/modules/schnorr/main_impl.h: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Copyright (c) 2014-2015 Pieter Wuille * 3 | * Distributed under the MIT software license, see the accompanying * 4 | * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 | **********************************************************************/ 6 | 7 | #ifndef SECP256K1_MODULE_SCHNORR_MAIN 8 | #define SECP256K1_MODULE_SCHNORR_MAIN 9 | 10 | #include "include/secp256k1_schnorr.h" 11 | #include "modules/schnorr/schnorr_impl.h" 12 | 13 | static void secp256k1_schnorr_msghash_sha256(unsigned char *h32, const unsigned char *r32, const unsigned char *msg32) { 14 | secp256k1_sha256_t sha; 15 | secp256k1_sha256_initialize(&sha); 16 | secp256k1_sha256_write(&sha, r32, 32); 17 | secp256k1_sha256_write(&sha, msg32, 32); 18 | secp256k1_sha256_finalize(&sha, h32); 19 | } 20 | 21 | static const unsigned char secp256k1_schnorr_algo16[17] = "Schnorr+SHA256 "; 22 | 23 | int secp256k1_schnorr_sign(const secp256k1_context* ctx, unsigned char *sig64, const unsigned char *msg32, const unsigned char *seckey, secp256k1_nonce_function noncefp, const void* noncedata) { 24 | secp256k1_scalar sec, non; 25 | int ret = 0; 26 | int overflow = 0; 27 | unsigned int count = 0; 28 | VERIFY_CHECK(ctx != NULL); 29 | ARG_CHECK(secp256k1_ecmult_gen_context_is_built(&ctx->ecmult_gen_ctx)); 30 | ARG_CHECK(msg32 != NULL); 31 | ARG_CHECK(sig64 != NULL); 32 | ARG_CHECK(seckey != NULL); 33 | if (noncefp == NULL) { 34 | noncefp = secp256k1_nonce_function_default; 35 | } 36 | 37 | secp256k1_scalar_set_b32(&sec, seckey, NULL); 38 | while (1) { 39 | unsigned char nonce32[32]; 40 | ret = noncefp(nonce32, msg32, seckey, secp256k1_schnorr_algo16, (void*)noncedata, count); 41 | if (!ret) { 42 | break; 43 | } 44 | secp256k1_scalar_set_b32(&non, nonce32, &overflow); 45 | memset(nonce32, 0, 32); 46 | if (!secp256k1_scalar_is_zero(&non) && !overflow) { 47 | if (secp256k1_schnorr_sig_sign(&ctx->ecmult_gen_ctx, sig64, &sec, &non, NULL, secp256k1_schnorr_msghash_sha256, msg32)) { 48 | break; 49 | } 50 | } 51 | count++; 52 | } 53 | if (!ret) { 54 | memset(sig64, 0, 64); 55 | } 56 | secp256k1_scalar_clear(&non); 57 | secp256k1_scalar_clear(&sec); 58 | return ret; 59 | } 60 | 61 | int secp256k1_schnorr_verify(const secp256k1_context* ctx, const unsigned char *sig64, const unsigned char *msg32, const secp256k1_pubkey *pubkey) { 62 | secp256k1_ge q; 63 | VERIFY_CHECK(ctx != NULL); 64 | ARG_CHECK(secp256k1_ecmult_context_is_built(&ctx->ecmult_ctx)); 65 | ARG_CHECK(msg32 != NULL); 66 | ARG_CHECK(sig64 != NULL); 67 | ARG_CHECK(pubkey != NULL); 68 | 69 | secp256k1_pubkey_load(ctx, &q, pubkey); 70 | return secp256k1_schnorr_sig_verify(&ctx->ecmult_ctx, sig64, &q, secp256k1_schnorr_msghash_sha256, msg32); 71 | } 72 | 73 | int secp256k1_schnorr_recover(const secp256k1_context* ctx, secp256k1_pubkey *pubkey, const unsigned char *sig64, const unsigned char *msg32) { 74 | secp256k1_ge q; 75 | 76 | VERIFY_CHECK(ctx != NULL); 77 | ARG_CHECK(secp256k1_ecmult_context_is_built(&ctx->ecmult_ctx)); 78 | ARG_CHECK(msg32 != NULL); 79 | ARG_CHECK(sig64 != NULL); 80 | ARG_CHECK(pubkey != NULL); 81 | 82 | if (secp256k1_schnorr_sig_recover(&ctx->ecmult_ctx, sig64, &q, secp256k1_schnorr_msghash_sha256, msg32)) { 83 | secp256k1_pubkey_save(pubkey, &q); 84 | return 1; 85 | } else { 86 | memset(pubkey, 0, sizeof(*pubkey)); 87 | return 0; 88 | } 89 | } 90 | 91 | int secp256k1_schnorr_generate_nonce_pair(const secp256k1_context* ctx, secp256k1_pubkey *pubnonce, unsigned char *privnonce32, const unsigned char *sec32, const unsigned char *msg32, secp256k1_nonce_function noncefp, const void* noncedata) { 92 | int count = 0; 93 | int ret = 1; 94 | secp256k1_gej Qj; 95 | secp256k1_ge Q; 96 | secp256k1_scalar sec; 97 | 98 | VERIFY_CHECK(ctx != NULL); 99 | ARG_CHECK(secp256k1_ecmult_gen_context_is_built(&ctx->ecmult_gen_ctx)); 100 | ARG_CHECK(msg32 != NULL); 101 | ARG_CHECK(sec32 != NULL); 102 | ARG_CHECK(pubnonce != NULL); 103 | ARG_CHECK(privnonce32 != NULL); 104 | 105 | if (noncefp == NULL) { 106 | noncefp = secp256k1_nonce_function_default; 107 | } 108 | 109 | do { 110 | int overflow; 111 | ret = noncefp(privnonce32, sec32, msg32, secp256k1_schnorr_algo16, (void*)noncedata, count++); 112 | if (!ret) { 113 | break; 114 | } 115 | secp256k1_scalar_set_b32(&sec, privnonce32, &overflow); 116 | if (overflow || secp256k1_scalar_is_zero(&sec)) { 117 | continue; 118 | } 119 | secp256k1_ecmult_gen(&ctx->ecmult_gen_ctx, &Qj, &sec); 120 | secp256k1_ge_set_gej(&Q, &Qj); 121 | 122 | secp256k1_pubkey_save(pubnonce, &Q); 123 | break; 124 | } while(1); 125 | 126 | secp256k1_scalar_clear(&sec); 127 | if (!ret) { 128 | memset(pubnonce, 0, sizeof(*pubnonce)); 129 | } 130 | return ret; 131 | } 132 | 133 | int secp256k1_schnorr_partial_sign(const secp256k1_context* ctx, unsigned char *sig64, const unsigned char *msg32, const unsigned char *sec32, const secp256k1_pubkey *pubnonce_others, const unsigned char *secnonce32) { 134 | int overflow = 0; 135 | secp256k1_scalar sec, non; 136 | secp256k1_ge pubnon; 137 | VERIFY_CHECK(ctx != NULL); 138 | ARG_CHECK(secp256k1_ecmult_gen_context_is_built(&ctx->ecmult_gen_ctx)); 139 | ARG_CHECK(msg32 != NULL); 140 | ARG_CHECK(sig64 != NULL); 141 | ARG_CHECK(sec32 != NULL); 142 | ARG_CHECK(secnonce32 != NULL); 143 | ARG_CHECK(pubnonce_others != NULL); 144 | 145 | secp256k1_scalar_set_b32(&sec, sec32, &overflow); 146 | if (overflow || secp256k1_scalar_is_zero(&sec)) { 147 | return -1; 148 | } 149 | secp256k1_scalar_set_b32(&non, secnonce32, &overflow); 150 | if (overflow || secp256k1_scalar_is_zero(&non)) { 151 | return -1; 152 | } 153 | secp256k1_pubkey_load(ctx, &pubnon, pubnonce_others); 154 | return secp256k1_schnorr_sig_sign(&ctx->ecmult_gen_ctx, sig64, &sec, &non, &pubnon, secp256k1_schnorr_msghash_sha256, msg32); 155 | } 156 | 157 | int secp256k1_schnorr_partial_combine(const secp256k1_context* ctx, unsigned char *sig64, const unsigned char * const *sig64sin, int n) { 158 | ARG_CHECK(sig64 != NULL); 159 | ARG_CHECK(n >= 1); 160 | ARG_CHECK(sig64sin != NULL); 161 | return secp256k1_schnorr_sig_combine(sig64, n, sig64sin); 162 | } 163 | 164 | #endif 165 | -------------------------------------------------------------------------------- /src/utils.c: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | The MIT License (MIT) 4 | 5 | Copyright (c) 2015 Douglas J. Bakkum 6 | Copyright (c) 2015 Jonas Schnelli 7 | 8 | Permission is hereby granted, free of charge, to any person obtaining 9 | a copy of this software and associated documentation files (the "Software"), 10 | to deal in the Software without restriction, including without limitation 11 | the rights to use, copy, modify, merge, publish, distribute, sublicense, 12 | and/or sell copies of the Software, and to permit persons to whom the 13 | Software is furnished to do so, subject to the following conditions: 14 | 15 | The above copyright notice and this permission notice shall be included 16 | in all copies or substantial portions of the Software. 17 | 18 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 19 | OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 21 | THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES 22 | OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 23 | ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 24 | OTHER DEALINGS IN THE SOFTWARE. 25 | 26 | */ 27 | 28 | #include 29 | #include 30 | #include 31 | #include 32 | 33 | #include "utils.h" 34 | 35 | 36 | static uint8_t buffer_hex_to_uint8[TO_UINT8_HEX_BUF_LEN]; 37 | static char buffer_uint8_to_hex[TO_UINT8_HEX_BUF_LEN]; 38 | 39 | 40 | void utils_clear_buffers(void) 41 | { 42 | memset(buffer_hex_to_uint8, 0, TO_UINT8_HEX_BUF_LEN); 43 | memset(buffer_uint8_to_hex, 0, TO_UINT8_HEX_BUF_LEN); 44 | } 45 | 46 | void utils_hex_to_bin(const char *str, unsigned char *out, int inLen, int *outLen) 47 | { 48 | int bLen = inLen / 2; 49 | memset(out, 0, bLen); 50 | uint8_t c; 51 | int i; 52 | for (i = 0; i < bLen; i++) { 53 | c = 0; 54 | if (str[i * 2] >= '0' && str[i * 2] <= '9') { 55 | *out = (str[i * 2] - '0') << 4; 56 | } 57 | if (str[i * 2] >= 'a' && str[i * 2] <= 'f') { 58 | *out = (10 + str[i * 2] - 'a') << 4; 59 | } 60 | if (str[i * 2] >= 'A' && str[i * 2] <= 'F') { 61 | *out = (10 + str[i * 2] - 'A') << 4; 62 | } 63 | if (str[i * 2 + 1] >= '0' && str[i * 2 + 1] <= '9') { 64 | *out |= (str[i * 2 + 1] - '0'); 65 | } 66 | if (str[i * 2 + 1] >= 'a' && str[i * 2 + 1] <= 'f') { 67 | *out |= (10 + str[i * 2 + 1] - 'a'); 68 | } 69 | if (str[i * 2 + 1] >= 'A' && str[i * 2 + 1] <= 'F') { 70 | *out |= (10 + str[i * 2 + 1] - 'A'); 71 | } 72 | out++; 73 | } 74 | *outLen = i; 75 | } 76 | 77 | uint8_t *utils_hex_to_uint8(const char *str) 78 | { 79 | if (strlens(str) > TO_UINT8_HEX_BUF_LEN) { 80 | return NULL; 81 | } 82 | memset(buffer_hex_to_uint8, 0, TO_UINT8_HEX_BUF_LEN); 83 | uint8_t c; 84 | size_t i; 85 | for (i = 0; i < strlens(str) / 2; i++) { 86 | c = 0; 87 | if (str[i * 2] >= '0' && str[i * 2] <= '9') { 88 | c += (str[i * 2] - '0') << 4; 89 | } 90 | if (str[i * 2] >= 'a' && str[i * 2] <= 'f') { 91 | c += (10 + str[i * 2] - 'a') << 4; 92 | } 93 | if (str[i * 2] >= 'A' && str[i * 2] <= 'F') { 94 | c += (10 + str[i * 2] - 'A') << 4; 95 | } 96 | if (str[i * 2 + 1] >= '0' && str[i * 2 + 1] <= '9') { 97 | c += (str[i * 2 + 1] - '0'); 98 | } 99 | if (str[i * 2 + 1] >= 'a' && str[i * 2 + 1] <= 'f') { 100 | c += (10 + str[i * 2 + 1] - 'a'); 101 | } 102 | if (str[i * 2 + 1] >= 'A' && str[i * 2 + 1] <= 'F') { 103 | c += (10 + str[i * 2 + 1] - 'A'); 104 | } 105 | buffer_hex_to_uint8[i] = c; 106 | } 107 | return buffer_hex_to_uint8; 108 | } 109 | 110 | 111 | void utils_bin_to_hex(unsigned char *bin_in, size_t inlen, char *hex_out) 112 | { 113 | static char digits[] = "0123456789abcdef"; 114 | size_t i; 115 | for (i = 0; i < inlen; i++) { 116 | hex_out[i * 2] = digits[(bin_in[i] >> 4) & 0xF]; 117 | hex_out[i * 2 + 1] = digits[bin_in[i] & 0xF]; 118 | } 119 | hex_out[inlen * 2] = '\0'; 120 | } 121 | 122 | 123 | char *utils_uint8_to_hex(const uint8_t *bin, size_t l) 124 | { 125 | if (l > (TO_UINT8_HEX_BUF_LEN / 2 - 1)) { 126 | return NULL; 127 | } 128 | static char digits[] = "0123456789abcdef"; 129 | memset(buffer_uint8_to_hex, 0, TO_UINT8_HEX_BUF_LEN); 130 | size_t i; 131 | for (i = 0; i < l; i++) { 132 | buffer_uint8_to_hex[i * 2] = digits[(bin[i] >> 4) & 0xF]; 133 | buffer_uint8_to_hex[i * 2 + 1] = digits[bin[i] & 0xF]; 134 | } 135 | buffer_uint8_to_hex[l * 2] = '\0'; 136 | return buffer_uint8_to_hex; 137 | } 138 | 139 | 140 | void utils_reverse_hex(char *h, int len) 141 | { 142 | char copy[len]; 143 | strncpy(copy, h, len); 144 | int i; 145 | for (i = 0; i < len; i += 2) { 146 | h[i] = copy[len - i - 2]; 147 | h[i + 1] = copy[len - i - 1]; 148 | } 149 | } 150 | 151 | 152 | void utils_uint64_to_varint(char *vi, int *l, uint64_t i) 153 | { 154 | int len; 155 | char v[VARINT_LEN]; 156 | 157 | if (i < 0xfd) { 158 | sprintf(v, "%02" PRIx64 , i); 159 | len = 2; 160 | } else if (i <= 0xffff) { 161 | sprintf(v, "%04" PRIx64 , i); 162 | sprintf(vi, "fd"); 163 | len = 4; 164 | } else if (i <= 0xffffffff) { 165 | sprintf(v, "%08" PRIx64 , i); 166 | sprintf(vi, "fe"); 167 | len = 8; 168 | } else { 169 | sprintf(v, "%016" PRIx64 , i); 170 | sprintf(vi, "ff"); 171 | len = 16; 172 | } 173 | 174 | /* reverse order */ 175 | if (len > 2) { 176 | utils_reverse_hex(v, len); 177 | strncat(vi, v, len); 178 | } else { 179 | strncpy(vi, v, len); 180 | } 181 | 182 | *l = len; 183 | } 184 | 185 | 186 | int utils_varint_to_uint64(const char *vi, uint64_t *i) 187 | { 188 | char v[VARINT_LEN] = {0}; 189 | int len; 190 | 191 | if (!vi) { 192 | len = 0; 193 | } else if (!strncmp(vi, "ff", 2)) { 194 | len = 16; 195 | } else if (!strncmp(vi, "fe", 2)) { 196 | len = 8; 197 | } else if (!strncmp(vi, "fd", 2)) { 198 | len = 4; 199 | } else { 200 | len = 2; 201 | } 202 | 203 | if (len == 0) { 204 | /* continue */ 205 | } else if (len > 2) { 206 | strncpy(v, vi + 2, len); 207 | utils_reverse_hex(v, len); 208 | } else { 209 | strncpy(v, vi, len); 210 | } 211 | *i = strtoull(v, NULL, 16); 212 | 213 | return len; 214 | } 215 | 216 | --------------------------------------------------------------------------------