aboutsummaryrefslogtreecommitdiffstats
path: root/crypto/secp256k1/secp256.go
blob: 4284115e2d2678c8b1475262356b8d2d8b32ddd1 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
// Copyright 2015 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.

// Package secp256k1 wraps the bitcoin secp256k1 C library.
package secp256k1

/*
#cgo CFLAGS: -I./libsecp256k1
#cgo CFLAGS: -I./libsecp256k1/src/
#define USE_NUM_NONE
#define USE_FIELD_10X26
#define USE_FIELD_INV_BUILTIN
#define USE_SCALAR_8X32
#define USE_SCALAR_INV_BUILTIN
#define NDEBUG
#include "./libsecp256k1/src/secp256k1.c"
#include "./libsecp256k1/src/modules/recovery/main_impl.h"
#include "ext.h"

typedef void (*callbackFunc) (const char* msg, void* data);
extern void secp256k1GoPanicIllegal(const char* msg, void* data);
extern void secp256k1GoPanicError(const char* msg, void* data);
*/
import "C"

import (
    "errors"
    "math/big"
    "unsafe"
)

var (
    context *C.secp256k1_context
    N       *big.Int
    HalfN   *big.Int
)

func init() {
    N, _ = new(big.Int).SetString("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141", 16)
    // N / 2 == 57896044618658097711785492504343953926418782139537452191302581570759080747168
    HalfN, _ = new(big.Int).SetString("7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0", 16)

    // around 20 ms on a modern CPU.
    context = C.secp256k1_context_create_sign_verify()
    C.secp256k1_context_set_illegal_callback(context, C.callbackFunc(C.secp256k1GoPanicIllegal), nil)
    C.secp256k1_context_set_error_callback(context, C.callbackFunc(C.secp256k1GoPanicError), nil)
}

var (
    ErrInvalidMsgLen       = errors.New("invalid message length, need 32 bytes")
    ErrInvalidSignatureLen = errors.New("invalid signature length")
    ErrInvalidRecoveryID   = errors.New("invalid signature recovery id")
    ErrInvalidKey          = errors.New("invalid private key")
    ErrSignFailed          = errors.New("signing failed")
    ErrRecoverFailed       = errors.New("recovery failed")
)

// Sign creates a recoverable ECDSA signature.
// The produced signature is in the 65-byte [R || S || V] format where V is 0 or 1.
//
// The caller is responsible for ensuring that msg cannot be chosen
// directly by an attacker. It is usually preferable to use a cryptographic
// hash function on any input before handing it to this function.
func Sign(msg []byte, seckey []byte) ([]byte, error) {
    if len(msg) != 32 {
        return nil, ErrInvalidMsgLen
    }
    if len(seckey) != 32 {
        return nil, ErrInvalidKey
    }
    seckeydata := (*C.uchar)(unsafe.Pointer(&seckey[0]))
    if C.secp256k1_ec_seckey_verify(context, seckeydata) != 1 {
        return nil, ErrInvalidKey
    }

    var (
        msgdata   = (*C.uchar)(unsafe.Pointer(&msg[0]))
        noncefunc = C.secp256k1_nonce_function_rfc6979
        sigstruct C.secp256k1_ecdsa_recoverable_signature
    )
    if C.secp256k1_ecdsa_sign_recoverable(context, &sigstruct, msgdata, seckeydata, noncefunc, nil) == 0 {
        return nil, ErrSignFailed
    }

    var (
        sig     = make([]byte, 65)
        sigdata = (*C.uchar)(unsafe.Pointer(&sig[0]))
        recid   C.int
    )
    C.secp256k1_ecdsa_recoverable_signature_serialize_compact(context, sigdata, &recid, &sigstruct)
    sig[64] = byte(recid) // add back recid to get 65 bytes sig
    return sig, nil
}

// RecoverPubkey returns the the public key of the signer.
// msg must be the 32-byte hash of the message to be signed.
// sig must be a 65-byte compact ECDSA signature containing the
// recovery id as the last element.
func RecoverPubkey(msg []byte, sig []byte) ([]byte, error) {
    if len(msg) != 32 {
        return nil, ErrInvalidMsgLen
    }
    if err := checkSignature(sig); err != nil {
        return nil, err
    }

    var (
        pubkey  = make([]byte, 65)
        sigdata = (*C.uchar)(unsafe.Pointer(&sig[0]))
        msgdata = (*C.uchar)(unsafe.Pointer(&msg[0]))
    )
    if C.secp256k1_ecdsa_recover_pubkey(context, (*C.uchar)(unsafe.Pointer(&pubkey[0])), sigdata, msgdata) == 0 {
        return nil, ErrRecoverFailed
    }
    return pubkey, nil
}

func checkSignature(sig []byte) error {
    if len(sig) != 65 {
        return ErrInvalidSignatureLen
    }
    if sig[64] >= 4 {
        return ErrInvalidRecoveryID
    }
    return nil
}

// reads num into buf as big-endian bytes.
func readBits(buf []byte, num *big.Int) {
    const wordLen = int(unsafe.Sizeof(big.Word(0)))
    i := len(buf)
    for _, d := range num.Bits() {
        for j := 0; j < wordLen && i > 0; j++ {
            i--
            buf[i] = byte(d)
            d >>= 8
        }
    }
}