aboutsummaryrefslogtreecommitdiffstats
path: root/crypto/secp256k1/secp256.go
blob: a2104016a2b42b063ddd5baa6b898543abc807b2 (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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
// 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

// TODO: set USE_SCALAR_4X64 depending on platform?

/*
#cgo CFLAGS: -I./libsecp256k1
#cgo darwin CFLAGS: -I/usr/local/include -I/opt/pkg/include
#cgo freebsd CFLAGS: -I/usr/local/include
#cgo linux,arm CFLAGS: -I/usr/local/arm/include
#cgo LDFLAGS: -lgmp
#cgo darwin LDFLAGS: -L/usr/local/lib -L/opt/pkg/lib
#cgo freebsd LDFLAGS: -L/usr/local/lib
#cgo linux,arm LDFLAGS: -L/usr/local/arm/lib
#define USE_NUM_GMP
#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"
*/
import "C"

import (
    "bytes"
    "errors"
    "unsafe"

    "github.com/ethereum/go-ethereum/crypto/randentropy"
)

//#define USE_FIELD_5X64

/*
   TODO:
   > store private keys in buffer and shuffle (deters persistance on swap disc)
   > byte permutation (changing)
   > xor with chaning random block (to deter scanning memory for 0x63) (stream cipher?)
   > on disk: store keys in wallets
*/

// holds ptr to secp256k1_context_struct (see secp256k1/include/secp256k1.h)
var context *C.secp256k1_context

func init() {
    // around 20 ms on a modern CPU.
    context = C.secp256k1_context_create(3) // SECP256K1_START_SIGN | SECP256K1_START_VERIFY
}

func GenerateKeyPair() ([]byte, []byte) {
    var seckey []byte = randentropy.GetEntropyCSPRNG(32)
    var seckey_ptr *C.uchar = (*C.uchar)(unsafe.Pointer(&seckey[0]))

    var pubkey64 []byte = make([]byte, 64) // secp256k1_pubkey
    var pubkey65 []byte = make([]byte, 65) // 65 byte uncompressed pubkey
    pubkey64_ptr := (*C.secp256k1_pubkey)(unsafe.Pointer(&pubkey64[0]))
    pubkey65_ptr := (*C.uchar)(unsafe.Pointer(&pubkey65[0]))

    ret := C.secp256k1_ec_pubkey_create(
        context,
        pubkey64_ptr,
        seckey_ptr,
    )

    if ret != C.int(1) {
        return GenerateKeyPair() // invalid secret, try again
    }

    var output_len C.size_t

    C.secp256k1_ec_pubkey_serialize( // always returns 1
        context,
        pubkey65_ptr,
        &output_len,
        pubkey64_ptr,
        0, // SECP256K1_EC_COMPRESSED
    )

    return pubkey65, seckey
}

func GeneratePubKey(seckey []byte) ([]byte, error) {
    if err := VerifySeckeyValidity(seckey); err != nil {
        return nil, err
    }

    var pubkey []byte = make([]byte, 64)
    var pubkey_ptr *C.secp256k1_pubkey = (*C.secp256k1_pubkey)(unsafe.Pointer(&pubkey[0]))

    var seckey_ptr *C.uchar = (*C.uchar)(unsafe.Pointer(&seckey[0]))

    ret := C.secp256k1_ec_pubkey_create(
        context,
        pubkey_ptr,
        seckey_ptr,
    )

    if ret != C.int(1) {
        return nil, errors.New("Unable to generate pubkey from seckey")
    }

    return pubkey, nil
}

func Sign(msg []byte, seckey []byte) ([]byte, error) {
    msg_ptr := (*C.uchar)(unsafe.Pointer(&msg[0]))
    seckey_ptr := (*C.uchar)(unsafe.Pointer(&seckey[0]))

    sig := make([]byte, 65)
    sig_ptr := (*C.secp256k1_ecdsa_recoverable_signature)(unsafe.Pointer(&sig[0]))

    nonce := randentropy.GetEntropyCSPRNG(32)
    ndata_ptr := unsafe.Pointer(&nonce[0])

    noncefp_ptr := &(*C.secp256k1_nonce_function_default)

    if C.secp256k1_ec_seckey_verify(context, seckey_ptr) != C.int(1) {
        return nil, errors.New("Invalid secret key")
    }

    ret := C.secp256k1_ecdsa_sign_recoverable(
        context,
        sig_ptr,
        msg_ptr,
        seckey_ptr,
        noncefp_ptr,
        ndata_ptr,
    )

    if ret == C.int(0) {
        return Sign(msg, seckey) //invalid secret, try again
    }

    sig_serialized := make([]byte, 65)
    sig_serialized_ptr := (*C.uchar)(unsafe.Pointer(&sig_serialized[0]))
    var recid C.int

    C.secp256k1_ecdsa_recoverable_signature_serialize_compact(
        context,
        sig_serialized_ptr, // 64 byte compact signature
        &recid,
        sig_ptr, // 65 byte "recoverable" signature
    )

    sig_serialized[64] = byte(int(recid)) // add back recid to get 65 bytes sig

    return sig_serialized, nil

}

func VerifySeckeyValidity(seckey []byte) error {
    if len(seckey) != 32 {
        return errors.New("priv key is not 32 bytes")
    }
    var seckey_ptr *C.uchar = (*C.uchar)(unsafe.Pointer(&seckey[0]))
    ret := C.secp256k1_ec_seckey_verify(context, seckey_ptr)
    if int(ret) != 1 {
        return errors.New("invalid seckey")
    }
    return nil
}

func VerifySignatureValidity(sig []byte) bool {
    //64+1
    if len(sig) != 65 {
        return false
    }
    //malleability check, highest bit must be 1
    if (sig[32] & 0x80) == 0x80 {
        return false
    }
    //recovery id check
    if sig[64] >= 4 {
        return false
    }

    return true
}

//for compressed signatures, does not need pubkey
func VerifySignature(msg []byte, sig []byte, pubkey1 []byte) error {
    if msg == nil || sig == nil || pubkey1 == nil {
        return errors.New("inputs must be non-nil")
    }
    if len(sig) != 65 {
        return errors.New("invalid signature length")
    }
    if len(pubkey1) != 65 {
        return errors.New("Invalid public key length")
    }

    //to enforce malleability, highest bit of S must be 0
    //S starts at 32nd byte
    if (sig[32] & 0x80) == 0x80 { //highest bit must be 1
        return errors.New("Signature not malleable")
    }

    if sig[64] >= 4 {
        return errors.New("Recover byte invalid")
    }

    // if pubkey recovered, signature valid
    pubkey2, err := RecoverPubkey(msg, sig)
    if err != nil {
        return err
    }
    if len(pubkey2) != 65 {
        return errors.New("Invalid recovered public key length")
    }
    if !bytes.Equal(pubkey1, pubkey2) {
        return errors.New("Public key does not match recovered public key")
    }

    return nil
}

// recovers a public key from the signature
func RecoverPubkey(msg []byte, sig []byte) ([]byte, error) {
    if len(sig) != 65 {
        return nil, errors.New("Invalid signature length")
    }

    msg_ptr := (*C.uchar)(unsafe.Pointer(&msg[0]))
    sig_ptr := (*C.uchar)(unsafe.Pointer(&sig[0]))

    pubkey := make([]byte, 64)
    /*
        this slice is used for both the recoverable signature and the
        resulting serialized pubkey (both types in libsecp256k1 are 65
        bytes). this saves one allocation of 65 bytes, which is nice as
        pubkey recovery is one bottleneck during load in Ethereum
    */
    bytes65 := make([]byte, 65)

    pubkey_ptr := (*C.secp256k1_pubkey)(unsafe.Pointer(&pubkey[0]))
    recoverable_sig_ptr := (*C.secp256k1_ecdsa_recoverable_signature)(unsafe.Pointer(&bytes65[0]))

    recid := C.int(sig[64])
    ret := C.secp256k1_ecdsa_recoverable_signature_parse_compact(
        context,
        recoverable_sig_ptr,
        sig_ptr,
        recid)

    if ret == C.int(0) {
        return nil, errors.New("Failed to parse signature")
    }

    ret = C.secp256k1_ecdsa_recover(
        context,
        pubkey_ptr,
        recoverable_sig_ptr,
        msg_ptr,
    )

    if ret == C.int(0) {
        return nil, errors.New("Failed to recover public key")
    } else {
        serialized_pubkey_ptr := (*C.uchar)(unsafe.Pointer(&bytes65[0]))

        var output_len C.size_t
        C.secp256k1_ec_pubkey_serialize( // always returns 1
            context,
            serialized_pubkey_ptr,
            &output_len,
            pubkey_ptr,
            0, // SECP256K1_EC_COMPRESSED
        )
        return bytes65, nil
    }
}