mirror of
https://github.com/ethereum/go-ethereum.git
synced 2026-07-22 12:46:44 +00:00
Merge branch 'develop' into rpcfabian
Conflicts: xeth/xeth.go
This commit is contained in:
commit
763375af66
152 changed files with 14030 additions and 5625 deletions
4
Godeps/Godeps.json
generated
4
Godeps/Godeps.json
generated
|
|
@ -22,8 +22,8 @@
|
|||
},
|
||||
{
|
||||
"ImportPath": "github.com/ethereum/ethash",
|
||||
"Comment": "v23.1-33-g6ecb8e6",
|
||||
"Rev": "6ecb8e610d60240187b44f61e66b06198c26fae6"
|
||||
"Comment": "v23.1-81-g4039fd0",
|
||||
"Rev": "4039fd095084679fb0bf3feae91d02506b5d67aa"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/ethereum/serpent-go",
|
||||
|
|
|
|||
14
Godeps/_workspace/src/github.com/ethereum/ethash/.travis.yml
generated
vendored
14
Godeps/_workspace/src/github.com/ethereum/ethash/.travis.yml
generated
vendored
|
|
@ -1,6 +1,14 @@
|
|||
# making our travis.yml play well with C++11 by obtaining g++4.8
|
||||
# Taken from this file:
|
||||
# https://github.com/beark/ftl/blob/master/.travis.yml
|
||||
before_install:
|
||||
- sudo apt-get update -qq
|
||||
- sudo apt-get install -qq wget cmake gcc bash libboost-test-dev nodejs python-pip python-dev
|
||||
- sudo pip install virtualenv -q
|
||||
- sudo add-apt-repository -y ppa:ubuntu-toolchain-r/test
|
||||
- sudo apt-get update -y -qq
|
||||
|
||||
install:
|
||||
- sudo apt-get install -qq --yes --force-yes g++-4.8
|
||||
- sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-4.8 50
|
||||
# need to explicitly request version 1.48 since by default we get 1.46 which does not work with C++11
|
||||
- sudo apt-get install -qq wget cmake bash libboost-test1.48-dev libboost-system1.48-dev libboost-filesystem1.48-dev nodejs python-pip python-dev
|
||||
- sudo pip install virtualenv -q
|
||||
script: "./test/test.sh"
|
||||
|
|
|
|||
2
Godeps/_workspace/src/github.com/ethereum/ethash/CMakeLists.txt
generated
vendored
2
Godeps/_workspace/src/github.com/ethereum/ethash/CMakeLists.txt
generated
vendored
|
|
@ -18,4 +18,4 @@ if (OpenCL_FOUND)
|
|||
add_subdirectory(src/libethash-cl)
|
||||
endif()
|
||||
add_subdirectory(src/benchmark EXCLUDE_FROM_ALL)
|
||||
add_subdirectory(test/c EXCLUDE_FROM_ALL)
|
||||
add_subdirectory(test/c)
|
||||
|
|
|
|||
63
Godeps/_workspace/src/github.com/ethereum/ethash/ethash.go
generated
vendored
63
Godeps/_workspace/src/github.com/ethereum/ethash/ethash.go
generated
vendored
|
|
@ -34,13 +34,12 @@ import (
|
|||
"github.com/ethereum/go-ethereum/common"
|
||||
"github.com/ethereum/go-ethereum/crypto"
|
||||
"github.com/ethereum/go-ethereum/logger"
|
||||
"github.com/ethereum/go-ethereum/logger/glog"
|
||||
"github.com/ethereum/go-ethereum/pow"
|
||||
)
|
||||
|
||||
var minDifficulty = new(big.Int).Exp(big.NewInt(2), big.NewInt(256), big.NewInt(0))
|
||||
|
||||
var powlogger = logger.NewLogger("POW")
|
||||
|
||||
type ParamsAndCache struct {
|
||||
params *C.ethash_params
|
||||
cache *C.ethash_cache
|
||||
|
|
@ -85,29 +84,32 @@ func makeParamsAndCache(chainManager pow.ChainManager, blockNum uint64) (*Params
|
|||
Epoch: blockNum / epochLength,
|
||||
}
|
||||
C.ethash_params_init(paramsAndCache.params, C.uint32_t(uint32(blockNum)))
|
||||
paramsAndCache.cache.mem = C.malloc(paramsAndCache.params.cache_size)
|
||||
paramsAndCache.cache.mem = C.malloc(C.size_t(paramsAndCache.params.cache_size))
|
||||
|
||||
seedHash, err := GetSeedHash(blockNum)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
powlogger.Infoln("Making Cache")
|
||||
glog.V(logger.Info).Infoln("Making cache")
|
||||
start := time.Now()
|
||||
C.ethash_mkcache(paramsAndCache.cache, paramsAndCache.params, (*C.uint8_t)(unsafe.Pointer(&seedHash[0])))
|
||||
powlogger.Infoln("Took:", time.Since(start))
|
||||
C.ethash_mkcache(paramsAndCache.cache, paramsAndCache.params, (*C.ethash_blockhash_t)(unsafe.Pointer(&seedHash[0])))
|
||||
|
||||
if glog.V(logger.Info) {
|
||||
glog.Infoln("Took:", time.Since(start))
|
||||
}
|
||||
|
||||
return paramsAndCache, nil
|
||||
}
|
||||
|
||||
func (pow *Ethash) UpdateCache(force bool) error {
|
||||
func (pow *Ethash) UpdateCache(blockNum uint64, force bool) error {
|
||||
pow.cacheMutex.Lock()
|
||||
defer pow.cacheMutex.Unlock()
|
||||
|
||||
thisEpoch := pow.chainManager.CurrentBlock().NumberU64() / epochLength
|
||||
thisEpoch := blockNum / epochLength
|
||||
if force || pow.paramsAndCache.Epoch != thisEpoch {
|
||||
var err error
|
||||
pow.paramsAndCache, err = makeParamsAndCache(pow.chainManager, pow.chainManager.CurrentBlock().NumberU64())
|
||||
pow.paramsAndCache, err = makeParamsAndCache(pow.chainManager, blockNum)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
|
@ -118,7 +120,7 @@ func (pow *Ethash) UpdateCache(force bool) error {
|
|||
|
||||
func makeDAG(p *ParamsAndCache) *DAG {
|
||||
d := &DAG{
|
||||
dag: C.malloc(p.params.full_size),
|
||||
dag: C.malloc(C.size_t(p.params.full_size)),
|
||||
file: false,
|
||||
paramsAndCache: p,
|
||||
}
|
||||
|
|
@ -131,9 +133,9 @@ func makeDAG(p *ParamsAndCache) *DAG {
|
|||
for {
|
||||
select {
|
||||
case <-t.C:
|
||||
powlogger.Infof("... still generating DAG (%v) ...\n", time.Since(tstart).Seconds())
|
||||
glog.V(logger.Info).Infof("... still generating DAG (%v) ...\n", time.Since(tstart).Seconds())
|
||||
case str := <-donech:
|
||||
powlogger.Infof("... %s ...\n", str)
|
||||
glog.V(logger.Info).Infof("... %s ...\n", str)
|
||||
break done
|
||||
}
|
||||
}
|
||||
|
|
@ -193,30 +195,30 @@ func (pow *Ethash) UpdateDAG() {
|
|||
pow.paramsAndCache = paramsAndCache
|
||||
path := path.Join("/", "tmp", "dag")
|
||||
pow.dag = nil
|
||||
powlogger.Infoln("Retrieving DAG")
|
||||
glog.V(logger.Info).Infoln("Retrieving DAG")
|
||||
start := time.Now()
|
||||
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
powlogger.Infof("No DAG found. Generating new DAG in '%s' (this takes a while)...\n", path)
|
||||
glog.V(logger.Info).Infof("No DAG found. Generating new DAG in '%s' (this takes a while)...\n", path)
|
||||
pow.dag = makeDAG(paramsAndCache)
|
||||
file = pow.writeDagToDisk(pow.dag, thisEpoch)
|
||||
pow.dag.file = true
|
||||
} else {
|
||||
data, err := ioutil.ReadAll(file)
|
||||
if err != nil {
|
||||
powlogger.Infof("DAG load err: %v\n", err)
|
||||
glog.V(logger.Info).Infof("DAG load err: %v\n", err)
|
||||
}
|
||||
|
||||
if len(data) < 8 {
|
||||
powlogger.Infof("DAG in '%s' is less than 8 bytes, it must be corrupted. Generating new DAG (this takes a while)...\n", path)
|
||||
glog.V(logger.Info).Infof("DAG in '%s' is less than 8 bytes, it must be corrupted. Generating new DAG (this takes a while)...\n", path)
|
||||
pow.dag = makeDAG(paramsAndCache)
|
||||
file = pow.writeDagToDisk(pow.dag, thisEpoch)
|
||||
pow.dag.file = true
|
||||
} else {
|
||||
dataEpoch := binary.BigEndian.Uint64(data[0:8])
|
||||
if dataEpoch < thisEpoch {
|
||||
powlogger.Infof("DAG in '%s' is stale. Generating new DAG (this takes a while)...\n", path)
|
||||
glog.V(logger.Info).Infof("DAG in '%s' is stale. Generating new DAG (this takes a while)...\n", path)
|
||||
pow.dag = makeDAG(paramsAndCache)
|
||||
file = pow.writeDagToDisk(pow.dag, thisEpoch)
|
||||
pow.dag.file = true
|
||||
|
|
@ -224,7 +226,7 @@ func (pow *Ethash) UpdateDAG() {
|
|||
// FIXME
|
||||
panic(fmt.Errorf("Saved DAG in '%s' reports to be from future epoch %v (current epoch is %v)\n", path, dataEpoch, thisEpoch))
|
||||
} else if len(data) != (int(paramsAndCache.params.full_size) + 8) {
|
||||
powlogger.Infof("DAG in '%s' is corrupted. Generating new DAG (this takes a while)...\n", path)
|
||||
glog.V(logger.Info).Infof("DAG in '%s' is corrupted. Generating new DAG (this takes a while)...\n", path)
|
||||
pow.dag = makeDAG(paramsAndCache)
|
||||
file = pow.writeDagToDisk(pow.dag, thisEpoch)
|
||||
pow.dag.file = true
|
||||
|
|
@ -238,7 +240,7 @@ func (pow *Ethash) UpdateDAG() {
|
|||
}
|
||||
}
|
||||
}
|
||||
powlogger.Infoln("Took:", time.Since(start))
|
||||
glog.V(logger.Info).Infoln("Took:", time.Since(start))
|
||||
|
||||
file.Close()
|
||||
}
|
||||
|
|
@ -319,14 +321,13 @@ func (pow *Ethash) Search(block pow.Block, stop <-chan struct{}) (uint64, []byte
|
|||
start := time.Now().UnixNano()
|
||||
|
||||
nonce := uint64(r.Int63())
|
||||
cMiningHash := (*C.uint8_t)(unsafe.Pointer(&miningHash[0]))
|
||||
cMiningHash := (*C.ethash_blockhash_t)(unsafe.Pointer(&miningHash[0]))
|
||||
target := new(big.Int).Div(minDifficulty, diff)
|
||||
|
||||
var ret C.ethash_return_value
|
||||
for {
|
||||
select {
|
||||
case <-stop:
|
||||
powlogger.Infoln("Breaking from mining")
|
||||
pow.HashRate = 0
|
||||
return 0, nil, nil
|
||||
default:
|
||||
|
|
@ -337,11 +338,11 @@ func (pow *Ethash) Search(block pow.Block, stop <-chan struct{}) (uint64, []byte
|
|||
pow.HashRate = int64(hashes)
|
||||
|
||||
C.ethash_full(&ret, pow.dag.dag, pow.dag.paramsAndCache.params, cMiningHash, C.uint64_t(nonce))
|
||||
result := common.Bytes2Big(C.GoBytes(unsafe.Pointer(&ret.result[0]), C.int(32)))
|
||||
result := common.Bytes2Big(C.GoBytes(unsafe.Pointer(&ret.result), C.int(32)))
|
||||
|
||||
// TODO: disagrees with the spec https://github.com/ethereum/wiki/wiki/Ethash#mining
|
||||
if result.Cmp(target) <= 0 {
|
||||
mixDigest := C.GoBytes(unsafe.Pointer(&ret.mix_hash[0]), C.int(32))
|
||||
mixDigest := C.GoBytes(unsafe.Pointer(&ret.mix_hash), C.int(32))
|
||||
seedHash, err := GetSeedHash(block.NumberU64()) // This seedhash is useless
|
||||
if err != nil {
|
||||
panic(err)
|
||||
|
|
@ -367,14 +368,14 @@ func (pow *Ethash) Verify(block pow.Block) bool {
|
|||
func (pow *Ethash) verify(hash common.Hash, mixDigest common.Hash, difficulty *big.Int, blockNum uint64, nonce uint64) bool {
|
||||
// Make sure the block num is valid
|
||||
if blockNum >= epochLength*2048 {
|
||||
powlogger.Infoln(fmt.Sprintf("Block number exceeds limit, invalid (value is %v, limit is %v)",
|
||||
glog.V(logger.Info).Infoln(fmt.Sprintf("Block number exceeds limit, invalid (value is %v, limit is %v)",
|
||||
blockNum, epochLength*2048))
|
||||
return false
|
||||
}
|
||||
|
||||
// First check: make sure header, mixDigest, nonce are correct without hitting the cache
|
||||
// This is to prevent DOS attacks
|
||||
chash := (*C.uint8_t)(unsafe.Pointer(&hash[0]))
|
||||
chash := (*C.ethash_blockhash_t)(unsafe.Pointer(&hash[0]))
|
||||
cnonce := C.uint64_t(nonce)
|
||||
target := new(big.Int).Div(minDifficulty, difficulty)
|
||||
|
||||
|
|
@ -386,13 +387,13 @@ func (pow *Ethash) verify(hash common.Hash, mixDigest common.Hash, difficulty *b
|
|||
if blockNum/epochLength < pow.paramsAndCache.Epoch {
|
||||
var err error
|
||||
// If we can't make the params for some reason, this block is invalid
|
||||
pAc, err = makeParamsAndCache(pow.chainManager, blockNum)
|
||||
pAc, err = makeParamsAndCache(pow.chainManager, blockNum+1)
|
||||
if err != nil {
|
||||
powlogger.Infoln(err)
|
||||
glog.V(logger.Info).Infoln("big fucking eror", err)
|
||||
return false
|
||||
}
|
||||
} else {
|
||||
pow.UpdateCache(false)
|
||||
pow.UpdateCache(blockNum, false)
|
||||
pow.cacheMutex.RLock()
|
||||
defer pow.cacheMutex.RUnlock()
|
||||
pAc = pow.paramsAndCache
|
||||
|
|
@ -402,7 +403,7 @@ func (pow *Ethash) verify(hash common.Hash, mixDigest common.Hash, difficulty *b
|
|||
|
||||
C.ethash_light(ret, pAc.cache, pAc.params, chash, cnonce)
|
||||
|
||||
result := common.Bytes2Big(C.GoBytes(unsafe.Pointer(&ret.result[0]), C.int(32)))
|
||||
result := common.Bytes2Big(C.GoBytes(unsafe.Pointer(&ret.result), C.int(32)))
|
||||
return result.Cmp(target) <= 0
|
||||
}
|
||||
|
||||
|
|
@ -418,7 +419,7 @@ func (pow *Ethash) FullHash(nonce uint64, miningHash []byte) []byte {
|
|||
pow.UpdateDAG()
|
||||
pow.dagMutex.Lock()
|
||||
defer pow.dagMutex.Unlock()
|
||||
cMiningHash := (*C.uint8_t)(unsafe.Pointer(&miningHash[0]))
|
||||
cMiningHash := (*C.ethash_blockhash_t)(unsafe.Pointer(&miningHash[0]))
|
||||
cnonce := C.uint64_t(nonce)
|
||||
ret := new(C.ethash_return_value)
|
||||
// pow.hash is the output/return of ethash_full
|
||||
|
|
@ -428,7 +429,7 @@ func (pow *Ethash) FullHash(nonce uint64, miningHash []byte) []byte {
|
|||
}
|
||||
|
||||
func (pow *Ethash) LightHash(nonce uint64, miningHash []byte) []byte {
|
||||
cMiningHash := (*C.uint8_t)(unsafe.Pointer(&miningHash[0]))
|
||||
cMiningHash := (*C.ethash_blockhash_t)(unsafe.Pointer(&miningHash[0]))
|
||||
cnonce := C.uint64_t(nonce)
|
||||
ret := new(C.ethash_return_value)
|
||||
C.ethash_light(ret, pow.paramsAndCache.cache, pow.paramsAndCache.params, cMiningHash, cnonce)
|
||||
|
|
|
|||
29
Godeps/_workspace/src/github.com/ethereum/ethash/setup.py
generated
vendored
29
Godeps/_workspace/src/github.com/ethereum/ethash/setup.py
generated
vendored
|
|
@ -2,12 +2,12 @@
|
|||
from distutils.core import setup, Extension
|
||||
|
||||
pyethash = Extension('pyethash',
|
||||
sources = [
|
||||
sources=[
|
||||
'src/python/core.c',
|
||||
'src/libethash/util.c',
|
||||
'src/libethash/internal.c',
|
||||
'src/libethash/sha3.c'],
|
||||
depends = [
|
||||
depends=[
|
||||
'src/libethash/ethash.h',
|
||||
'src/libethash/compiler.h',
|
||||
'src/libethash/data_sizes.h',
|
||||
|
|
@ -18,16 +18,17 @@ pyethash = Extension('pyethash',
|
|||
'src/libethash/sha3.h',
|
||||
'src/libethash/util.h'
|
||||
],
|
||||
extra_compile_args = ["-Isrc/", "-std=gnu99", "-Wall"])
|
||||
extra_compile_args=["-Isrc/", "-std=gnu99", "-Wall"])
|
||||
|
||||
setup (
|
||||
name = 'pyethash',
|
||||
author = "Matthew Wampler-Doty",
|
||||
author_email = "matthew.wampler.doty@gmail.com",
|
||||
license = 'GPL',
|
||||
version = '23',
|
||||
url = 'https://github.com/ethereum/ethash',
|
||||
download_url = 'https://github.com/ethereum/ethash/tarball/v23',
|
||||
description = 'Python wrappers for ethash, the ethereum proof of work hashing function',
|
||||
ext_modules = [pyethash],
|
||||
)
|
||||
setup(
|
||||
name='pyethash',
|
||||
author="Matthew Wampler-Doty",
|
||||
author_email="matthew.wampler.doty@gmail.com",
|
||||
license='GPL',
|
||||
version='0.1.23',
|
||||
url='https://github.com/ethereum/ethash',
|
||||
download_url='https://github.com/ethereum/ethash/tarball/v23',
|
||||
description=('Python wrappers for ethash, the ethereum proof of work'
|
||||
'hashing function'),
|
||||
ext_modules=[pyethash],
|
||||
)
|
||||
|
|
|
|||
5
Godeps/_workspace/src/github.com/ethereum/ethash/src/benchmark/CMakeLists.txt
generated
vendored
5
Godeps/_workspace/src/github.com/ethereum/ethash/src/benchmark/CMakeLists.txt
generated
vendored
|
|
@ -6,6 +6,11 @@ if (MSVC)
|
|||
add_definitions("/openmp")
|
||||
endif()
|
||||
|
||||
# enable C++11, should probably be a bit more specific about compiler
|
||||
if (NOT MSVC)
|
||||
SET(CMAKE_CXX_FLAGS "-std=c++11")
|
||||
endif()
|
||||
|
||||
if (NOT MPI_FOUND)
|
||||
find_package(MPI)
|
||||
endif()
|
||||
|
|
|
|||
69
Godeps/_workspace/src/github.com/ethereum/ethash/src/benchmark/benchmark.cpp
generated
vendored
69
Godeps/_workspace/src/github.com/ethereum/ethash/src/benchmark/benchmark.cpp
generated
vendored
|
|
@ -21,7 +21,7 @@
|
|||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <time.h>
|
||||
#include <chrono>
|
||||
#include <libethash/ethash.h>
|
||||
#include <libethash/util.h>
|
||||
#ifdef OPENCL
|
||||
|
|
@ -41,6 +41,8 @@
|
|||
#undef min
|
||||
#undef max
|
||||
|
||||
using std::chrono::high_resolution_clock;
|
||||
|
||||
#if defined(OPENCL)
|
||||
const unsigned trials = 1024*1024*32;
|
||||
#elif defined(FULL)
|
||||
|
|
@ -104,10 +106,11 @@ extern "C" int main(void)
|
|||
//params.full_size = 8209 * 4096; // 8MBish;
|
||||
//params.cache_size = 8209*4096;
|
||||
//params.cache_size = 2053*4096;
|
||||
uint8_t seed[32], previous_hash[32];
|
||||
ethash_blockhash_t seed;
|
||||
ethash_blockhash_t previous_hash;
|
||||
|
||||
memcpy(seed, hexStringToBytes("9410b944535a83d9adf6bbdcc80e051f30676173c16ca0d32d6f1263fc246466").data(), 32);
|
||||
memcpy(previous_hash, hexStringToBytes("c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470").data(), 32);
|
||||
memcpy(&seed, hexStringToBytes("9410b944535a83d9adf6bbdcc80e051f30676173c16ca0d32d6f1263fc246466").data(), 32);
|
||||
memcpy(&previous_hash, hexStringToBytes("c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470").data(), 32);
|
||||
|
||||
// allocate page aligned buffer for dataset
|
||||
#ifdef FULL
|
||||
|
|
@ -122,50 +125,50 @@ extern "C" int main(void)
|
|||
|
||||
// compute cache or full data
|
||||
{
|
||||
clock_t startTime = clock();
|
||||
auto startTime = high_resolution_clock::now();
|
||||
ethash_mkcache(&cache, ¶ms, seed);
|
||||
clock_t time = clock() - startTime;
|
||||
auto time = std::chrono::duration_cast<std::chrono::milliseconds>(high_resolution_clock::now() - startTime).count();
|
||||
|
||||
uint8_t cache_hash[32];
|
||||
SHA3_256(cache_hash, (uint8_t const*)cache_mem, params.cache_size);
|
||||
ethash_blockhash_t cache_hash;
|
||||
SHA3_256(&cache_hash, (uint8_t const*)cache_mem, params.cache_size);
|
||||
debugf("ethash_mkcache: %ums, sha3: %s\n", (unsigned)((time*1000)/CLOCKS_PER_SEC), bytesToHexString(cache_hash,sizeof(cache_hash)).data());
|
||||
|
||||
// print a couple of test hashes
|
||||
{
|
||||
const clock_t startTime = clock();
|
||||
auto startTime = high_resolution_clock::now();
|
||||
ethash_return_value hash;
|
||||
ethash_light(&hash, &cache, ¶ms, previous_hash, 0);
|
||||
const clock_t time = clock() - startTime;
|
||||
debugf("ethash_light test: %ums, %s\n", (unsigned)((time*1000)/CLOCKS_PER_SEC), bytesToHexString(hash.result, 32).data());
|
||||
auto time = std::chrono::duration_cast<std::chrono::milliseconds>(high_resolution_clock::now() - startTime).count();
|
||||
debugf("ethash_light test: %ums, %s\n", (unsigned)time, bytesToHexString(hash.result, 32).data());
|
||||
}
|
||||
|
||||
#ifdef FULL
|
||||
startTime = clock();
|
||||
startTime = high_resolution_clock::now();
|
||||
ethash_compute_full_data(full_mem, ¶ms, &cache);
|
||||
time = clock() - startTime;
|
||||
debugf("ethash_compute_full_data: %ums\n", (unsigned)((time*1000)/CLOCKS_PER_SEC));
|
||||
time = std::chrono::duration_cast<std::chrono::milliseconds>(high_resolution_clock::now() - startTime).count();
|
||||
debugf("ethash_compute_full_data: %ums\n", (unsigned)time);
|
||||
#endif // FULL
|
||||
}
|
||||
|
||||
#ifdef OPENCL
|
||||
ethash_cl_miner miner;
|
||||
{
|
||||
const clock_t startTime = clock();
|
||||
auto startTime = high_resolution_clock::now();
|
||||
if (!miner.init(params, seed))
|
||||
exit(-1);
|
||||
const clock_t time = clock() - startTime;
|
||||
debugf("ethash_cl_miner init: %ums\n", (unsigned)((time*1000)/CLOCKS_PER_SEC));
|
||||
auto time = std::chrono::duration_cast<std::chrono::milliseconds>(high_resolution_clock::now() - startTime).count();
|
||||
debugf("ethash_cl_miner init: %ums\n", (unsigned)time);
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
#ifdef FULL
|
||||
{
|
||||
const clock_t startTime = clock();
|
||||
auto startTime = high_resolution_clock::now();
|
||||
ethash_return_value hash;
|
||||
ethash_full(&hash, full_mem, ¶ms, previous_hash, 0);
|
||||
const clock_t time = clock() - startTime;
|
||||
debugf("ethash_full test: %uns, %s\n", (unsigned)((time*1000000)/CLOCKS_PER_SEC), bytesToHexString(hash.result, 32).data());
|
||||
auto time = std::chrono::duration_cast<std::chrono::milliseconds>(high_resolution_clock::now() - startTime).count();
|
||||
debugf("ethash_full test: %uns, %s\n", (unsigned)time);
|
||||
}
|
||||
#endif
|
||||
|
||||
|
|
@ -186,10 +189,12 @@ extern "C" int main(void)
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ensure nothing else is going on
|
||||
miner.finish();
|
||||
#endif
|
||||
|
||||
|
||||
clock_t startTime = clock();
|
||||
auto startTime = high_resolution_clock::now();
|
||||
unsigned hash_count = trials;
|
||||
|
||||
#ifdef OPENCL
|
||||
|
|
@ -201,7 +206,7 @@ extern "C" int main(void)
|
|||
|
||||
virtual bool found(uint64_t const* nonces, uint32_t count)
|
||||
{
|
||||
nonce_vec.assign(nonces, nonces + count);
|
||||
nonce_vec.insert(nonce_vec.end(), nonces, nonces + count);
|
||||
return false;
|
||||
}
|
||||
|
||||
|
|
@ -241,15 +246,23 @@ extern "C" int main(void)
|
|||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
clock_t time = std::max((clock_t)1u, clock() - startTime);
|
||||
auto time = std::chrono::duration_cast<std::chrono::microseconds>(high_resolution_clock::now() - startTime).count();
|
||||
debugf("Search took: %ums\n", (unsigned)time/1000);
|
||||
|
||||
unsigned read_size = ACCESSES * MIX_BYTES;
|
||||
#if defined(OPENCL) || defined(FULL)
|
||||
debugf(
|
||||
"hashrate: %8u, bw: %6u MB/s\n",
|
||||
(unsigned)(((uint64_t)hash_count*CLOCKS_PER_SEC)/time),
|
||||
(unsigned)((((uint64_t)hash_count*read_size*CLOCKS_PER_SEC)/time) / (1024*1024))
|
||||
"hashrate: %8.2f Mh/s, bw: %8.2f GB/s\n",
|
||||
(double)hash_count * (1000*1000)/time / (1000*1000),
|
||||
(double)hash_count*read_size * (1000*1000)/time / (1024*1024*1024)
|
||||
);
|
||||
#else
|
||||
debugf(
|
||||
"hashrate: %8.2f Kh/s, bw: %8.2f MB/s\n",
|
||||
(double)hash_count * (1000*1000)/time / (1000),
|
||||
(double)hash_count*read_size * (1000*1000)/time / (1024*1024)
|
||||
);
|
||||
#endif
|
||||
|
||||
free(cache_mem_buf);
|
||||
#ifdef FULL
|
||||
|
|
|
|||
7
Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash-cl/CMakeLists.txt
generated
vendored
7
Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash-cl/CMakeLists.txt
generated
vendored
|
|
@ -1,3 +1,5 @@
|
|||
cmake_minimum_required(VERSION 2.8)
|
||||
|
||||
set(LIBRARY ethash-cl)
|
||||
set(CMAKE_BUILD_TYPE Release)
|
||||
|
||||
|
|
@ -28,11 +30,16 @@ if (NOT MSVC)
|
|||
endif ()
|
||||
endif()
|
||||
|
||||
set(OpenCL_FOUND TRUE)
|
||||
set(OpenCL_INCLUDE_DIRS /usr/include/CL)
|
||||
set(OpenCL_LIBRARIES -lOpenCL)
|
||||
|
||||
if (NOT OpenCL_FOUND)
|
||||
find_package(OpenCL)
|
||||
endif()
|
||||
|
||||
if (OpenCL_FOUND)
|
||||
set(CMAKE_CXX_FLAGS "-std=c++11 -Wall -Wno-unknown-pragmas -Wextra -Werror -pedantic -fPIC ${CMAKE_CXX_FLAGS}")
|
||||
include_directories(${OpenCL_INCLUDE_DIRS} ${CMAKE_CURRENT_BINARY_DIR})
|
||||
include_directories(..)
|
||||
add_library(${LIBRARY} ethash_cl_miner.cpp ethash_cl_miner.h cl.hpp)
|
||||
|
|
|
|||
10
Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash-cl/ethash_cl_miner.cpp
generated
vendored
10
Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash-cl/ethash_cl_miner.cpp
generated
vendored
|
|
@ -22,6 +22,8 @@
|
|||
|
||||
#define _CRT_SECURE_NO_WARNINGS
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <assert.h>
|
||||
#include <queue>
|
||||
#include <vector>
|
||||
|
|
@ -52,7 +54,7 @@ ethash_cl_miner::ethash_cl_miner()
|
|||
{
|
||||
}
|
||||
|
||||
bool ethash_cl_miner::init(ethash_params const& params, const uint8_t seed[32], unsigned workgroup_size)
|
||||
bool ethash_cl_miner::init(ethash_params const& params, ethash_blockhash_t const *seed, unsigned workgroup_size)
|
||||
{
|
||||
// store params
|
||||
m_params = params;
|
||||
|
|
@ -95,7 +97,7 @@ bool ethash_cl_miner::init(ethash_params const& params, const uint8_t seed[32],
|
|||
}
|
||||
|
||||
// create context
|
||||
m_context = cl::Context(std::vector<cl::Device>(&device, &device+1));
|
||||
m_context = cl::Context(std::vector<cl::Device>(&device, &device + 1));
|
||||
m_queue = cl::CommandQueue(m_context, device);
|
||||
|
||||
// use requested workgroup size, but we require multiple of 8
|
||||
|
|
@ -308,6 +310,10 @@ void ethash_cl_miner::search(uint8_t const* header, uint64_t target, search_hook
|
|||
if (exit)
|
||||
break;
|
||||
|
||||
// reset search buffer if we're still going
|
||||
if (num_found)
|
||||
m_queue.enqueueWriteBuffer(m_search_buf[batch.buf], true, 0, 4, &c_zero);
|
||||
|
||||
pending.pop();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
3
Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash-cl/ethash_cl_miner.h
generated
vendored
3
Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash-cl/ethash_cl_miner.h
generated
vendored
|
|
@ -19,8 +19,9 @@ public:
|
|||
public:
|
||||
ethash_cl_miner();
|
||||
|
||||
bool init(ethash_params const& params, const uint8_t seed[32], unsigned workgroup_size = 64);
|
||||
bool init(ethash_params const& params, ethash_blockhash_t const *seed, unsigned workgroup_size = 64);
|
||||
|
||||
void finish();
|
||||
void hash(uint8_t* ret, uint8_t const* header, uint64_t nonce, unsigned count);
|
||||
void search(uint8_t const* header, uint64_t target, search_hook& hook);
|
||||
|
||||
|
|
|
|||
7
Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/CMakeLists.txt
generated
vendored
7
Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/CMakeLists.txt
generated
vendored
|
|
@ -12,6 +12,7 @@ endif()
|
|||
|
||||
set(FILES util.c
|
||||
util.h
|
||||
io.c
|
||||
internal.c
|
||||
ethash.h
|
||||
endian.h
|
||||
|
|
@ -19,6 +20,12 @@ set(FILES util.c
|
|||
fnv.h
|
||||
data_sizes.h)
|
||||
|
||||
if (MSVC)
|
||||
list(APPEND FILES io_win32.c)
|
||||
else()
|
||||
list(APPEND FILES io_posix.c)
|
||||
endif()
|
||||
|
||||
if (NOT CRYPTOPP_FOUND)
|
||||
find_package(CryptoPP 5.6.2)
|
||||
endif()
|
||||
|
|
|
|||
4
Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/data_sizes.h
generated
vendored
4
Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/data_sizes.h
generated
vendored
|
|
@ -48,7 +48,7 @@ extern "C" {
|
|||
// Sow[i*HashBytes]; j++]]]][[2]][[1]]
|
||||
|
||||
|
||||
static const size_t dag_sizes[2048] = {
|
||||
static const uint64_t dag_sizes[2048] = {
|
||||
1073739904U, 1082130304U, 1090514816U, 1098906752U, 1107293056U,
|
||||
1115684224U, 1124070016U, 1132461952U, 1140849536U, 1149232768U,
|
||||
1157627776U, 1166013824U, 1174404736U, 1182786944U, 1191180416U,
|
||||
|
|
@ -477,7 +477,7 @@ static const size_t dag_sizes[2048] = {
|
|||
// While[! PrimeQ[i], i--];
|
||||
// Sow[i*HashBytes]; j++]]]][[2]][[1]]
|
||||
|
||||
const size_t cache_sizes[2048] = {
|
||||
const uint64_t cache_sizes[2048] = {
|
||||
16776896U, 16907456U, 17039296U, 17170112U, 17301056U, 17432512U, 17563072U,
|
||||
17693888U, 17824192U, 17955904U, 18087488U, 18218176U, 18349504U, 18481088U,
|
||||
18611392U, 18742336U, 18874304U, 19004224U, 19135936U, 19267264U, 19398208U,
|
||||
|
|
|
|||
80
Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/ethash.h
generated
vendored
80
Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/ethash.h
generated
vendored
|
|
@ -43,17 +43,34 @@ extern "C" {
|
|||
#endif
|
||||
|
||||
typedef struct ethash_params {
|
||||
size_t full_size; // Size of full data set (in bytes, multiple of mix size (128)).
|
||||
size_t cache_size; // Size of compute cache (in bytes, multiple of node size (64)).
|
||||
uint64_t full_size; // Size of full data set (in bytes, multiple of mix size (128)).
|
||||
uint64_t cache_size; // Size of compute cache (in bytes, multiple of node size (64)).
|
||||
} ethash_params;
|
||||
|
||||
/// Type of a blockhash
|
||||
typedef struct ethash_blockhash { uint8_t b[32]; } ethash_blockhash_t;
|
||||
static inline uint8_t ethash_blockhash_get(ethash_blockhash_t const* hash, unsigned int i)
|
||||
{
|
||||
return hash->b[i];
|
||||
}
|
||||
|
||||
static inline void ethash_blockhash_set(ethash_blockhash_t *hash, unsigned int i, uint8_t v)
|
||||
{
|
||||
hash->b[i] = v;
|
||||
}
|
||||
|
||||
static inline void ethash_blockhash_reset(ethash_blockhash_t *hash)
|
||||
{
|
||||
memset(hash, 0, 32);
|
||||
}
|
||||
|
||||
typedef struct ethash_return_value {
|
||||
uint8_t result[32];
|
||||
uint8_t mix_hash[32];
|
||||
ethash_blockhash_t result;
|
||||
ethash_blockhash_t mix_hash;
|
||||
} ethash_return_value;
|
||||
|
||||
size_t ethash_get_datasize(const uint32_t block_number);
|
||||
size_t ethash_get_cachesize(const uint32_t block_number);
|
||||
uint64_t ethash_get_datasize(const uint32_t block_number);
|
||||
uint64_t ethash_get_cachesize(const uint32_t block_number);
|
||||
|
||||
// initialize the parameters
|
||||
static inline void ethash_params_init(ethash_params *params, const uint32_t block_number) {
|
||||
|
|
@ -65,51 +82,68 @@ typedef struct ethash_cache {
|
|||
void *mem;
|
||||
} ethash_cache;
|
||||
|
||||
void ethash_mkcache(ethash_cache *cache, ethash_params const *params, const uint8_t seed[32]);
|
||||
void ethash_mkcache(ethash_cache *cache, ethash_params const *params, ethash_blockhash_t const *seed);
|
||||
void ethash_compute_full_data(void *mem, ethash_params const *params, ethash_cache const *cache);
|
||||
void ethash_full(ethash_return_value *ret, void const *full_mem, ethash_params const *params, const uint8_t header_hash[32], const uint64_t nonce);
|
||||
void ethash_light(ethash_return_value *ret, ethash_cache const *cache, ethash_params const *params, const uint8_t header_hash[32], const uint64_t nonce);
|
||||
void ethash_get_seedhash(uint8_t seedhash[32], const uint32_t block_number);
|
||||
void ethash_full(ethash_return_value *ret,
|
||||
void const *full_mem,
|
||||
ethash_params const *params,
|
||||
ethash_blockhash_t const *header_hash,
|
||||
const uint64_t nonce);
|
||||
void ethash_light(ethash_return_value *ret,
|
||||
ethash_cache const *cache,
|
||||
ethash_params const *params,
|
||||
ethash_blockhash_t const *header_hash,
|
||||
const uint64_t nonce);
|
||||
void ethash_get_seedhash(ethash_blockhash_t *seedhash, const uint32_t block_number);
|
||||
|
||||
static inline void ethash_prep_light(void *cache, ethash_params const *params, const uint8_t seed[32]) {
|
||||
static inline void ethash_prep_light(void *cache, ethash_params const *params, ethash_blockhash_t const* seed)
|
||||
{
|
||||
ethash_cache c;
|
||||
c.mem = cache;
|
||||
ethash_mkcache(&c, params, seed);
|
||||
}
|
||||
|
||||
static inline void ethash_compute_light(ethash_return_value *ret, void const *cache, ethash_params const *params, const uint8_t header_hash[32], const uint64_t nonce) {
|
||||
static inline void ethash_compute_light(ethash_return_value *ret, void const *cache, ethash_params const *params, ethash_blockhash_t const *header_hash, const uint64_t nonce)
|
||||
{
|
||||
ethash_cache c;
|
||||
c.mem = (void *) cache;
|
||||
ethash_light(ret, &c, params, header_hash, nonce);
|
||||
}
|
||||
|
||||
static inline void ethash_prep_full(void *full, ethash_params const *params, void const *cache) {
|
||||
static inline void ethash_prep_full(void *full, ethash_params const *params, void const *cache)
|
||||
{
|
||||
ethash_cache c;
|
||||
c.mem = (void *) cache;
|
||||
ethash_compute_full_data(full, params, &c);
|
||||
}
|
||||
|
||||
static inline void ethash_compute_full(ethash_return_value *ret, void const *full, ethash_params const *params, const uint8_t header_hash[32], const uint64_t nonce) {
|
||||
static inline void ethash_compute_full(ethash_return_value *ret,
|
||||
void const *full,
|
||||
ethash_params const *params,
|
||||
ethash_blockhash_t const *header_hash,
|
||||
const uint64_t nonce)
|
||||
{
|
||||
ethash_full(ret, full, params, header_hash, nonce);
|
||||
}
|
||||
|
||||
// Returns if hash is less than or equal to difficulty
|
||||
static inline int ethash_check_difficulty(
|
||||
const uint8_t hash[32],
|
||||
const uint8_t difficulty[32]) {
|
||||
static inline int ethash_check_difficulty(ethash_blockhash_t const *hash,
|
||||
ethash_blockhash_t const *difficulty)
|
||||
{
|
||||
// Difficulty is big endian
|
||||
for (int i = 0; i < 32; i++) {
|
||||
if (hash[i] == difficulty[i]) continue;
|
||||
return hash[i] < difficulty[i];
|
||||
if (ethash_blockhash_get(hash, i) == ethash_blockhash_get(difficulty, i)) {
|
||||
continue;
|
||||
}
|
||||
return ethash_blockhash_get(hash, i) < ethash_blockhash_get(difficulty, i);
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
int ethash_quick_check_difficulty(
|
||||
const uint8_t header_hash[32],
|
||||
int ethash_quick_check_difficulty(ethash_blockhash_t const *header_hash,
|
||||
const uint64_t nonce,
|
||||
const uint8_t mix_hash[32],
|
||||
const uint8_t difficulty[32]);
|
||||
ethash_blockhash_t const *mix_hash,
|
||||
ethash_blockhash_t const *difficulty);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
|
|
|
|||
84
Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/internal.c
generated
vendored
84
Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/internal.c
generated
vendored
|
|
@ -37,12 +37,12 @@
|
|||
#include "sha3.h"
|
||||
#endif // WITH_CRYPTOPP
|
||||
|
||||
size_t ethash_get_datasize(const uint32_t block_number) {
|
||||
uint64_t ethash_get_datasize(const uint32_t block_number) {
|
||||
assert(block_number / EPOCH_LENGTH < 2048);
|
||||
return dag_sizes[block_number / EPOCH_LENGTH];
|
||||
}
|
||||
|
||||
size_t ethash_get_cachesize(const uint32_t block_number) {
|
||||
uint64_t ethash_get_cachesize(const uint32_t block_number) {
|
||||
assert(block_number / EPOCH_LENGTH < 2048);
|
||||
return cache_sizes[block_number / EPOCH_LENGTH];
|
||||
}
|
||||
|
|
@ -50,14 +50,14 @@ size_t ethash_get_cachesize(const uint32_t block_number) {
|
|||
// Follows Sergio's "STRICT MEMORY HARD HASHING FUNCTIONS" (2014)
|
||||
// https://bitslog.files.wordpress.com/2013/12/memohash-v0-3.pdf
|
||||
// SeqMemoHash(s, R, N)
|
||||
void static ethash_compute_cache_nodes(
|
||||
node *const nodes,
|
||||
void static ethash_compute_cache_nodes(node *const nodes,
|
||||
ethash_params const *params,
|
||||
const uint8_t seed[32]) {
|
||||
ethash_blockhash_t const* seed)
|
||||
{
|
||||
assert((params->cache_size % sizeof(node)) == 0);
|
||||
uint32_t const num_nodes = (uint32_t) (params->cache_size / sizeof(node));
|
||||
|
||||
SHA3_512(nodes[0].bytes, seed, 32);
|
||||
SHA3_512(nodes[0].bytes, (uint8_t*)seed, 32);
|
||||
|
||||
for (unsigned i = 1; i != num_nodes; ++i) {
|
||||
SHA3_512(nodes[i].bytes, nodes[i - 1].bytes, 64);
|
||||
|
|
@ -84,20 +84,19 @@ void static ethash_compute_cache_nodes(
|
|||
#endif
|
||||
}
|
||||
|
||||
void ethash_mkcache(
|
||||
ethash_cache *cache,
|
||||
void ethash_mkcache(ethash_cache *cache,
|
||||
ethash_params const *params,
|
||||
const uint8_t seed[32]) {
|
||||
ethash_blockhash_t const* seed)
|
||||
{
|
||||
node *nodes = (node *) cache->mem;
|
||||
ethash_compute_cache_nodes(nodes, params, seed);
|
||||
}
|
||||
|
||||
void ethash_calculate_dag_item(
|
||||
node *const ret,
|
||||
void ethash_calculate_dag_item(node *const ret,
|
||||
const unsigned node_index,
|
||||
const struct ethash_params *params,
|
||||
const struct ethash_cache *cache) {
|
||||
|
||||
const struct ethash_cache *cache)
|
||||
{
|
||||
uint32_t num_parent_nodes = (uint32_t) (params->cache_size / sizeof(node));
|
||||
node const *cache_nodes = (node const *) cache->mem;
|
||||
node const *init = &cache_nodes[node_index % num_parent_nodes];
|
||||
|
|
@ -161,13 +160,13 @@ void ethash_compute_full_data(
|
|||
}
|
||||
}
|
||||
|
||||
static void ethash_hash(
|
||||
ethash_return_value *ret,
|
||||
static void ethash_hash(ethash_return_value *ret,
|
||||
node const *full_nodes,
|
||||
ethash_cache const *cache,
|
||||
ethash_params const *params,
|
||||
const uint8_t header_hash[32],
|
||||
const uint64_t nonce) {
|
||||
ethash_blockhash_t const *header_hash,
|
||||
const uint64_t nonce)
|
||||
{
|
||||
|
||||
assert((params->full_size % MIX_WORDS) == 0);
|
||||
|
||||
|
|
@ -251,16 +250,16 @@ static void ethash_hash(
|
|||
}
|
||||
#endif
|
||||
|
||||
memcpy(ret->mix_hash, mix->bytes, 32);
|
||||
memcpy(&ret->mix_hash, mix->bytes, 32);
|
||||
// final Keccak hash
|
||||
SHA3_256(ret->result, s_mix->bytes, 64 + 32); // Keccak-256(s + compressed_mix)
|
||||
SHA3_256(&ret->result, s_mix->bytes, 64 + 32); // Keccak-256(s + compressed_mix)
|
||||
}
|
||||
|
||||
void ethash_quick_hash(
|
||||
uint8_t return_hash[32],
|
||||
const uint8_t header_hash[32],
|
||||
void ethash_quick_hash(ethash_blockhash_t *return_hash,
|
||||
ethash_blockhash_t const *header_hash,
|
||||
const uint64_t nonce,
|
||||
const uint8_t mix_hash[32]) {
|
||||
ethash_blockhash_t const *mix_hash)
|
||||
{
|
||||
|
||||
uint8_t buf[64 + 32];
|
||||
memcpy(buf, header_hash, 32);
|
||||
|
|
@ -273,28 +272,39 @@ void ethash_quick_hash(
|
|||
SHA3_256(return_hash, buf, 64 + 32);
|
||||
}
|
||||
|
||||
void ethash_get_seedhash(uint8_t seedhash[32], const uint32_t block_number) {
|
||||
memset(seedhash, 0, 32);
|
||||
void ethash_get_seedhash(ethash_blockhash_t *seedhash, const uint32_t block_number)
|
||||
{
|
||||
ethash_blockhash_reset(seedhash);
|
||||
const uint32_t epochs = block_number / EPOCH_LENGTH;
|
||||
for (uint32_t i = 0; i < epochs; ++i)
|
||||
SHA3_256(seedhash, seedhash, 32);
|
||||
SHA3_256(seedhash, (uint8_t*)seedhash, 32);
|
||||
}
|
||||
|
||||
int ethash_quick_check_difficulty(
|
||||
const uint8_t header_hash[32],
|
||||
int ethash_quick_check_difficulty(ethash_blockhash_t const *header_hash,
|
||||
const uint64_t nonce,
|
||||
const uint8_t mix_hash[32],
|
||||
const uint8_t difficulty[32]) {
|
||||
ethash_blockhash_t const *mix_hash,
|
||||
ethash_blockhash_t const *difficulty)
|
||||
{
|
||||
|
||||
uint8_t return_hash[32];
|
||||
ethash_quick_hash(return_hash, header_hash, nonce, mix_hash);
|
||||
return ethash_check_difficulty(return_hash, difficulty);
|
||||
ethash_blockhash_t return_hash;
|
||||
ethash_quick_hash(&return_hash, header_hash, nonce, mix_hash);
|
||||
return ethash_check_difficulty(&return_hash, difficulty);
|
||||
}
|
||||
|
||||
void ethash_full(ethash_return_value *ret, void const *full_mem, ethash_params const *params, const uint8_t previous_hash[32], const uint64_t nonce) {
|
||||
ethash_hash(ret, (node const *) full_mem, NULL, params, previous_hash, nonce);
|
||||
void ethash_full(ethash_return_value *ret,
|
||||
void const *full_mem,
|
||||
ethash_params const *params,
|
||||
ethash_blockhash_t const *header_hash,
|
||||
const uint64_t nonce)
|
||||
{
|
||||
ethash_hash(ret, (node const *) full_mem, NULL, params, header_hash, nonce);
|
||||
}
|
||||
|
||||
void ethash_light(ethash_return_value *ret, ethash_cache const *cache, ethash_params const *params, const uint8_t previous_hash[32], const uint64_t nonce) {
|
||||
ethash_hash(ret, NULL, cache, params, previous_hash, nonce);
|
||||
void ethash_light(ethash_return_value *ret,
|
||||
ethash_cache const *cache,
|
||||
ethash_params const *params,
|
||||
ethash_blockhash_t const *header_hash,
|
||||
const uint64_t nonce)
|
||||
{
|
||||
ethash_hash(ret, NULL, cache, params, header_hash, nonce);
|
||||
}
|
||||
13
Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/internal.h
generated
vendored
13
Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/internal.h
generated
vendored
|
|
@ -30,18 +30,15 @@ typedef union node {
|
|||
|
||||
} node;
|
||||
|
||||
void ethash_calculate_dag_item(
|
||||
node *const ret,
|
||||
void ethash_calculate_dag_item(node *const ret,
|
||||
const unsigned node_index,
|
||||
ethash_params const *params,
|
||||
ethash_cache const *cache
|
||||
);
|
||||
ethash_cache const *cache);
|
||||
|
||||
void ethash_quick_hash(
|
||||
uint8_t return_hash[32],
|
||||
const uint8_t header_hash[32],
|
||||
void ethash_quick_hash(ethash_blockhash_t *return_hash,
|
||||
ethash_blockhash_t const *header_hash,
|
||||
const uint64_t nonce,
|
||||
const uint8_t mix_hash[32]);
|
||||
ethash_blockhash_t const *mix_hash);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
|
|
|
|||
89
Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/io.c
generated
vendored
Normal file
89
Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/io.c
generated
vendored
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
/*
|
||||
This file is part of ethash.
|
||||
|
||||
ethash is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
ethash 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 General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with ethash. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
/** @file io.c
|
||||
* @author Lefteris Karapetsas <lefteris@ethdev.com>
|
||||
* @date 2015
|
||||
*/
|
||||
#include "io.h"
|
||||
#include <string.h>
|
||||
#include <stdio.h>
|
||||
|
||||
// silly macro to save some typing
|
||||
#define PASS_ARR(c_) (c_), sizeof(c_)
|
||||
|
||||
static bool ethash_io_write_file(char const *dirname,
|
||||
char const* filename,
|
||||
size_t filename_length,
|
||||
void const* data,
|
||||
size_t data_size)
|
||||
{
|
||||
bool ret = false;
|
||||
char *fullname = ethash_io_create_filename(dirname, filename, filename_length);
|
||||
if (!fullname) {
|
||||
return false;
|
||||
}
|
||||
FILE *f = fopen(fullname, "wb");
|
||||
if (!f) {
|
||||
goto free_name;
|
||||
}
|
||||
if (data_size != fwrite(data, 1, data_size, f)) {
|
||||
goto close;
|
||||
}
|
||||
|
||||
ret = true;
|
||||
close:
|
||||
fclose(f);
|
||||
free_name:
|
||||
free(fullname);
|
||||
return ret;
|
||||
}
|
||||
|
||||
bool ethash_io_write(char const *dirname,
|
||||
ethash_params const* params,
|
||||
ethash_blockhash_t seedhash,
|
||||
void const* cache,
|
||||
uint8_t **data,
|
||||
uint64_t *data_size)
|
||||
{
|
||||
char info_buffer[DAG_MEMO_BYTESIZE];
|
||||
// allocate the bytes
|
||||
uint8_t *temp_data_ptr = malloc((size_t)params->full_size);
|
||||
if (!temp_data_ptr) {
|
||||
goto end;
|
||||
}
|
||||
ethash_compute_full_data(temp_data_ptr, params, cache);
|
||||
|
||||
if (!ethash_io_write_file(dirname, PASS_ARR(DAG_FILE_NAME), temp_data_ptr, (size_t)params->full_size)) {
|
||||
goto fail_free;
|
||||
}
|
||||
|
||||
ethash_io_serialize_info(REVISION, seedhash, info_buffer);
|
||||
if (!ethash_io_write_file(dirname, PASS_ARR(DAG_MEMO_NAME), info_buffer, DAG_MEMO_BYTESIZE)) {
|
||||
goto fail_free;
|
||||
}
|
||||
|
||||
*data = temp_data_ptr;
|
||||
*data_size = params->full_size;
|
||||
return true;
|
||||
|
||||
fail_free:
|
||||
free(temp_data_ptr);
|
||||
end:
|
||||
return false;
|
||||
}
|
||||
|
||||
#undef PASS_ARR
|
||||
115
Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/io.h
generated
vendored
Normal file
115
Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/io.h
generated
vendored
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
/*
|
||||
This file is part of ethash.
|
||||
|
||||
ethash is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
ethash 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 General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with ethash. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
/** @file io.h
|
||||
* @author Lefteris Karapetsas <lefteris@ethdev.com>
|
||||
* @date 2015
|
||||
*/
|
||||
#pragma once
|
||||
#include <stdlib.h>
|
||||
#include <stdint.h>
|
||||
#include <stdbool.h>
|
||||
#include "ethash.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
static const char DAG_FILE_NAME[] = "full";
|
||||
static const char DAG_MEMO_NAME[] = "full.info";
|
||||
// MSVC thinks that "static const unsigned int" is not a compile time variable. Sorry for the #define :(
|
||||
#define DAG_MEMO_BYTESIZE 36
|
||||
|
||||
/// Possible return values of @see ethash_io_prepare
|
||||
enum ethash_io_rc {
|
||||
ETHASH_IO_FAIL = 0, ///< There has been an IO failure
|
||||
ETHASH_IO_MEMO_MISMATCH, ///< Memo file either did not exist or there was content mismatch
|
||||
ETHASH_IO_MEMO_MATCH, ///< Memo file existed and contents matched. No need to do anything
|
||||
};
|
||||
|
||||
/**
|
||||
* Prepares io for ethash
|
||||
*
|
||||
* Create the DAG directory if it does not exist, and check if the memo file matches.
|
||||
* If it does not match then it's deleted to pave the way for @ref ethash_io_write()
|
||||
*
|
||||
* @param dirname A null terminated c-string of the path of the ethash
|
||||
* data directory. If it does not exist it's created.
|
||||
* @param seedhash The seedhash of the current block number
|
||||
* @return For possible return values @see enum ethash_io_rc
|
||||
*/
|
||||
enum ethash_io_rc ethash_io_prepare(char const *dirname, ethash_blockhash_t seedhash);
|
||||
|
||||
/**
|
||||
* Fully computes data and writes it to the file on disk.
|
||||
*
|
||||
* This function should be called after @see ethash_io_prepare() and only if
|
||||
* its return value is @c ETHASH_IO_MEMO_MISMATCH. Will write both the full data
|
||||
* and the memo file.
|
||||
*
|
||||
* @param[in] dirname A null terminated c-string of the path of the ethash
|
||||
* data directory. Has to exist.
|
||||
* @param[in] params An ethash_params object containing the full size
|
||||
* and the cache size
|
||||
* @param[in] seedhash The seedhash of the current block number
|
||||
* @param[in] cache The cache data. Would have usually been calulated by
|
||||
* @see ethash_prep_light().
|
||||
* @param[out] data Pass a pointer to uint8_t by reference here. If the
|
||||
* function is succesfull then this point to the allocated
|
||||
* data calculated by @see ethash_prep_full(). Memory
|
||||
* ownership is transfered to the callee. Remember that
|
||||
* you eventually need to free this with a call to free().
|
||||
* @param[out] data_size Pass a uint64_t by value. If the function is succesfull
|
||||
* then this will contain the number of bytes allocated
|
||||
* for @a data.
|
||||
* @return True for success and false in case of failure.
|
||||
*/
|
||||
bool ethash_io_write(char const *dirname,
|
||||
ethash_params const* params,
|
||||
ethash_blockhash_t seedhash,
|
||||
void const* cache,
|
||||
uint8_t **data,
|
||||
uint64_t *data_size);
|
||||
|
||||
static inline void ethash_io_serialize_info(uint32_t revision,
|
||||
ethash_blockhash_t seed_hash,
|
||||
char *output)
|
||||
{
|
||||
// if .info is only consumed locally we don't really care about endianess
|
||||
memcpy(output, &revision, 4);
|
||||
memcpy(output + 4, &seed_hash, 32);
|
||||
}
|
||||
|
||||
static inline char *ethash_io_create_filename(char const *dirname,
|
||||
char const* filename,
|
||||
size_t filename_length)
|
||||
{
|
||||
// in C the cast is not needed, but a C++ compiler will complain for invalid conversion
|
||||
char *name = (char*)malloc(strlen(dirname) + filename_length);
|
||||
if (!name) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
name[0] = '\0';
|
||||
strcat(name, dirname);
|
||||
strcat(name, filename);
|
||||
return name;
|
||||
}
|
||||
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
76
Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/io_posix.c
generated
vendored
Normal file
76
Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/io_posix.c
generated
vendored
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
/*
|
||||
This file is part of ethash.
|
||||
|
||||
ethash is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
ethash 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 General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with ethash. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
/** @file io_posix.c
|
||||
* @author Lefteris Karapetsas <lefteris@ethdev.com>
|
||||
* @date 2015
|
||||
*/
|
||||
|
||||
#include "io.h"
|
||||
#include <sys/types.h>
|
||||
#include <sys/stat.h>
|
||||
#include <errno.h>
|
||||
#include <libgen.h>
|
||||
#include <stdio.h>
|
||||
#include <unistd.h>
|
||||
|
||||
enum ethash_io_rc ethash_io_prepare(char const *dirname, ethash_blockhash_t seedhash)
|
||||
{
|
||||
char read_buffer[DAG_MEMO_BYTESIZE];
|
||||
char expect_buffer[DAG_MEMO_BYTESIZE];
|
||||
enum ethash_io_rc ret = ETHASH_IO_FAIL;
|
||||
|
||||
// assert directory exists, full owner permissions and read/search for others
|
||||
int rc = mkdir(dirname, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
|
||||
if (rc == -1 && errno != EEXIST) {
|
||||
goto end;
|
||||
}
|
||||
|
||||
char *memofile = ethash_io_create_filename(dirname, DAG_MEMO_NAME, sizeof(DAG_MEMO_NAME));
|
||||
if (!memofile) {
|
||||
goto end;
|
||||
}
|
||||
|
||||
// try to open memo file
|
||||
FILE *f = fopen(memofile, "rb");
|
||||
if (!f) {
|
||||
// file does not exist, so no checking happens. All is fine.
|
||||
ret = ETHASH_IO_MEMO_MISMATCH;
|
||||
goto free_memo;
|
||||
}
|
||||
|
||||
if (fread(read_buffer, 1, DAG_MEMO_BYTESIZE, f) != DAG_MEMO_BYTESIZE) {
|
||||
goto close;
|
||||
}
|
||||
|
||||
ethash_io_serialize_info(REVISION, seedhash, expect_buffer);
|
||||
if (memcmp(read_buffer, expect_buffer, DAG_MEMO_BYTESIZE) != 0) {
|
||||
// we have different memo contents so delete the memo file
|
||||
if (unlink(memofile) != 0) {
|
||||
goto close;
|
||||
}
|
||||
ret = ETHASH_IO_MEMO_MISMATCH;
|
||||
}
|
||||
|
||||
ret = ETHASH_IO_MEMO_MATCH;
|
||||
|
||||
close:
|
||||
fclose(f);
|
||||
free_memo:
|
||||
free(memofile);
|
||||
end:
|
||||
return ret;
|
||||
}
|
||||
73
Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/io_win32.c
generated
vendored
Normal file
73
Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/io_win32.c
generated
vendored
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
/*
|
||||
This file is part of ethash.
|
||||
|
||||
ethash is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
ethash 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 General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with ethash. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
/** @file io_win32.c
|
||||
* @author Lefteris Karapetsas <lefteris@ethdev.com>
|
||||
* @date 2015
|
||||
*/
|
||||
|
||||
#include "io.h"
|
||||
#include <direct.h>
|
||||
#include <errno.h>
|
||||
#include <stdio.h>
|
||||
|
||||
enum ethash_io_rc ethash_io_prepare(char const *dirname, ethash_blockhash_t seedhash)
|
||||
{
|
||||
char read_buffer[DAG_MEMO_BYTESIZE];
|
||||
char expect_buffer[DAG_MEMO_BYTESIZE];
|
||||
enum ethash_io_rc ret = ETHASH_IO_FAIL;
|
||||
|
||||
// assert directory exists
|
||||
int rc = _mkdir(dirname);
|
||||
if (rc == -1 && errno != EEXIST) {
|
||||
goto end;
|
||||
}
|
||||
|
||||
char *memofile = ethash_io_create_filename(dirname, DAG_MEMO_NAME, sizeof(DAG_MEMO_NAME));
|
||||
if (!memofile) {
|
||||
goto end;
|
||||
}
|
||||
|
||||
// try to open memo file
|
||||
FILE *f = fopen(memofile, "rb");
|
||||
if (!f) {
|
||||
// file does not exist, so no checking happens. All is fine.
|
||||
ret = ETHASH_IO_MEMO_MISMATCH;
|
||||
goto free_memo;
|
||||
}
|
||||
|
||||
if (fread(read_buffer, 1, DAG_MEMO_BYTESIZE, f) != DAG_MEMO_BYTESIZE) {
|
||||
goto close;
|
||||
}
|
||||
|
||||
ethash_io_serialize_info(REVISION, seedhash, expect_buffer);
|
||||
if (memcmp(read_buffer, expect_buffer, DAG_MEMO_BYTESIZE) != 0) {
|
||||
// we have different memo contents so delete the memo file
|
||||
if (_unlink(memofile) != 0) {
|
||||
goto close;
|
||||
}
|
||||
ret = ETHASH_IO_MEMO_MISMATCH;
|
||||
}
|
||||
|
||||
ret = ETHASH_IO_MEMO_MATCH;
|
||||
|
||||
close:
|
||||
fclose(f);
|
||||
free_memo:
|
||||
free(memofile);
|
||||
end:
|
||||
return ret;
|
||||
}
|
||||
10
Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/sha3.h
generated
vendored
10
Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/sha3.h
generated
vendored
|
|
@ -8,17 +8,21 @@ extern "C" {
|
|||
#include <stdint.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
struct ethash_blockhash;
|
||||
|
||||
#define decsha3(bits) \
|
||||
int sha3_##bits(uint8_t*, size_t, const uint8_t*, size_t);
|
||||
|
||||
decsha3(256)
|
||||
decsha3(512)
|
||||
|
||||
static inline void SHA3_256(uint8_t * const ret, uint8_t const *data, const size_t size) {
|
||||
sha3_256(ret, 32, data, size);
|
||||
static inline void SHA3_256(struct ethash_blockhash const* ret, uint8_t const *data, const size_t size)
|
||||
{
|
||||
sha3_256((uint8_t*)ret, 32, data, size);
|
||||
}
|
||||
|
||||
static inline void SHA3_512(uint8_t * const ret, uint8_t const *data, const size_t size) {
|
||||
static inline void SHA3_512(uint8_t *ret, uint8_t const *data, const size_t size)
|
||||
{
|
||||
sha3_512(ret, 64, data, size);
|
||||
}
|
||||
|
||||
|
|
|
|||
7
Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/sha3_cryptopp.cpp
generated
vendored
7
Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/sha3_cryptopp.cpp
generated
vendored
|
|
@ -19,13 +19,14 @@
|
|||
* @author Tim Hughes <tim@twistedfury.com>
|
||||
* @date 2015
|
||||
*/
|
||||
|
||||
#include <stdint.h>
|
||||
#include <cryptopp/sha3.h>
|
||||
|
||||
extern "C" {
|
||||
void SHA3_256(uint8_t *const ret, const uint8_t *data, size_t size) {
|
||||
CryptoPP::SHA3_256().CalculateDigest(ret, data, size);
|
||||
struct ethash_blockhash;
|
||||
typedef struct ethash_blockhash ethash_blockhash_t;
|
||||
void SHA3_256(ethash_blockhash_t const* ret, const uint8_t *data, size_t size) {
|
||||
CryptoPP::SHA3_256().CalculateDigest((uint8_t*)ret, data, size);
|
||||
}
|
||||
|
||||
void SHA3_512(uint8_t *const ret, const uint8_t *data, size_t size) {
|
||||
|
|
|
|||
6
Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/sha3_cryptopp.h
generated
vendored
6
Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/sha3_cryptopp.h
generated
vendored
|
|
@ -2,12 +2,16 @@
|
|||
|
||||
#include "compiler.h"
|
||||
#include <stdint.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
void SHA3_256(uint8_t *const ret, const uint8_t *data, size_t size);
|
||||
struct ethash_blockhash;
|
||||
typedef struct ethash_blockhash ethash_blockhash_t;
|
||||
|
||||
void SHA3_256(ethash_blockhash_t *const ret, const uint8_t *data, size_t size);
|
||||
void SHA3_512(uint8_t *const ret, const uint8_t *data, size_t size);
|
||||
|
||||
#ifdef __cplusplus
|
||||
|
|
|
|||
98
Godeps/_workspace/src/github.com/ethereum/ethash/src/python/core.c
generated
vendored
98
Godeps/_workspace/src/github.com/ethereum/ethash/src/python/core.c
generated
vendored
|
|
@ -5,6 +5,14 @@
|
|||
#include <time.h>
|
||||
#include "../libethash/ethash.h"
|
||||
|
||||
#if PY_MAJOR_VERSION >= 3
|
||||
#define PY_STRING_FORMAT "y#"
|
||||
#define PY_CONST_STRING_FORMAT "y"
|
||||
#else
|
||||
#define PY_STRING_FORMAT "s#"
|
||||
#define PY_CONST_STRING_FORMAT "s"
|
||||
#endif
|
||||
|
||||
#define MIX_WORDS (MIX_BYTES/4)
|
||||
|
||||
static PyObject *
|
||||
|
|
@ -46,7 +54,7 @@ mkcache_bytes(PyObject *self, PyObject *args) {
|
|||
unsigned long cache_size;
|
||||
int seed_len;
|
||||
|
||||
if (!PyArg_ParseTuple(args, "ks#", &cache_size, &seed, &seed_len))
|
||||
if (!PyArg_ParseTuple(args, "k" PY_STRING_FORMAT, &cache_size, &seed, &seed_len))
|
||||
return 0;
|
||||
|
||||
if (seed_len != 32) {
|
||||
|
|
@ -61,8 +69,8 @@ mkcache_bytes(PyObject *self, PyObject *args) {
|
|||
params.cache_size = (size_t) cache_size;
|
||||
ethash_cache cache;
|
||||
cache.mem = malloc(cache_size);
|
||||
ethash_mkcache(&cache, ¶ms, (uint8_t *) seed);
|
||||
PyObject * val = Py_BuildValue("s#", cache.mem, cache_size);
|
||||
ethash_mkcache(&cache, ¶ms, (ethash_blockhash_t *) seed);
|
||||
PyObject * val = Py_BuildValue(PY_STRING_FORMAT, cache.mem, cache_size);
|
||||
free(cache.mem);
|
||||
return val;
|
||||
}
|
||||
|
|
@ -74,7 +82,7 @@ calc_dataset_bytes(PyObject *self, PyObject *args) {
|
|||
unsigned long full_size;
|
||||
int cache_size;
|
||||
|
||||
if (!PyArg_ParseTuple(args, "ks#", &full_size, &cache_bytes, &cache_size))
|
||||
if (!PyArg_ParseTuple(args, "k" PY_STRING_FORMAT, &full_size, &cache_bytes, &cache_size))
|
||||
return 0;
|
||||
|
||||
if (full_size % MIX_WORDS != 0) {
|
||||
|
|
@ -98,7 +106,7 @@ calc_dataset_bytes(PyObject *self, PyObject *args) {
|
|||
cache.mem = (void *) cache_bytes;
|
||||
void *mem = malloc(params.full_size);
|
||||
ethash_compute_full_data(mem, ¶ms, &cache);
|
||||
PyObject * val = Py_BuildValue("s#", (char *) mem, full_size);
|
||||
PyObject * val = Py_BuildValue(PY_STRING_FORMAT, (char *) mem, full_size);
|
||||
free(mem);
|
||||
return val;
|
||||
}
|
||||
|
|
@ -106,28 +114,25 @@ calc_dataset_bytes(PyObject *self, PyObject *args) {
|
|||
// hashimoto_light(full_size, cache, header, nonce)
|
||||
static PyObject *
|
||||
hashimoto_light(PyObject *self, PyObject *args) {
|
||||
char *cache_bytes, *header;
|
||||
char *cache_bytes;
|
||||
char *header;
|
||||
unsigned long full_size;
|
||||
unsigned long long nonce;
|
||||
int cache_size, header_size;
|
||||
|
||||
if (!PyArg_ParseTuple(args, "ks#s#K", &full_size, &cache_bytes, &cache_size, &header, &header_size, &nonce))
|
||||
if (!PyArg_ParseTuple(args, "k" PY_STRING_FORMAT PY_STRING_FORMAT "K", &full_size, &cache_bytes, &cache_size, &header, &header_size, &nonce))
|
||||
return 0;
|
||||
|
||||
if (full_size % MIX_WORDS != 0) {
|
||||
char error_message[1024];
|
||||
sprintf(error_message, "The size of data set must be a multiple of %i bytes (was %lu)", MIX_WORDS, full_size);
|
||||
PyErr_SetString(PyExc_ValueError, error_message);
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (cache_size % HASH_BYTES != 0) {
|
||||
char error_message[1024];
|
||||
sprintf(error_message, "The size of the cache must be a multiple of %i bytes (was %i)", HASH_BYTES, cache_size);
|
||||
PyErr_SetString(PyExc_ValueError, error_message);
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (header_size != 32) {
|
||||
char error_message[1024];
|
||||
sprintf(error_message, "Seed must be 32 bytes long (was %i)", header_size);
|
||||
|
|
@ -135,27 +140,27 @@ hashimoto_light(PyObject *self, PyObject *args) {
|
|||
return 0;
|
||||
}
|
||||
|
||||
|
||||
ethash_return_value out;
|
||||
ethash_params params;
|
||||
params.cache_size = (size_t) cache_size;
|
||||
params.full_size = (size_t) full_size;
|
||||
ethash_cache cache;
|
||||
cache.mem = (void *) cache_bytes;
|
||||
ethash_light(&out, &cache, ¶ms, (uint8_t *) header, nonce);
|
||||
return Py_BuildValue("{s:s#,s:s#}",
|
||||
"mix digest", out.mix_hash, 32,
|
||||
"result", out.result, 32);
|
||||
ethash_light(&out, &cache, ¶ms, (ethash_blockhash_t *) header, nonce);
|
||||
return Py_BuildValue("{" PY_CONST_STRING_FORMAT ":" PY_STRING_FORMAT "," PY_CONST_STRING_FORMAT ":" PY_STRING_FORMAT "}",
|
||||
"mix digest", &out.mix_hash, 32,
|
||||
"result", &out.result, 32);
|
||||
}
|
||||
|
||||
// hashimoto_full(dataset, header, nonce)
|
||||
static PyObject *
|
||||
hashimoto_full(PyObject *self, PyObject *args) {
|
||||
char *full_bytes, *header;
|
||||
char *full_bytes;
|
||||
char *header;
|
||||
unsigned long long nonce;
|
||||
int full_size, header_size;
|
||||
|
||||
if (!PyArg_ParseTuple(args, "s#s#K", &full_bytes, &full_size, &header, &header_size, &nonce))
|
||||
if (!PyArg_ParseTuple(args, PY_STRING_FORMAT PY_STRING_FORMAT "K", &full_bytes, &full_size, &header, &header_size, &nonce))
|
||||
return 0;
|
||||
|
||||
if (full_size % MIX_WORDS != 0) {
|
||||
|
|
@ -176,21 +181,23 @@ hashimoto_full(PyObject *self, PyObject *args) {
|
|||
ethash_return_value out;
|
||||
ethash_params params;
|
||||
params.full_size = (size_t) full_size;
|
||||
ethash_full(&out, (void *) full_bytes, ¶ms, (uint8_t *) header, nonce);
|
||||
return Py_BuildValue("{s:s#, s:s#}",
|
||||
"mix digest", out.mix_hash, 32,
|
||||
"result", out.result, 32);
|
||||
ethash_full(&out, (void *) full_bytes, ¶ms, (ethash_blockhash_t *) header, nonce);
|
||||
return Py_BuildValue("{" PY_CONST_STRING_FORMAT ":" PY_STRING_FORMAT ", " PY_CONST_STRING_FORMAT ":" PY_STRING_FORMAT "}",
|
||||
"mix digest", &out.mix_hash, 32,
|
||||
"result", &out.result, 32);
|
||||
}
|
||||
|
||||
// mine(dataset_bytes, header, difficulty_bytes)
|
||||
static PyObject *
|
||||
mine(PyObject *self, PyObject *args) {
|
||||
char *full_bytes, *header, *difficulty;
|
||||
char *full_bytes;
|
||||
char *header;
|
||||
char *difficulty;
|
||||
srand(time(0));
|
||||
uint64_t nonce = ((uint64_t) rand()) << 32 | rand();
|
||||
int full_size, header_size, difficulty_size;
|
||||
|
||||
if (!PyArg_ParseTuple(args, "s#s#s#", &full_bytes, &full_size, &header, &header_size, &difficulty, &difficulty_size))
|
||||
if (!PyArg_ParseTuple(args, PY_STRING_FORMAT PY_STRING_FORMAT PY_STRING_FORMAT, &full_bytes, &full_size, &header, &header_size, &difficulty, &difficulty_size))
|
||||
return 0;
|
||||
|
||||
if (full_size % MIX_WORDS != 0) {
|
||||
|
|
@ -220,13 +227,13 @@ mine(PyObject *self, PyObject *args) {
|
|||
|
||||
// TODO: Multi threading?
|
||||
do {
|
||||
ethash_full(&out, (void *) full_bytes, ¶ms, (const uint8_t *) header, nonce++);
|
||||
ethash_full(&out, (void *) full_bytes, ¶ms, (const ethash_blockhash_t *) header, nonce++);
|
||||
// TODO: disagrees with the spec https://github.com/ethereum/wiki/wiki/Ethash#mining
|
||||
} while (!ethash_check_difficulty(out.result, (const uint8_t *) difficulty));
|
||||
} while (!ethash_check_difficulty(&out.result, (const ethash_blockhash_t *) difficulty));
|
||||
|
||||
return Py_BuildValue("{s:s#, s:s#, s:K}",
|
||||
"mix digest", out.mix_hash, 32,
|
||||
"result", out.result, 32,
|
||||
return Py_BuildValue("{" PY_CONST_STRING_FORMAT ":" PY_STRING_FORMAT ", " PY_CONST_STRING_FORMAT ":" PY_STRING_FORMAT ", " PY_CONST_STRING_FORMAT ":K}",
|
||||
"mix digest", &out.mix_hash, 32,
|
||||
"result", &out.result, 32,
|
||||
"nonce", nonce);
|
||||
}
|
||||
|
||||
|
|
@ -243,9 +250,9 @@ get_seedhash(PyObject *self, PyObject *args) {
|
|||
PyErr_SetString(PyExc_ValueError, error_message);
|
||||
return 0;
|
||||
}
|
||||
uint8_t seedhash[32];
|
||||
ethash_get_seedhash(seedhash, block_number);
|
||||
return Py_BuildValue("s#", (char *) seedhash, 32);
|
||||
ethash_blockhash_t seedhash;
|
||||
ethash_get_seedhash(&seedhash, block_number);
|
||||
return Py_BuildValue(PY_STRING_FORMAT, (char *) &seedhash, 32);
|
||||
}
|
||||
|
||||
static PyMethodDef PyethashMethods[] =
|
||||
|
|
@ -287,6 +294,32 @@ static PyMethodDef PyethashMethods[] =
|
|||
{NULL, NULL, 0, NULL}
|
||||
};
|
||||
|
||||
#if PY_MAJOR_VERSION >= 3
|
||||
static struct PyModuleDef PyethashModule = {
|
||||
PyModuleDef_HEAD_INIT,
|
||||
"pyethash",
|
||||
"...",
|
||||
-1,
|
||||
PyethashMethods
|
||||
};
|
||||
|
||||
PyMODINIT_FUNC PyInit_pyethash(void) {
|
||||
PyObject *module = PyModule_Create(&PyethashModule);
|
||||
// Following Spec: https://github.com/ethereum/wiki/wiki/Ethash#definitions
|
||||
PyModule_AddIntConstant(module, "REVISION", (long) REVISION);
|
||||
PyModule_AddIntConstant(module, "DATASET_BYTES_INIT", (long) DATASET_BYTES_INIT);
|
||||
PyModule_AddIntConstant(module, "DATASET_BYTES_GROWTH", (long) DATASET_BYTES_GROWTH);
|
||||
PyModule_AddIntConstant(module, "CACHE_BYTES_INIT", (long) CACHE_BYTES_INIT);
|
||||
PyModule_AddIntConstant(module, "CACHE_BYTES_GROWTH", (long) CACHE_BYTES_GROWTH);
|
||||
PyModule_AddIntConstant(module, "EPOCH_LENGTH", (long) EPOCH_LENGTH);
|
||||
PyModule_AddIntConstant(module, "MIX_BYTES", (long) MIX_BYTES);
|
||||
PyModule_AddIntConstant(module, "HASH_BYTES", (long) HASH_BYTES);
|
||||
PyModule_AddIntConstant(module, "DATASET_PARENTS", (long) DATASET_PARENTS);
|
||||
PyModule_AddIntConstant(module, "CACHE_ROUNDS", (long) CACHE_ROUNDS);
|
||||
PyModule_AddIntConstant(module, "ACCESSES", (long) ACCESSES);
|
||||
return module;
|
||||
}
|
||||
#else
|
||||
PyMODINIT_FUNC
|
||||
initpyethash(void) {
|
||||
PyObject *module = Py_InitModule("pyethash", PyethashMethods);
|
||||
|
|
@ -303,3 +336,4 @@ initpyethash(void) {
|
|||
PyModule_AddIntConstant(module, "CACHE_ROUNDS", (long) CACHE_ROUNDS);
|
||||
PyModule_AddIntConstant(module, "ACCESSES", (long) ACCESSES);
|
||||
}
|
||||
#endif
|
||||
|
|
|
|||
39
Godeps/_workspace/src/github.com/ethereum/ethash/test/c/CMakeLists.txt
generated
vendored
39
Godeps/_workspace/src/github.com/ethereum/ethash/test/c/CMakeLists.txt
generated
vendored
|
|
@ -1,5 +1,30 @@
|
|||
if (MSVC)
|
||||
if (NOT BOOST_ROOT)
|
||||
set (BOOST_ROOT "$ENV{BOOST_ROOT}")
|
||||
endif()
|
||||
set (CMAKE_PREFIX_PATH BOOST_ROOT)
|
||||
endif()
|
||||
|
||||
IF( NOT Boost_FOUND )
|
||||
find_package(Boost COMPONENTS unit_test_framework)
|
||||
# use multithreaded boost libraries, with -mt suffix
|
||||
set(Boost_USE_MULTITHREADED ON)
|
||||
|
||||
if (MSVC)
|
||||
# TODO handle other msvc versions or it will fail find them
|
||||
set(Boost_COMPILER -vc120)
|
||||
# use static boost libraries *.lib
|
||||
set(Boost_USE_STATIC_LIBS ON)
|
||||
elseif (APPLE)
|
||||
|
||||
# use static boost libraries *.a
|
||||
set(Boost_USE_STATIC_LIBS ON)
|
||||
|
||||
elseif (UNIX)
|
||||
# use dynamic boost libraries .dll
|
||||
set(Boost_USE_STATIC_LIBS OFF)
|
||||
|
||||
endif()
|
||||
find_package(Boost 1.48.0 COMPONENTS unit_test_framework system filesystem)
|
||||
ENDIF()
|
||||
|
||||
IF( Boost_FOUND )
|
||||
|
|
@ -8,8 +33,9 @@ IF( Boost_FOUND )
|
|||
|
||||
link_directories ( ${Boost_LIBRARY_DIRS} )
|
||||
file(GLOB HEADERS "*.h")
|
||||
if (NOT MSVC)
|
||||
ADD_DEFINITIONS(-DBOOST_TEST_DYN_LINK)
|
||||
|
||||
endif()
|
||||
if (NOT CRYPTOPP_FOUND)
|
||||
find_package (CryptoPP)
|
||||
endif()
|
||||
|
|
@ -18,8 +44,15 @@ IF( Boost_FOUND )
|
|||
add_definitions(-DWITH_CRYPTOPP)
|
||||
endif()
|
||||
|
||||
if (NOT MSVC)
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 ")
|
||||
endif()
|
||||
|
||||
add_executable (Test test.cpp ${HEADERS})
|
||||
target_link_libraries (Test ${Boost_UNIT_TEST_FRAMEWORK_LIBRARY} ${ETHHASH_LIBS})
|
||||
target_link_libraries(Test ${ETHHASH_LIBS})
|
||||
target_link_libraries(Test ${Boost_FILESYSTEM_LIBRARIES})
|
||||
target_link_libraries(Test ${Boost_SYSTEM_LIBRARIES})
|
||||
target_link_libraries (Test ${Boost_UNIT_TEST_FRAMEWORK_LIBRARY})
|
||||
|
||||
if (CRYPTOPP_FOUND)
|
||||
TARGET_LINK_LIBRARIES(Test ${CRYPTOPP_LIBRARIES})
|
||||
|
|
|
|||
262
Godeps/_workspace/src/github.com/ethereum/ethash/test/c/test.cpp
generated
vendored
262
Godeps/_workspace/src/github.com/ethereum/ethash/test/c/test.cpp
generated
vendored
|
|
@ -2,6 +2,7 @@
|
|||
#include <libethash/fnv.h>
|
||||
#include <libethash/ethash.h>
|
||||
#include <libethash/internal.h>
|
||||
#include <libethash/io.h>
|
||||
|
||||
#ifdef WITH_CRYPTOPP
|
||||
|
||||
|
|
@ -14,18 +15,32 @@
|
|||
#define BOOST_TEST_MODULE Daggerhashimoto
|
||||
#define BOOST_TEST_MAIN
|
||||
|
||||
#include <boost/test/unit_test.hpp>
|
||||
#include <iostream>
|
||||
#include <fstream>
|
||||
#include <vector>
|
||||
#include <boost/filesystem.hpp>
|
||||
#include <boost/test/unit_test.hpp>
|
||||
|
||||
std::string bytesToHexString(const uint8_t *str, const size_t s) {
|
||||
using namespace std;
|
||||
namespace fs = boost::filesystem;
|
||||
|
||||
// Just an alloca "wrapper" to silence uint64_t to size_t conversion warnings in windows
|
||||
// consider replacing alloca calls with something better though!
|
||||
#define our_alloca(param__) alloca((size_t)(param__))
|
||||
|
||||
std::string bytesToHexString(const uint8_t *str, const uint64_t s) {
|
||||
std::ostringstream ret;
|
||||
|
||||
for (int i = 0; i < s; ++i)
|
||||
for (size_t i = 0; i < s; ++i)
|
||||
ret << std::hex << std::setfill('0') << std::setw(2) << std::nouppercase << (int) str[i];
|
||||
|
||||
return ret.str();
|
||||
}
|
||||
|
||||
std::string blockhashToHexString(ethash_blockhash_t *hash) {
|
||||
return bytesToHexString((uint8_t*)hash, 32);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(fnv_hash_check) {
|
||||
uint32_t x = 1235U;
|
||||
const uint32_t
|
||||
|
|
@ -41,12 +56,13 @@ BOOST_AUTO_TEST_CASE(fnv_hash_check) {
|
|||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(SHA256_check) {
|
||||
uint8_t input[32], out[32];
|
||||
memcpy(input, "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", 32);
|
||||
SHA3_256(out, input, 32);
|
||||
ethash_blockhash_t input;
|
||||
ethash_blockhash_t out;
|
||||
memcpy(&input, "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", 32);
|
||||
SHA3_256(&out, (uint8_t*)&input, 32);
|
||||
const std::string
|
||||
expected = "2b5ddf6f4d21c23de216f44d5e4bdc68e044b71897837ea74c83908be7037cd7",
|
||||
actual = bytesToHexString(out, 32);
|
||||
actual = bytesToHexString((uint8_t*)&out, 32);
|
||||
BOOST_REQUIRE_MESSAGE(expected == actual,
|
||||
"\nexpected: " << expected.c_str() << "\n"
|
||||
<< "actual: " << actual.c_str() << "\n");
|
||||
|
|
@ -93,24 +109,27 @@ BOOST_AUTO_TEST_CASE(ethash_params_init_genesis_calcifide_check) {
|
|||
|
||||
BOOST_AUTO_TEST_CASE(light_and_full_client_checks) {
|
||||
ethash_params params;
|
||||
uint8_t seed[32], hash[32], difficulty[32];
|
||||
ethash_return_value light_out, full_out;
|
||||
memcpy(seed, "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", 32);
|
||||
memcpy(hash, "~~~X~~~~~~~~~~~~~~~~~~~~~~~~~~~~", 32);
|
||||
ethash_blockhash_t seed;
|
||||
ethash_blockhash_t hash;
|
||||
ethash_blockhash_t difficulty;
|
||||
ethash_return_value light_out;
|
||||
ethash_return_value full_out;
|
||||
memcpy(&seed, "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", 32);
|
||||
memcpy(&hash, "~~~X~~~~~~~~~~~~~~~~~~~~~~~~~~~~", 32);
|
||||
|
||||
// Set the difficulty
|
||||
difficulty[0] = 197;
|
||||
difficulty[1] = 90;
|
||||
ethash_blockhash_set(&difficulty, 0, 197);
|
||||
ethash_blockhash_set(&difficulty, 1, 90);
|
||||
for (int i = 2; i < 32; i++)
|
||||
difficulty[i] = (uint8_t) 255;
|
||||
ethash_blockhash_set(&difficulty, i, 255);
|
||||
|
||||
ethash_params_init(¶ms, 0);
|
||||
params.cache_size = 1024;
|
||||
params.full_size = 1024 * 32;
|
||||
ethash_cache cache;
|
||||
cache.mem = alloca(params.cache_size);
|
||||
ethash_mkcache(&cache, ¶ms, seed);
|
||||
node *full_mem = (node *) alloca(params.full_size);
|
||||
cache.mem = our_alloca(params.cache_size);
|
||||
ethash_mkcache(&cache, ¶ms, &seed);
|
||||
node *full_mem = (node *) our_alloca(params.full_size);
|
||||
ethash_compute_full_data(full_mem, ¶ms, &cache);
|
||||
|
||||
{
|
||||
|
|
@ -153,76 +172,217 @@ BOOST_AUTO_TEST_CASE(light_and_full_client_checks) {
|
|||
|
||||
{
|
||||
uint64_t nonce = 0x7c7c597c;
|
||||
ethash_full(&full_out, full_mem, ¶ms, hash, nonce);
|
||||
ethash_light(&light_out, &cache, ¶ms, hash, nonce);
|
||||
ethash_full(&full_out, full_mem, ¶ms, &hash, nonce);
|
||||
ethash_light(&light_out, &cache, ¶ms, &hash, nonce);
|
||||
const std::string
|
||||
light_result_string = bytesToHexString(light_out.result, 32),
|
||||
full_result_string = bytesToHexString(full_out.result, 32);
|
||||
light_result_string = blockhashToHexString(&light_out.result),
|
||||
full_result_string = blockhashToHexString(&full_out.result);
|
||||
BOOST_REQUIRE_MESSAGE(light_result_string == full_result_string,
|
||||
"\nlight result: " << light_result_string.c_str() << "\n"
|
||||
<< "full result: " << full_result_string.c_str() << "\n");
|
||||
const std::string
|
||||
light_mix_hash_string = bytesToHexString(light_out.mix_hash, 32),
|
||||
full_mix_hash_string = bytesToHexString(full_out.mix_hash, 32);
|
||||
light_mix_hash_string = blockhashToHexString(&light_out.mix_hash),
|
||||
full_mix_hash_string = blockhashToHexString(&full_out.mix_hash);
|
||||
BOOST_REQUIRE_MESSAGE(full_mix_hash_string == light_mix_hash_string,
|
||||
"\nlight mix hash: " << light_mix_hash_string.c_str() << "\n"
|
||||
<< "full mix hash: " << full_mix_hash_string.c_str() << "\n");
|
||||
uint8_t check_hash[32];
|
||||
ethash_quick_hash(check_hash, hash, nonce, full_out.mix_hash);
|
||||
const std::string check_hash_string = bytesToHexString(check_hash, 32);
|
||||
ethash_blockhash_t check_hash;
|
||||
ethash_quick_hash(&check_hash, &hash, nonce, &full_out.mix_hash);
|
||||
const std::string check_hash_string = blockhashToHexString(&check_hash);
|
||||
BOOST_REQUIRE_MESSAGE(check_hash_string == full_result_string,
|
||||
"\ncheck hash string: " << check_hash_string.c_str() << "\n"
|
||||
<< "full result: " << full_result_string.c_str() << "\n");
|
||||
}
|
||||
{
|
||||
ethash_full(&full_out, full_mem, ¶ms, hash, 5);
|
||||
ethash_full(&full_out, full_mem, ¶ms, &hash, 5);
|
||||
std::string
|
||||
light_result_string = bytesToHexString(light_out.result, 32),
|
||||
full_result_string = bytesToHexString(full_out.result, 32);
|
||||
light_result_string = blockhashToHexString(&light_out.result),
|
||||
full_result_string = blockhashToHexString(&full_out.result);
|
||||
|
||||
BOOST_REQUIRE_MESSAGE(light_result_string != full_result_string,
|
||||
"\nlight result and full result should differ: " << light_result_string.c_str() << "\n");
|
||||
|
||||
ethash_light(&light_out, &cache, ¶ms, hash, 5);
|
||||
light_result_string = bytesToHexString(light_out.result, 32);
|
||||
ethash_light(&light_out, &cache, ¶ms, &hash, 5);
|
||||
light_result_string = blockhashToHexString(&light_out.result);
|
||||
BOOST_REQUIRE_MESSAGE(light_result_string == full_result_string,
|
||||
"\nlight result and full result should be the same\n"
|
||||
<< "light result: " << light_result_string.c_str() << "\n"
|
||||
<< "full result: " << full_result_string.c_str() << "\n");
|
||||
std::string
|
||||
light_mix_hash_string = bytesToHexString(light_out.mix_hash, 32),
|
||||
full_mix_hash_string = bytesToHexString(full_out.mix_hash, 32);
|
||||
light_mix_hash_string = blockhashToHexString(&light_out.mix_hash),
|
||||
full_mix_hash_string = blockhashToHexString(&full_out.mix_hash);
|
||||
BOOST_REQUIRE_MESSAGE(full_mix_hash_string == light_mix_hash_string,
|
||||
"\nlight mix hash: " << light_mix_hash_string.c_str() << "\n"
|
||||
<< "full mix hash: " << full_mix_hash_string.c_str() << "\n");
|
||||
BOOST_REQUIRE_MESSAGE(ethash_check_difficulty(full_out.result, difficulty),
|
||||
BOOST_REQUIRE_MESSAGE(ethash_check_difficulty(&full_out.result, &difficulty),
|
||||
"ethash_check_difficulty failed"
|
||||
);
|
||||
BOOST_REQUIRE_MESSAGE(ethash_quick_check_difficulty(hash, 5U, full_out.mix_hash, difficulty),
|
||||
BOOST_REQUIRE_MESSAGE(ethash_quick_check_difficulty(&hash, 5U, &full_out.mix_hash, &difficulty),
|
||||
"ethash_quick_check_difficulty failed"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(ethash_check_difficulty_check) {
|
||||
uint8_t hash[32], target[32];
|
||||
memset(hash, 0, 32);
|
||||
memset(target, 0, 32);
|
||||
|
||||
memcpy(hash, "11111111111111111111111111111111", 32);
|
||||
memcpy(target, "22222222222222222222222222222222", 32);
|
||||
ethash_blockhash_t hash;
|
||||
ethash_blockhash_t target;
|
||||
memcpy(&hash, "11111111111111111111111111111111", 32);
|
||||
memcpy(&target, "22222222222222222222222222222222", 32);
|
||||
BOOST_REQUIRE_MESSAGE(
|
||||
ethash_check_difficulty(hash, target),
|
||||
"\nexpected \"" << std::string((char *) hash, 32).c_str() << "\" to have the same or less difficulty than \"" << std::string((char *) target, 32).c_str() << "\"\n");
|
||||
ethash_check_difficulty(&hash, &target),
|
||||
"\nexpected \"" << std::string((char *) &hash, 32).c_str() << "\" to have the same or less difficulty than \"" << std::string((char *) &target, 32).c_str() << "\"\n");
|
||||
BOOST_REQUIRE_MESSAGE(
|
||||
ethash_check_difficulty(hash, hash),
|
||||
"\nexpected \"" << hash << "\" to have the same or less difficulty than \"" << hash << "\"\n");
|
||||
memcpy(target, "11111111111111111111111111111112", 32);
|
||||
ethash_check_difficulty(&hash, &hash), "");
|
||||
// "\nexpected \"" << hash << "\" to have the same or less difficulty than \"" << hash << "\"\n");
|
||||
memcpy(&target, "11111111111111111111111111111112", 32);
|
||||
BOOST_REQUIRE_MESSAGE(
|
||||
ethash_check_difficulty(hash, target),
|
||||
"\nexpected \"" << hash << "\" to have the same or less difficulty than \"" << target << "\"\n");
|
||||
memcpy(target, "11111111111111111111111111111110", 32);
|
||||
ethash_check_difficulty(&hash, &target), "");
|
||||
// "\nexpected \"" << hash << "\" to have the same or less difficulty than \"" << target << "\"\n");
|
||||
memcpy(&target, "11111111111111111111111111111110", 32);
|
||||
BOOST_REQUIRE_MESSAGE(
|
||||
!ethash_check_difficulty(hash, target),
|
||||
"\nexpected \"" << hash << "\" to have more difficulty than \"" << target << "\"\n");
|
||||
!ethash_check_difficulty(&hash, &target), "");
|
||||
// "\nexpected \"" << hash << "\" to have more difficulty than \"" << target << "\"\n");
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(test_ethash_dir_creation) {
|
||||
ethash_blockhash_t seedhash;
|
||||
memset(&seedhash, 0, 32);
|
||||
BOOST_REQUIRE_EQUAL(
|
||||
ETHASH_IO_MEMO_MISMATCH,
|
||||
ethash_io_prepare("./test_ethash_directory/", seedhash)
|
||||
);
|
||||
|
||||
// let's make sure that the directory was created
|
||||
BOOST_REQUIRE(fs::is_directory(fs::path("./test_ethash_directory/")));
|
||||
|
||||
// cleanup
|
||||
fs::remove_all("./test_ethash_directory/");
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(test_ethash_io_write_files_are_created) {
|
||||
ethash_blockhash_t seedhash;
|
||||
static const int blockn = 0;
|
||||
ethash_get_seedhash(&seedhash, blockn);
|
||||
BOOST_REQUIRE_EQUAL(
|
||||
ETHASH_IO_MEMO_MISMATCH,
|
||||
ethash_io_prepare("./test_ethash_directory/", seedhash)
|
||||
);
|
||||
|
||||
// let's make sure that the directory was created
|
||||
BOOST_REQUIRE(fs::is_directory(fs::path("./test_ethash_directory/")));
|
||||
|
||||
ethash_cache cache;
|
||||
ethash_params params;
|
||||
uint8_t *data;
|
||||
uint64_t size;
|
||||
ethash_params_init(¶ms, blockn);
|
||||
params.cache_size = 1024;
|
||||
params.full_size = 1024 * 32;
|
||||
cache.mem = our_alloca(params.cache_size);
|
||||
ethash_mkcache(&cache, ¶ms, &seedhash);
|
||||
|
||||
BOOST_REQUIRE(
|
||||
ethash_io_write("./test_ethash_directory/", ¶ms, seedhash, &cache, &data, &size)
|
||||
);
|
||||
|
||||
BOOST_REQUIRE(fs::exists(fs::path("./test_ethash_directory/full")));
|
||||
BOOST_REQUIRE(fs::exists(fs::path("./test_ethash_directory/full.info")));
|
||||
|
||||
// cleanup
|
||||
fs::remove_all("./test_ethash_directory/");
|
||||
free(data);
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(test_ethash_io_memo_file_match) {
|
||||
ethash_blockhash_t seedhash;
|
||||
static const int blockn = 0;
|
||||
ethash_get_seedhash(&seedhash, blockn);
|
||||
BOOST_REQUIRE_EQUAL(
|
||||
ETHASH_IO_MEMO_MISMATCH,
|
||||
ethash_io_prepare("./test_ethash_directory/", seedhash)
|
||||
);
|
||||
|
||||
// let's make sure that the directory was created
|
||||
BOOST_REQUIRE(fs::is_directory(fs::path("./test_ethash_directory/")));
|
||||
|
||||
ethash_cache cache;
|
||||
ethash_params params;
|
||||
uint8_t *data;
|
||||
uint64_t size;
|
||||
ethash_params_init(¶ms, blockn);
|
||||
params.cache_size = 1024;
|
||||
params.full_size = 1024 * 32;
|
||||
cache.mem = our_alloca(params.cache_size);
|
||||
ethash_mkcache(&cache, ¶ms, &seedhash);
|
||||
|
||||
BOOST_REQUIRE(
|
||||
ethash_io_write("./test_ethash_directory/", ¶ms, seedhash, &cache, &data, &size)
|
||||
);
|
||||
|
||||
BOOST_REQUIRE(fs::exists(fs::path("./test_ethash_directory/full")));
|
||||
BOOST_REQUIRE(fs::exists(fs::path("./test_ethash_directory/full.info")));
|
||||
|
||||
BOOST_REQUIRE_EQUAL(
|
||||
ETHASH_IO_MEMO_MATCH,
|
||||
ethash_io_prepare("./test_ethash_directory/", seedhash)
|
||||
);
|
||||
|
||||
// cleanup
|
||||
fs::remove_all("./test_ethash_directory/");
|
||||
free(data);
|
||||
}
|
||||
|
||||
// could have used dev::contentsNew but don't wanna try to import
|
||||
// libdevcore just for one function
|
||||
static std::vector<char> readFileIntoVector(char const* filename)
|
||||
{
|
||||
ifstream ifs(filename, ios::binary|ios::ate);
|
||||
ifstream::pos_type pos = ifs.tellg();
|
||||
|
||||
std::vector<char> result((unsigned int)pos);
|
||||
|
||||
ifs.seekg(0, ios::beg);
|
||||
ifs.read(&result[0], pos);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
BOOST_AUTO_TEST_CASE(test_ethash_io_memo_file_contents) {
|
||||
ethash_blockhash_t seedhash;
|
||||
static const int blockn = 0;
|
||||
ethash_get_seedhash(&seedhash, blockn);
|
||||
BOOST_REQUIRE_EQUAL(
|
||||
ETHASH_IO_MEMO_MISMATCH,
|
||||
ethash_io_prepare("./test_ethash_directory/", seedhash)
|
||||
);
|
||||
|
||||
// let's make sure that the directory was created
|
||||
BOOST_REQUIRE(fs::is_directory(fs::path("./test_ethash_directory/")));
|
||||
|
||||
ethash_cache cache;
|
||||
ethash_params params;
|
||||
uint8_t *data;
|
||||
uint64_t size;
|
||||
ethash_params_init(¶ms, blockn);
|
||||
params.cache_size = 1024;
|
||||
params.full_size = 1024 * 32;
|
||||
cache.mem = our_alloca(params.cache_size);
|
||||
ethash_mkcache(&cache, ¶ms, &seedhash);
|
||||
|
||||
BOOST_REQUIRE(
|
||||
ethash_io_write("./test_ethash_directory/", ¶ms, seedhash, &cache, &data, &size)
|
||||
);
|
||||
|
||||
BOOST_REQUIRE(fs::exists(fs::path("./test_ethash_directory/full")));
|
||||
BOOST_REQUIRE(fs::exists(fs::path("./test_ethash_directory/full.info")));
|
||||
|
||||
char expect_buffer[DAG_MEMO_BYTESIZE];
|
||||
ethash_io_serialize_info(REVISION, seedhash, expect_buffer);
|
||||
auto vec = readFileIntoVector("./test_ethash_directory/full.info");
|
||||
BOOST_REQUIRE_EQUAL(vec.size(), DAG_MEMO_BYTESIZE);
|
||||
BOOST_REQUIRE(memcmp(expect_buffer, &vec[0], DAG_MEMO_BYTESIZE) == 0);
|
||||
|
||||
// cleanup
|
||||
fs::remove_all("./test_ethash_directory/");
|
||||
free(data);
|
||||
}
|
||||
20
Godeps/_workspace/src/github.com/ethereum/ethash/test/go/test.sh
generated
vendored
20
Godeps/_workspace/src/github.com/ethereum/ethash/test/go/test.sh
generated
vendored
|
|
@ -1,20 +0,0 @@
|
|||
#!/bin/bash
|
||||
|
||||
# Strict mode
|
||||
set -e
|
||||
|
||||
SOURCE="${BASH_SOURCE[0]}"
|
||||
while [ -h "$SOURCE" ]; do
|
||||
DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
|
||||
SOURCE="$(readlink "$SOURCE")"
|
||||
[[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE"
|
||||
done
|
||||
TEST_DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
|
||||
|
||||
export GOPATH=${HOME}/.go
|
||||
export PATH=$PATH:$GOPATH/bin
|
||||
echo "# getting go dependencies (can take some time)..."
|
||||
cd ${TEST_DIR}/../.. && go get
|
||||
cd ${GOPATH}/src/github.com/ethereum/go-ethereum
|
||||
git checkout poc-9
|
||||
cd ${TEST_DIR} && go test
|
||||
13
Godeps/_workspace/src/github.com/ethereum/ethash/test/python/test.sh
generated
vendored
13
Godeps/_workspace/src/github.com/ethereum/ethash/test/python/test.sh
generated
vendored
|
|
@ -3,6 +3,15 @@
|
|||
# Strict mode
|
||||
set -e
|
||||
|
||||
if [ -x "$(which virtualenv2)" ] ; then
|
||||
VIRTUALENV_EXEC=virtualenv2
|
||||
elif [ -x "$(which virtualenv)" ] ; then
|
||||
VIRTUALENV_EXEC=virtualenv
|
||||
else
|
||||
echo "Could not find a suitable version of virtualenv"
|
||||
false
|
||||
fi
|
||||
|
||||
SOURCE="${BASH_SOURCE[0]}"
|
||||
while [ -h "$SOURCE" ]; do
|
||||
DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
|
||||
|
|
@ -11,9 +20,11 @@ while [ -h "$SOURCE" ]; do
|
|||
done
|
||||
TEST_DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
|
||||
|
||||
[ -d $TEST_DIR/python-virtual-env ] || virtualenv --system-site-packages $TEST_DIR/python-virtual-env
|
||||
[ -d $TEST_DIR/python-virtual-env ] || $VIRTUALENV_EXEC --system-site-packages $TEST_DIR/python-virtual-env
|
||||
source $TEST_DIR/python-virtual-env/bin/activate
|
||||
pip install -r $TEST_DIR/requirements.txt > /dev/null
|
||||
# force installation of nose in virtualenv even if existing in thereuser's system
|
||||
pip install nose -I
|
||||
pip install --upgrade --no-deps --force-reinstall -e $TEST_DIR/../..
|
||||
cd $TEST_DIR
|
||||
nosetests --with-doctest -v --nocapture
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ import (
|
|||
"github.com/ethereum/go-ethereum/errs"
|
||||
"github.com/ethereum/go-ethereum/event"
|
||||
ethlogger "github.com/ethereum/go-ethereum/logger"
|
||||
"github.com/ethereum/go-ethereum/logger/glog"
|
||||
"github.com/ethereum/go-ethereum/pow"
|
||||
)
|
||||
|
||||
|
|
@ -260,7 +261,7 @@ func (self *BlockPool) Start() {
|
|||
}
|
||||
}
|
||||
}()
|
||||
plog.Infoln("Started")
|
||||
glog.V(ethlogger.Info).Infoln("Blockpool started")
|
||||
}
|
||||
|
||||
func (self *BlockPool) Stop() {
|
||||
|
|
@ -653,6 +654,9 @@ func (self *BlockPool) AddBlock(block *types.Block, peerId string) {
|
|||
}
|
||||
sender.lock.Unlock()
|
||||
|
||||
/* @zelig !!!
|
||||
requested 5 hashes from both A & B. A responds sooner then B, process blocks. Close section.
|
||||
delayed B sends you block ... UNREQUESTED. Blocked
|
||||
if entry == nil {
|
||||
plog.DebugDetailf("AddBlock: unrequested block %s received from peer <%s> (head: %s)", hex(hash), peerId, hex(sender.currentBlockHash))
|
||||
sender.addError(ErrUnrequestedBlock, "%x", hash)
|
||||
|
|
@ -662,6 +666,7 @@ func (self *BlockPool) AddBlock(block *types.Block, peerId string) {
|
|||
self.status.lock.Unlock()
|
||||
return
|
||||
}
|
||||
*/
|
||||
}
|
||||
if entry == nil {
|
||||
return
|
||||
|
|
@ -683,6 +688,8 @@ func (self *BlockPool) AddBlock(block *types.Block, peerId string) {
|
|||
return
|
||||
}
|
||||
|
||||
/*
|
||||
@zelig needs discussing
|
||||
// validate block for PoW
|
||||
if !self.verifyPoW(block) {
|
||||
plog.Warnf("AddBlock: invalid PoW on block %s from peer <%s> (head: %s)", hex(hash), peerId, hex(sender.currentBlockHash))
|
||||
|
|
@ -694,6 +701,7 @@ func (self *BlockPool) AddBlock(block *types.Block, peerId string) {
|
|||
|
||||
return
|
||||
}
|
||||
*/
|
||||
|
||||
node.block = block
|
||||
node.blockBy = peerId
|
||||
|
|
@ -761,10 +769,10 @@ func (self *BlockPool) checkTD(nodes ...*node) {
|
|||
if n.td != nil {
|
||||
plog.DebugDetailf("peer td %v =?= block td %v", n.td, n.block.Td)
|
||||
if n.td.Cmp(n.block.Td) != 0 {
|
||||
self.peers.peerError(n.blockBy, ErrIncorrectTD, "on block %x", n.hash)
|
||||
self.status.lock.Lock()
|
||||
self.status.badPeers[n.blockBy]++
|
||||
self.status.lock.Unlock()
|
||||
//self.peers.peerError(n.blockBy, ErrIncorrectTD, "on block %x", n.hash)
|
||||
//self.status.lock.Lock()
|
||||
//self.status.badPeers[n.blockBy]++
|
||||
//self.status.lock.Unlock()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -124,6 +124,8 @@ func TestErrInsufficientChainInfo(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestIncorrectTD(t *testing.T) {
|
||||
t.Skip() // @zelig this one requires fixing for the TD
|
||||
|
||||
test.LogInit()
|
||||
_, blockPool, blockPoolTester := newTestBlockPool(t)
|
||||
blockPoolTester.blockChain[0] = nil
|
||||
|
|
|
|||
|
|
@ -477,8 +477,8 @@ func (self *peer) getBlockHashes() bool {
|
|||
// XXX added currentBlock check (?)
|
||||
if self.currentBlock != nil && self.currentBlock.Td != nil {
|
||||
if self.td.Cmp(self.currentBlock.Td) != 0 {
|
||||
self.addError(ErrIncorrectTD, "on block %x", self.currentBlockHash)
|
||||
self.bp.status.badPeers[self.id]++
|
||||
//self.addError(ErrIncorrectTD, "on block %x", self.currentBlockHash)
|
||||
//self.bp.status.badPeers[self.id]++
|
||||
}
|
||||
}
|
||||
headKey := self.parentHash
|
||||
|
|
|
|||
|
|
@ -132,7 +132,7 @@ func (self *section) addSectionToBlockChain(p *peer) {
|
|||
}
|
||||
self.bp.lock.Unlock()
|
||||
|
||||
plog.Infof("[%s] insert %v blocks [%v/%v] into blockchain", sectionhex(self), len(blocks), hex(blocks[0].Hash()), hex(blocks[len(blocks)-1].Hash()))
|
||||
plog.Debugf("[%s] insert %v blocks [%v/%v] into blockchain", sectionhex(self), len(blocks), hex(blocks[0].Hash()), hex(blocks[len(blocks)-1].Hash()))
|
||||
err := self.bp.insertChain(blocks)
|
||||
if err != nil {
|
||||
self.invalid = true
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ import (
|
|||
"github.com/ethereum/go-ethereum/common"
|
||||
"github.com/ethereum/go-ethereum/core/state"
|
||||
"github.com/ethereum/go-ethereum/core/types"
|
||||
"github.com/ethereum/go-ethereum/logger/glog"
|
||||
"github.com/ethereum/go-ethereum/rlp"
|
||||
"github.com/ethereum/go-ethereum/rpc"
|
||||
"github.com/ethereum/go-ethereum/xeth"
|
||||
|
|
@ -25,8 +26,6 @@ func (js *jsre) adminBindings() {
|
|||
admin := t.Object()
|
||||
admin.Set("suggestPeer", js.suggestPeer)
|
||||
admin.Set("startRPC", js.startRPC)
|
||||
admin.Set("startMining", js.startMining)
|
||||
admin.Set("stopMining", js.stopMining)
|
||||
admin.Set("nodeInfo", js.nodeInfo)
|
||||
admin.Set("peers", js.peers)
|
||||
admin.Set("newAccount", js.newAccount)
|
||||
|
|
@ -34,6 +33,58 @@ func (js *jsre) adminBindings() {
|
|||
admin.Set("import", js.importChain)
|
||||
admin.Set("export", js.exportChain)
|
||||
admin.Set("dumpBlock", js.dumpBlock)
|
||||
admin.Set("verbosity", js.verbosity)
|
||||
admin.Set("backtrace", js.backtrace)
|
||||
|
||||
admin.Set("miner", struct{}{})
|
||||
t, _ = admin.Get("miner")
|
||||
miner := t.Object()
|
||||
miner.Set("start", js.startMining)
|
||||
miner.Set("stop", js.stopMining)
|
||||
miner.Set("hashrate", js.hashrate)
|
||||
miner.Set("setExtra", js.setExtra)
|
||||
}
|
||||
|
||||
func (js *jsre) setExtra(call otto.FunctionCall) otto.Value {
|
||||
extra, err := call.Argument(0).ToString()
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return otto.UndefinedValue()
|
||||
}
|
||||
|
||||
if len(extra) > 1024 {
|
||||
fmt.Println("error: cannot exceed 1024 bytes")
|
||||
return otto.UndefinedValue()
|
||||
}
|
||||
|
||||
js.ethereum.Miner().SetExtra([]byte(extra))
|
||||
return otto.UndefinedValue()
|
||||
}
|
||||
|
||||
func (js *jsre) hashrate(otto.FunctionCall) otto.Value {
|
||||
return js.re.ToVal(js.ethereum.Miner().HashRate())
|
||||
}
|
||||
|
||||
func (js *jsre) backtrace(call otto.FunctionCall) otto.Value {
|
||||
tracestr, err := call.Argument(0).ToString()
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return otto.UndefinedValue()
|
||||
}
|
||||
glog.GetTraceLocation().Set(tracestr)
|
||||
|
||||
return otto.UndefinedValue()
|
||||
}
|
||||
|
||||
func (js *jsre) verbosity(call otto.FunctionCall) otto.Value {
|
||||
v, err := call.Argument(0).ToInteger()
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return otto.UndefinedValue()
|
||||
}
|
||||
|
||||
glog.SetV(int(v))
|
||||
return otto.UndefinedValue()
|
||||
}
|
||||
|
||||
func (js *jsre) startMining(call otto.FunctionCall) otto.Value {
|
||||
|
|
|
|||
|
|
@ -43,13 +43,10 @@ import (
|
|||
|
||||
const (
|
||||
ClientIdentifier = "Geth"
|
||||
Version = "0.9.5"
|
||||
Version = "0.9.7"
|
||||
)
|
||||
|
||||
var (
|
||||
clilogger = logger.NewLogger("CLI")
|
||||
app = utils.NewApp(Version, "the go-ethereum command line interface")
|
||||
)
|
||||
var app = utils.NewApp(Version, "the go-ethereum command line interface")
|
||||
|
||||
func init() {
|
||||
app.Action = run
|
||||
|
|
@ -217,9 +214,6 @@ JavaScript API. See https://github.com/ethereum/go-ethereum/wiki/Javascipt-Conso
|
|||
utils.DataDirFlag,
|
||||
utils.JSpathFlag,
|
||||
utils.ListenPortFlag,
|
||||
utils.LogFileFlag,
|
||||
utils.LogJSONFlag,
|
||||
utils.LogLevelFlag,
|
||||
utils.MaxPeersFlag,
|
||||
utils.EtherbaseFlag,
|
||||
utils.MinerThreadsFlag,
|
||||
|
|
@ -234,6 +228,12 @@ JavaScript API. See https://github.com/ethereum/go-ethereum/wiki/Javascipt-Conso
|
|||
utils.ProtocolVersionFlag,
|
||||
utils.NetworkIdFlag,
|
||||
utils.RPCCORSDomainFlag,
|
||||
utils.LogLevelFlag,
|
||||
utils.BacktraceAtFlag,
|
||||
utils.LogToStdErrFlag,
|
||||
utils.LogVModuleFlag,
|
||||
utils.LogFileFlag,
|
||||
utils.LogJSONFlag,
|
||||
}
|
||||
|
||||
// missing:
|
||||
|
|
@ -248,6 +248,7 @@ JavaScript API. See https://github.com/ethereum/go-ethereum/wiki/Javascipt-Conso
|
|||
}
|
||||
|
||||
func main() {
|
||||
fmt.Printf("Welcome to the FRONTIER\n")
|
||||
runtime.GOMAXPROCS(runtime.NumCPU())
|
||||
defer logger.Flush()
|
||||
if err := app.Run(os.Args); err != nil {
|
||||
|
|
@ -257,7 +258,6 @@ func main() {
|
|||
}
|
||||
|
||||
func run(ctx *cli.Context) {
|
||||
fmt.Printf("Welcome to the FRONTIER\n")
|
||||
utils.HandleInterrupt()
|
||||
cfg := utils.MakeEthConfig(ClientIdentifier, Version, ctx)
|
||||
ethereum, err := eth.New(cfg)
|
||||
|
|
@ -478,7 +478,7 @@ func makedag(ctx *cli.Context) {
|
|||
chain, _, _ := utils.GetChain(ctx)
|
||||
pow := ethash.New(chain)
|
||||
fmt.Println("making cache")
|
||||
pow.UpdateCache(true)
|
||||
pow.UpdateCache(0, true)
|
||||
fmt.Println("making DAG")
|
||||
pow.UpdateDAG()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1 +1 @@
|
|||
Subproject commit 31e046dbecea51d3b99b21f3e7e60ddfb6c39304
|
||||
Subproject commit c80ede50c3b60a482f1ec76038325ec52f5e73b0
|
||||
|
|
@ -33,10 +33,10 @@ import (
|
|||
"github.com/ethereum/go-ethereum/core/types"
|
||||
"github.com/ethereum/go-ethereum/eth"
|
||||
"github.com/ethereum/go-ethereum/logger"
|
||||
"github.com/ethereum/go-ethereum/logger/glog"
|
||||
"github.com/ethereum/go-ethereum/rlp"
|
||||
)
|
||||
|
||||
var clilogger = logger.NewLogger("CLI")
|
||||
var interruptCallbacks = []func(os.Signal){}
|
||||
|
||||
// Register interrupt handlers callbacks
|
||||
|
|
@ -50,7 +50,7 @@ func HandleInterrupt() {
|
|||
go func() {
|
||||
signal.Notify(c, os.Interrupt)
|
||||
for sig := range c {
|
||||
clilogger.Errorf("Shutting down (%v) ... \n", sig)
|
||||
glog.V(logger.Error).Infof("Shutting down (%v) ... \n", sig)
|
||||
RunInterruptCallbacks(sig)
|
||||
}
|
||||
}()
|
||||
|
|
@ -113,7 +113,7 @@ func Fatalf(format string, args ...interface{}) {
|
|||
}
|
||||
|
||||
func StartEthereum(ethereum *eth.Ethereum) {
|
||||
clilogger.Infoln("Starting ", ethereum.Name())
|
||||
glog.V(logger.Info).Infoln("Starting ", ethereum.Name())
|
||||
if err := ethereum.Start(); err != nil {
|
||||
exit(err)
|
||||
}
|
||||
|
|
@ -124,7 +124,7 @@ func StartEthereum(ethereum *eth.Ethereum) {
|
|||
}
|
||||
|
||||
func StartEthereumForTest(ethereum *eth.Ethereum) {
|
||||
clilogger.Infoln("Starting ", ethereum.Name())
|
||||
glog.V(logger.Info).Infoln("Starting ", ethereum.Name())
|
||||
ethereum.StartForTest()
|
||||
RegisterInterrupt(func(sig os.Signal) {
|
||||
ethereum.Stop()
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ import (
|
|||
"github.com/ethereum/go-ethereum/ethdb"
|
||||
"github.com/ethereum/go-ethereum/event"
|
||||
"github.com/ethereum/go-ethereum/logger"
|
||||
"github.com/ethereum/go-ethereum/logger/glog"
|
||||
"github.com/ethereum/go-ethereum/p2p/nat"
|
||||
"github.com/ethereum/go-ethereum/rpc"
|
||||
"github.com/ethereum/go-ethereum/xeth"
|
||||
|
|
@ -184,6 +185,20 @@ var (
|
|||
Usage: "JS library path to be used with console and js subcommands",
|
||||
Value: ".",
|
||||
}
|
||||
BacktraceAtFlag = cli.GenericFlag{
|
||||
Name: "backtrace_at",
|
||||
Usage: "When set to a file and line number holding a logging statement a stack trace will be written to the Info log",
|
||||
Value: glog.GetTraceLocation(),
|
||||
}
|
||||
LogToStdErrFlag = cli.BoolFlag{
|
||||
Name: "logtostderr",
|
||||
Usage: "Logs are written to standard error instead of to files.",
|
||||
}
|
||||
LogVModuleFlag = cli.GenericFlag{
|
||||
Name: "vmodule",
|
||||
Usage: "The syntax of the argument is a comma-separated list of pattern=N, where pattern is a literal file name (minus the \".go\" suffix) or \"glob\" pattern and N is a V level.",
|
||||
Value: glog.GetVModule(),
|
||||
}
|
||||
)
|
||||
|
||||
func GetNAT(ctx *cli.Context) nat.Interface {
|
||||
|
|
@ -213,6 +228,13 @@ func GetNodeKey(ctx *cli.Context) (key *ecdsa.PrivateKey) {
|
|||
}
|
||||
|
||||
func MakeEthConfig(clientID, version string, ctx *cli.Context) *eth.Config {
|
||||
// Set verbosity on glog
|
||||
glog.SetV(ctx.GlobalInt(LogLevelFlag.Name))
|
||||
// Set the log type
|
||||
glog.SetToStderr(ctx.GlobalBool(LogToStdErrFlag.Name))
|
||||
// Set the log dir
|
||||
glog.SetLogDir(ctx.GlobalString(LogFileFlag.Name))
|
||||
|
||||
return ð.Config{
|
||||
Name: common.MakeName(clientID, version),
|
||||
DataDir: ctx.GlobalString(DataDirFlag.Name),
|
||||
|
|
|
|||
|
|
@ -56,6 +56,23 @@ func (bc *BlockCache) Push(block *types.Block) {
|
|||
bc.hashes[len(bc.hashes)-1] = hash
|
||||
}
|
||||
|
||||
func (bc *BlockCache) Delete(hash common.Hash) {
|
||||
bc.mu.Lock()
|
||||
defer bc.mu.Unlock()
|
||||
|
||||
if _, ok := bc.blocks[hash]; ok {
|
||||
delete(bc.blocks, hash)
|
||||
for i, h := range bc.hashes {
|
||||
if hash == h {
|
||||
bc.hashes = bc.hashes[:i+copy(bc.hashes[i:], bc.hashes[i+1:])]
|
||||
// or ? => bc.hashes = append(bc.hashes[:i], bc.hashes[i+1]...)
|
||||
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (bc *BlockCache) Get(hash common.Hash) *types.Block {
|
||||
bc.mu.RLock()
|
||||
defer bc.mu.RUnlock()
|
||||
|
|
@ -71,3 +88,14 @@ func (bc *BlockCache) Has(hash common.Hash) bool {
|
|||
_, ok := bc.blocks[hash]
|
||||
return ok
|
||||
}
|
||||
|
||||
func (bc *BlockCache) Each(cb func(int, *types.Block)) {
|
||||
bc.mu.Lock()
|
||||
defer bc.mu.Unlock()
|
||||
|
||||
i := 0
|
||||
for _, block := range bc.blocks {
|
||||
cb(i, block)
|
||||
i++
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ import (
|
|||
func newChain(size int) (chain []*types.Block) {
|
||||
var parentHash common.Hash
|
||||
for i := 0; i < size; i++ {
|
||||
block := types.NewBlock(parentHash, common.Address{}, common.Hash{}, new(big.Int), 0, "")
|
||||
block := types.NewBlock(parentHash, common.Address{}, common.Hash{}, new(big.Int), 0, nil)
|
||||
block.Header().Number = big.NewInt(int64(i))
|
||||
chain = append(chain, block)
|
||||
parentHash = block.Hash()
|
||||
|
|
@ -46,3 +46,15 @@ func TestInclusion(t *testing.T) {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeletion(t *testing.T) {
|
||||
chain := newChain(3)
|
||||
cache := NewBlockCache(3)
|
||||
insertChainCache(cache, chain)
|
||||
|
||||
cache.Delete(chain[1].Hash())
|
||||
|
||||
if cache.Has(chain[1].Hash()) {
|
||||
t.Errorf("expected %x not to be included")
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ import (
|
|||
"github.com/ethereum/go-ethereum/core/types"
|
||||
"github.com/ethereum/go-ethereum/event"
|
||||
"github.com/ethereum/go-ethereum/logger"
|
||||
"github.com/ethereum/go-ethereum/logger/glog"
|
||||
"github.com/ethereum/go-ethereum/params"
|
||||
"github.com/ethereum/go-ethereum/pow"
|
||||
"github.com/ethereum/go-ethereum/rlp"
|
||||
|
|
@ -90,7 +91,8 @@ func (self *BlockProcessor) ApplyTransaction(coinbase *state.StateObject, stated
|
|||
receipt := types.NewReceipt(statedb.Root().Bytes(), cumulative)
|
||||
receipt.SetLogs(statedb.Logs())
|
||||
receipt.Bloom = types.CreateBloom(types.Receipts{receipt})
|
||||
chainlogger.Debugln(receipt)
|
||||
|
||||
glog.V(logger.Debug).Infoln(receipt)
|
||||
|
||||
// Notify all subscribers
|
||||
if !transientProcess {
|
||||
|
|
@ -120,7 +122,7 @@ func (self *BlockProcessor) ApplyTransactions(coinbase *state.StateObject, state
|
|||
}
|
||||
|
||||
if err != nil {
|
||||
statelogger.Infoln("TX err:", err)
|
||||
glog.V(logger.Core).Infoln("TX err:", err)
|
||||
}
|
||||
receipts = append(receipts, receipt)
|
||||
|
||||
|
|
@ -165,16 +167,10 @@ func (sm *BlockProcessor) processWithParent(block, parent *types.Block) (td *big
|
|||
// Create a new state based on the parent's root (e.g., create copy)
|
||||
state := state.New(parent.Root(), sm.db)
|
||||
|
||||
// track (possible) uncle block
|
||||
var uncle bool
|
||||
// Block validation
|
||||
if err = sm.ValidateHeader(block.Header(), parent.Header()); err != nil {
|
||||
if err != BlockEqualTSErr {
|
||||
return
|
||||
}
|
||||
err = nil
|
||||
uncle = true
|
||||
}
|
||||
|
||||
// There can be at most two uncles
|
||||
if len(block.Uncles()) > 2 {
|
||||
|
|
@ -231,23 +227,14 @@ func (sm *BlockProcessor) processWithParent(block, parent *types.Block) (td *big
|
|||
// Sync the current block's state to the database
|
||||
state.Sync()
|
||||
|
||||
if !uncle {
|
||||
// Remove transactions from the pool
|
||||
sm.txpool.RemoveSet(block.Transactions())
|
||||
}
|
||||
|
||||
// This puts transactions in a extra db for rpc
|
||||
for i, tx := range block.Transactions() {
|
||||
putTx(sm.extraDb, tx, block, uint64(i))
|
||||
}
|
||||
|
||||
if uncle {
|
||||
chainlogger.Infof("found possible uncle block #%d (%x...)\n", header.Number, block.Hash().Bytes()[0:4])
|
||||
return td, nil, BlockEqualTSErr
|
||||
} else {
|
||||
chainlogger.Infof("processed block #%d (%d TXs %d UNCs) (%x...)\n", header.Number, len(block.Transactions()), len(block.Uncles()), block.Hash().Bytes()[0:4])
|
||||
}
|
||||
|
||||
return td, state.Logs(), nil
|
||||
}
|
||||
|
||||
|
|
@ -272,7 +259,8 @@ func (sm *BlockProcessor) ValidateHeader(block, parent *types.Header) error {
|
|||
return fmt.Errorf("GasLimit check failed for block %v (%v > %v)", block.GasLimit, a, b)
|
||||
}
|
||||
|
||||
if int64(block.Time) > time.Now().Unix() {
|
||||
// Allow future blocks up to 10 seconds
|
||||
if int64(block.Time) > time.Now().Unix()+4 {
|
||||
return BlockFutureErr
|
||||
}
|
||||
|
||||
|
|
@ -280,15 +268,15 @@ func (sm *BlockProcessor) ValidateHeader(block, parent *types.Header) error {
|
|||
return BlockNumberErr
|
||||
}
|
||||
|
||||
if block.Time <= parent.Time {
|
||||
return BlockEqualTSErr //ValidationError("Block timestamp equal or less than previous block (%v - %v)", block.Time, parent.Time)
|
||||
}
|
||||
|
||||
// Verify the nonce of the block. Return an error if it's not valid
|
||||
if !sm.Pow.Verify(types.NewBlockWithHeader(block)) {
|
||||
return ValidationError("Block's nonce is invalid (= %x)", block.Nonce)
|
||||
}
|
||||
|
||||
if block.Time <= parent.Time {
|
||||
return BlockEqualTSErr //ValidationError("Block timestamp equal or less than previous block (%v - %v)", block.Time, parent.Time)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
|
|
@ -371,7 +359,7 @@ func (sm *BlockProcessor) GetLogs(block *types.Block) (logs state.Logs, err erro
|
|||
func putTx(db common.Database, tx *types.Transaction, block *types.Block, i uint64) {
|
||||
rlpEnc, err := rlp.EncodeToBytes(tx)
|
||||
if err != nil {
|
||||
statelogger.Infoln("Failed encoding tx", err)
|
||||
glog.V(logger.Debug).Infoln("Failed encoding tx", err)
|
||||
return
|
||||
}
|
||||
db.Put(tx.Hash().Bytes(), rlpEnc)
|
||||
|
|
@ -386,7 +374,7 @@ func putTx(db common.Database, tx *types.Transaction, block *types.Block, i uint
|
|||
txExtra.Index = i
|
||||
rlpMeta, err := rlp.EncodeToBytes(txExtra)
|
||||
if err != nil {
|
||||
statelogger.Infoln("Failed encoding meta", err)
|
||||
glog.V(logger.Debug).Infoln("Failed encoding tx meta data", err)
|
||||
return
|
||||
}
|
||||
db.Put(append(tx.Hash().Bytes(), 0x0001), rlpMeta)
|
||||
|
|
|
|||
|
|
@ -22,10 +22,11 @@ func TestNumber(t *testing.T) {
|
|||
bp, chain := proc()
|
||||
block1 := chain.NewBlock(common.Address{})
|
||||
block1.Header().Number = big.NewInt(3)
|
||||
block1.Header().Time--
|
||||
|
||||
err := bp.ValidateHeader(block1.Header(), chain.Genesis().Header())
|
||||
if err != BlockNumberErr {
|
||||
t.Errorf("expected block number error")
|
||||
t.Errorf("expected block number error %v", err)
|
||||
}
|
||||
|
||||
block1 = chain.NewBlock(common.Address{})
|
||||
|
|
|
|||
|
|
@ -55,7 +55,7 @@ func NewCanonical(n int, db common.Database) (*BlockProcessor, error) {
|
|||
|
||||
// block time is fixed at 10 seconds
|
||||
func newBlockFromParent(addr common.Address, parent *types.Block) *types.Block {
|
||||
block := types.NewBlock(parent.Hash(), addr, parent.Root(), common.BigPow(2, 32), 0, "")
|
||||
block := types.NewBlock(parent.Hash(), addr, parent.Root(), common.BigPow(2, 32), 0, nil)
|
||||
block.SetUncles(nil)
|
||||
block.SetTransactions(nil)
|
||||
block.SetReceipts(nil)
|
||||
|
|
@ -109,6 +109,7 @@ func makeChain(bman *BlockProcessor, parent *types.Block, max int, db common.Dat
|
|||
// Effectively a fork factory
|
||||
func newChainManager(block *types.Block, eventMux *event.TypeMux, db common.Database) *ChainManager {
|
||||
bc := &ChainManager{blockDb: db, stateDb: db, genesisBlock: GenesisBlock(db), eventMux: eventMux}
|
||||
bc.futureBlocks = NewBlockCache(1000)
|
||||
if block == nil {
|
||||
bc.Reset()
|
||||
} else {
|
||||
|
|
|
|||
|
|
@ -6,12 +6,14 @@ import (
|
|||
"io"
|
||||
"math/big"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/ethereum/go-ethereum/common"
|
||||
"github.com/ethereum/go-ethereum/core/state"
|
||||
"github.com/ethereum/go-ethereum/core/types"
|
||||
"github.com/ethereum/go-ethereum/event"
|
||||
"github.com/ethereum/go-ethereum/logger"
|
||||
"github.com/ethereum/go-ethereum/logger/glog"
|
||||
"github.com/ethereum/go-ethereum/params"
|
||||
"github.com/ethereum/go-ethereum/rlp"
|
||||
)
|
||||
|
|
@ -95,6 +97,7 @@ type ChainManager struct {
|
|||
txState *state.ManagedState
|
||||
|
||||
cache *BlockCache
|
||||
futureBlocks *BlockCache
|
||||
|
||||
quit chan struct{}
|
||||
}
|
||||
|
|
@ -106,6 +109,7 @@ func NewChainManager(blockDb, stateDb common.Database, mux *event.TypeMux) *Chai
|
|||
// Take ownership of this particular state
|
||||
bc.txState = state.ManageState(bc.State().Copy())
|
||||
|
||||
bc.futureBlocks = NewBlockCache(254)
|
||||
bc.makeCache()
|
||||
|
||||
go bc.update()
|
||||
|
|
@ -186,7 +190,9 @@ func (bc *ChainManager) setLastBlock() {
|
|||
bc.Reset()
|
||||
}
|
||||
|
||||
chainlogger.Infof("Last block (#%v) %x TD=%v\n", bc.currentBlock.Number(), bc.currentBlock.Hash(), bc.td)
|
||||
if glog.V(logger.Info) {
|
||||
glog.Infof("Last block (#%v) %x TD=%v\n", bc.currentBlock.Number(), bc.currentBlock.Hash(), bc.td)
|
||||
}
|
||||
}
|
||||
|
||||
func (bc *ChainManager) makeCache() {
|
||||
|
|
@ -222,7 +228,7 @@ func (bc *ChainManager) NewBlock(coinbase common.Address) *types.Block {
|
|||
root,
|
||||
common.BigPow(2, 32),
|
||||
0,
|
||||
"")
|
||||
nil)
|
||||
block.SetUncles(nil)
|
||||
block.SetTransactions(nil)
|
||||
block.SetReceipts(nil)
|
||||
|
|
@ -284,7 +290,8 @@ func (bc *ChainManager) ResetWithGenesisBlock(gb *types.Block) {
|
|||
func (self *ChainManager) Export(w io.Writer) error {
|
||||
self.mu.RLock()
|
||||
defer self.mu.RUnlock()
|
||||
chainlogger.Infof("exporting %v blocks...\n", self.currentBlock.Header().Number)
|
||||
glog.V(logger.Info).Infof("exporting %v blocks...\n", self.currentBlock.Header().Number)
|
||||
|
||||
for block := self.currentBlock; block != nil; block = self.GetBlock(block.Header().ParentHash) {
|
||||
if err := block.EncodeRLP(w); err != nil {
|
||||
return err
|
||||
|
|
@ -331,7 +338,6 @@ func (self *ChainManager) GetBlockHashesFromHash(hash common.Hash, max uint64) (
|
|||
parentHash := block.Header().ParentHash
|
||||
block = self.GetBlock(parentHash)
|
||||
if block == nil {
|
||||
chainlogger.Infof("GetBlockHashesFromHash Parent UNKNOWN %x\n", parentHash)
|
||||
break
|
||||
}
|
||||
|
||||
|
|
@ -355,7 +361,7 @@ func (self *ChainManager) GetBlock(hash common.Hash) *types.Block {
|
|||
}
|
||||
var block types.StorageBlock
|
||||
if err := rlp.Decode(bytes.NewReader(data), &block); err != nil {
|
||||
chainlogger.Errorf("invalid block RLP for hash %x: %v", hash, err)
|
||||
glog.V(logger.Error).Infof("invalid block RLP for hash %x: %v", hash, err)
|
||||
return nil
|
||||
}
|
||||
return (*types.Block)(&block)
|
||||
|
|
@ -431,14 +437,28 @@ type queueEvent struct {
|
|||
splitCount int
|
||||
}
|
||||
|
||||
func (self *ChainManager) InsertChain(chain types.Blocks) error {
|
||||
//self.tsmu.Lock()
|
||||
//defer self.tsmu.Unlock()
|
||||
func (self *ChainManager) procFutureBlocks() {
|
||||
blocks := make([]*types.Block, len(self.futureBlocks.blocks))
|
||||
self.futureBlocks.Each(func(i int, block *types.Block) {
|
||||
blocks[i] = block
|
||||
})
|
||||
|
||||
types.BlockBy(types.Number).Sort(blocks)
|
||||
self.InsertChain(blocks)
|
||||
}
|
||||
|
||||
func (self *ChainManager) InsertChain(chain types.Blocks) error {
|
||||
// A queued approach to delivering events. This is generally faster than direct delivery and requires much less mutex acquiring.
|
||||
var queue = make([]interface{}, len(chain))
|
||||
var queueEvent = queueEvent{queue: queue}
|
||||
var (
|
||||
queue = make([]interface{}, len(chain))
|
||||
queueEvent = queueEvent{queue: queue}
|
||||
stats struct{ queued, processed int }
|
||||
tstart = time.Now()
|
||||
)
|
||||
for i, block := range chain {
|
||||
if block == nil {
|
||||
continue
|
||||
}
|
||||
// Call in to the block processor and check for errors. It's likely that if one block fails
|
||||
// all others will fail too (unless a known block is returned).
|
||||
td, logs, err := self.processor.Process(block)
|
||||
|
|
@ -447,16 +467,27 @@ func (self *ChainManager) InsertChain(chain types.Blocks) error {
|
|||
continue
|
||||
}
|
||||
|
||||
if err == BlockEqualTSErr {
|
||||
//queue[i] = ChainSideEvent{block, logs}
|
||||
// XXX silently discard it?
|
||||
block.Td = new(big.Int)
|
||||
// Do not penelise on future block. We'll need a block queue eventually that will queue
|
||||
// future block for future use
|
||||
if err == BlockFutureErr {
|
||||
self.futureBlocks.Push(block)
|
||||
stats.queued++
|
||||
continue
|
||||
}
|
||||
|
||||
if IsParentErr(err) && self.futureBlocks.Has(block.ParentHash()) {
|
||||
self.futureBlocks.Push(block)
|
||||
stats.queued++
|
||||
continue
|
||||
}
|
||||
|
||||
h := block.Header()
|
||||
chainlogger.Errorf("INVALID block #%v (%x)\n", h.Number, h.Hash().Bytes()[:4])
|
||||
chainlogger.Errorln(err)
|
||||
chainlogger.Debugln(block)
|
||||
|
||||
glog.V(logger.Error).Infof("INVALID block #%v (%x)\n", h.Number, h.Hash().Bytes()[:4])
|
||||
glog.V(logger.Error).Infoln(err)
|
||||
glog.V(logger.Debug).Infoln(block)
|
||||
|
||||
return err
|
||||
}
|
||||
block.Td = td
|
||||
|
|
@ -473,7 +504,10 @@ func (self *ChainManager) InsertChain(chain types.Blocks) error {
|
|||
if block.Header().Number.Cmp(new(big.Int).Add(cblock.Header().Number, common.Big1)) < 0 {
|
||||
chash := cblock.Hash()
|
||||
hash := block.Hash()
|
||||
chainlogger.Infof("Split detected. New head #%v (%x) TD=%v, was #%v (%x) TD=%v\n", block.Header().Number, hash[:4], td, cblock.Header().Number, chash[:4], self.td)
|
||||
|
||||
if glog.V(logger.Info) {
|
||||
glog.Infof("Split detected. New head #%v (%x) TD=%v, was #%v (%x) TD=%v\n", block.Header().Number, hash[:4], td, cblock.Header().Number, chash[:4], self.td)
|
||||
}
|
||||
|
||||
queue[i] = ChainSplitEvent{block, logs}
|
||||
queueEvent.splitCount++
|
||||
|
|
@ -494,6 +528,10 @@ func (self *ChainManager) InsertChain(chain types.Blocks) error {
|
|||
|
||||
queue[i] = ChainEvent{block, logs}
|
||||
queueEvent.canonicalCount++
|
||||
|
||||
if glog.V(logger.Debug) {
|
||||
glog.Infof("inserted block #%d (%d TXs %d UNCs) (%x...)\n", block.Number(), len(block.Transactions()), len(block.Uncles()), block.Hash().Bytes()[0:4])
|
||||
}
|
||||
} else {
|
||||
queue[i] = ChainSideEvent{block, logs}
|
||||
queueEvent.sideCount++
|
||||
|
|
@ -501,6 +539,16 @@ func (self *ChainManager) InsertChain(chain types.Blocks) error {
|
|||
}
|
||||
self.mu.Unlock()
|
||||
|
||||
stats.processed++
|
||||
|
||||
self.futureBlocks.Delete(block.Hash())
|
||||
|
||||
}
|
||||
|
||||
if (stats.queued > 0 || stats.processed > 0) && bool(glog.V(logger.Info)) {
|
||||
tend := time.Since(tstart)
|
||||
start, end := chain[0], chain[len(chain)-1]
|
||||
glog.Infof("imported %d block(s) %d queued in %v. #%v [%x / %x]\n", stats.processed, stats.queued, tend, end.Number(), start.Hash().Bytes()[:4], end.Hash().Bytes()[:4])
|
||||
}
|
||||
|
||||
go self.eventMux.Post(queueEvent)
|
||||
|
|
@ -510,7 +558,7 @@ func (self *ChainManager) InsertChain(chain types.Blocks) error {
|
|||
|
||||
func (self *ChainManager) update() {
|
||||
events := self.eventMux.Subscribe(queueEvent{})
|
||||
|
||||
futureTimer := time.NewTicker(5 * time.Second)
|
||||
out:
|
||||
for {
|
||||
select {
|
||||
|
|
@ -536,6 +584,8 @@ out:
|
|||
self.eventMux.Post(event)
|
||||
}
|
||||
}
|
||||
case <-futureTimer.C:
|
||||
self.procFutureBlocks()
|
||||
case <-self.quit:
|
||||
break out
|
||||
}
|
||||
|
|
|
|||
|
|
@ -20,7 +20,7 @@ var ZeroHash160 = make([]byte, 20)
|
|||
var ZeroHash512 = make([]byte, 64)
|
||||
|
||||
func GenesisBlock(db common.Database) *types.Block {
|
||||
genesis := types.NewBlock(common.Hash{}, common.Address{}, common.Hash{}, params.GenesisDifficulty, 42, "")
|
||||
genesis := types.NewBlock(common.Hash{}, common.Address{}, common.Hash{}, params.GenesisDifficulty, 42, nil)
|
||||
genesis.Header().Number = common.Big0
|
||||
genesis.Header().GasLimit = params.GenesisGasLimit
|
||||
genesis.Header().GasUsed = common.Big0
|
||||
|
|
|
|||
|
|
@ -7,6 +7,8 @@ import (
|
|||
|
||||
"github.com/ethereum/go-ethereum/common"
|
||||
"github.com/ethereum/go-ethereum/crypto"
|
||||
"github.com/ethereum/go-ethereum/logger"
|
||||
"github.com/ethereum/go-ethereum/logger/glog"
|
||||
"github.com/ethereum/go-ethereum/rlp"
|
||||
"github.com/ethereum/go-ethereum/trie"
|
||||
)
|
||||
|
|
@ -121,7 +123,10 @@ func NewStateObjectFromBytes(address common.Address, data []byte, db common.Data
|
|||
func (self *StateObject) MarkForDeletion() {
|
||||
self.remove = true
|
||||
self.dirty = true
|
||||
statelogger.Debugf("%x: #%d %v X\n", self.Address(), self.nonce, self.balance)
|
||||
|
||||
if glog.V(logger.Core) {
|
||||
glog.Infof("%x: #%d %v X\n", self.Address(), self.nonce, self.balance)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *StateObject) getAddr(addr common.Hash) *common.Value {
|
||||
|
|
@ -185,13 +190,17 @@ func (c *StateObject) GetInstr(pc *big.Int) *common.Value {
|
|||
func (c *StateObject) AddBalance(amount *big.Int) {
|
||||
c.SetBalance(new(big.Int).Add(c.balance, amount))
|
||||
|
||||
statelogger.Debugf("%x: #%d %v (+ %v)\n", c.Address(), c.nonce, c.balance, amount)
|
||||
if glog.V(logger.Core) {
|
||||
glog.Infof("%x: #%d %v (+ %v)\n", c.Address(), c.nonce, c.balance, amount)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *StateObject) SubBalance(amount *big.Int) {
|
||||
c.SetBalance(new(big.Int).Sub(c.balance, amount))
|
||||
|
||||
statelogger.Debugf("%x: #%d %v (- %v)\n", c.Address(), c.nonce, c.balance, amount)
|
||||
if glog.V(logger.Core) {
|
||||
glog.Infof("%x: #%d %v (- %v)\n", c.Address(), c.nonce, c.balance, amount)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *StateObject) SetBalance(amount *big.Int) {
|
||||
|
|
@ -225,7 +234,9 @@ func (c *StateObject) ConvertGas(gas, price *big.Int) error {
|
|||
func (self *StateObject) SetGasPool(gasLimit *big.Int) {
|
||||
self.gasPool = new(big.Int).Set(gasLimit)
|
||||
|
||||
statelogger.Debugf("%x: gas (+ %v)", self.Address(), self.gasPool)
|
||||
if glog.V(logger.Core) {
|
||||
glog.Infof("%x: gas (+ %v)", self.Address(), self.gasPool)
|
||||
}
|
||||
}
|
||||
|
||||
func (self *StateObject) BuyGas(gas, price *big.Int) error {
|
||||
|
|
|
|||
|
|
@ -6,11 +6,10 @@ import (
|
|||
|
||||
"github.com/ethereum/go-ethereum/common"
|
||||
"github.com/ethereum/go-ethereum/logger"
|
||||
"github.com/ethereum/go-ethereum/logger/glog"
|
||||
"github.com/ethereum/go-ethereum/trie"
|
||||
)
|
||||
|
||||
var statelogger = logger.NewLogger("STATE")
|
||||
|
||||
// StateDBs within the ethereum protocol are used to store anything
|
||||
// within the merkle trie. StateDBs take care of caching and storing
|
||||
// nested states. It's the general query interface to retrieve:
|
||||
|
|
@ -210,7 +209,9 @@ func (self *StateDB) GetOrNewStateObject(addr common.Address) *StateObject {
|
|||
|
||||
// NewStateObject create a state object whether it exist in the trie or not
|
||||
func (self *StateDB) newStateObject(addr common.Address) *StateObject {
|
||||
statelogger.Debugf("(+) %x\n", addr)
|
||||
if glog.V(logger.Core) {
|
||||
glog.Infof("(+) %x\n", addr)
|
||||
}
|
||||
|
||||
stateObject := NewStateObject(addr, self.db)
|
||||
self.stateObjects[addr.Str()] = stateObject
|
||||
|
|
|
|||
|
|
@ -8,6 +8,8 @@ import (
|
|||
"github.com/ethereum/go-ethereum/core/state"
|
||||
"github.com/ethereum/go-ethereum/core/vm"
|
||||
"github.com/ethereum/go-ethereum/crypto"
|
||||
"github.com/ethereum/go-ethereum/logger"
|
||||
"github.com/ethereum/go-ethereum/logger/glog"
|
||||
"github.com/ethereum/go-ethereum/params"
|
||||
)
|
||||
|
||||
|
|
@ -166,9 +168,6 @@ func (self *StateTransition) preCheck() (err error) {
|
|||
}
|
||||
|
||||
func (self *StateTransition) transitionState() (ret []byte, usedGas *big.Int, err error) {
|
||||
// statelogger.Debugf("(~) %x\n", self.msg.Hash())
|
||||
|
||||
// XXX Transactions after this point are considered valid.
|
||||
if err = self.preCheck(); err != nil {
|
||||
return
|
||||
}
|
||||
|
|
@ -207,7 +206,7 @@ func (self *StateTransition) transitionState() (ret []byte, usedGas *big.Int, er
|
|||
if err := self.UseGas(dataGas); err == nil {
|
||||
ref.SetCode(ret)
|
||||
} else {
|
||||
statelogger.Infoln("Insufficient gas for creating code. Require", dataGas, "and have", self.gas)
|
||||
glog.V(logger.Core).Infoln("Insufficient gas for creating code. Require", dataGas, "and have", self.gas)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
|
|
|
|||
|
|
@ -2,14 +2,15 @@ package core
|
|||
|
||||
import (
|
||||
"crypto/ecdsa"
|
||||
"math/big"
|
||||
"testing"
|
||||
|
||||
"github.com/ethereum/go-ethereum/common"
|
||||
"github.com/ethereum/go-ethereum/core/state"
|
||||
"github.com/ethereum/go-ethereum/core/types"
|
||||
"github.com/ethereum/go-ethereum/crypto"
|
||||
"github.com/ethereum/go-ethereum/ethdb"
|
||||
"github.com/ethereum/go-ethereum/event"
|
||||
"github.com/ethereum/go-ethereum/core/state"
|
||||
)
|
||||
|
||||
// State query interface
|
||||
|
|
@ -88,7 +89,10 @@ func TestRemoveInvalid(t *testing.T) {
|
|||
|
||||
func TestInvalidSender(t *testing.T) {
|
||||
pool, _ := setup()
|
||||
err := pool.ValidateTransaction(new(types.Transaction))
|
||||
tx := new(types.Transaction)
|
||||
tx.R = new(big.Int)
|
||||
tx.S = new(big.Int)
|
||||
err := pool.ValidateTransaction(tx)
|
||||
if err != ErrInvalidSender {
|
||||
t.Errorf("expected %v, got %v", ErrInvalidSender, err)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -39,7 +39,7 @@ type Header struct {
|
|||
// Creation time
|
||||
Time uint64
|
||||
// Extra data
|
||||
Extra string
|
||||
Extra []byte
|
||||
// Mix digest for quick checking to prevent DOS
|
||||
MixDigest common.Hash
|
||||
// Nonce
|
||||
|
|
@ -121,7 +121,7 @@ type storageblock struct {
|
|||
TD *big.Int
|
||||
}
|
||||
|
||||
func NewBlock(parentHash common.Hash, coinbase common.Address, root common.Hash, difficulty *big.Int, nonce uint64, extra string) *Block {
|
||||
func NewBlock(parentHash common.Hash, coinbase common.Address, root common.Hash, difficulty *big.Int, nonce uint64, extra []byte) *Block {
|
||||
header := &Header{
|
||||
Root: root,
|
||||
ParentHash: parentHash,
|
||||
|
|
@ -371,7 +371,7 @@ func (self *Header) String() string {
|
|||
GasLimit: %v
|
||||
GasUsed: %v
|
||||
Time: %v
|
||||
Extra: %v
|
||||
Extra: %s
|
||||
MixDigest: %x
|
||||
Nonce: %x`,
|
||||
self.ParentHash, self.UncleHash, self.Coinbase, self.Root, self.TxHash, self.ReceiptHash, self.Bloom, self.Difficulty, self.Number, self.GasLimit, self.GasUsed, self.Time, self.Extra, self.MixDigest, self.Nonce)
|
||||
|
|
|
|||
|
|
@ -44,8 +44,8 @@ func TestBlockEncoding(t *testing.T) {
|
|||
GasLimit: big.NewInt(50000),
|
||||
AccountNonce: 0,
|
||||
V: 27,
|
||||
R: common.FromHex("9bea4c4daac7c7c52e093e6a4c35dbbcf8856f1af7b059ba20253e70848d094f"),
|
||||
S: common.FromHex("8a8fae537ce25ed8cb5af9adac3f141af69bd515bd2ba031522df09b97dd72b1"),
|
||||
R: common.String2Big("0x9bea4c4daac7c7c52e093e6a4c35dbbcf8856f1af7b059ba20253e70848d094f"),
|
||||
S: common.String2Big("0x8a8fae537ce25ed8cb5af9adac3f141af69bd515bd2ba031522df09b97dd72b1"),
|
||||
Recipient: &to,
|
||||
},
|
||||
})
|
||||
|
|
|
|||
|
|
@ -24,15 +24,31 @@ type Transaction struct {
|
|||
Amount *big.Int
|
||||
Payload []byte
|
||||
V byte
|
||||
R, S []byte
|
||||
R, S *big.Int
|
||||
}
|
||||
|
||||
func NewContractCreationTx(amount, gasLimit, gasPrice *big.Int, data []byte) *Transaction {
|
||||
return &Transaction{Recipient: nil, Amount: amount, GasLimit: gasLimit, Price: gasPrice, Payload: data}
|
||||
return &Transaction{
|
||||
Recipient: nil,
|
||||
Amount: amount,
|
||||
GasLimit: gasLimit,
|
||||
Price: gasPrice,
|
||||
Payload: data,
|
||||
R: new(big.Int),
|
||||
S: new(big.Int),
|
||||
}
|
||||
}
|
||||
|
||||
func NewTransactionMessage(to common.Address, amount, gasAmount, gasPrice *big.Int, data []byte) *Transaction {
|
||||
return &Transaction{Recipient: &to, Amount: amount, GasLimit: gasAmount, Price: gasPrice, Payload: data}
|
||||
return &Transaction{
|
||||
Recipient: &to,
|
||||
Amount: amount,
|
||||
GasLimit: gasAmount,
|
||||
Price: gasPrice,
|
||||
Payload: data,
|
||||
R: new(big.Int),
|
||||
S: new(big.Int),
|
||||
}
|
||||
}
|
||||
|
||||
func NewTransactionFromBytes(data []byte) *Transaction {
|
||||
|
|
@ -94,8 +110,8 @@ func (tx *Transaction) To() *common.Address {
|
|||
|
||||
func (tx *Transaction) Curve() (v byte, r []byte, s []byte) {
|
||||
v = byte(tx.V)
|
||||
r = common.LeftPadBytes(tx.R, 32)
|
||||
s = common.LeftPadBytes(tx.S, 32)
|
||||
r = common.LeftPadBytes(tx.R.Bytes(), 32)
|
||||
s = common.LeftPadBytes(tx.S.Bytes(), 32)
|
||||
return
|
||||
}
|
||||
|
||||
|
|
@ -118,8 +134,8 @@ func (tx *Transaction) PublicKey() []byte {
|
|||
}
|
||||
|
||||
func (tx *Transaction) SetSignatureValues(sig []byte) error {
|
||||
tx.R = sig[:32]
|
||||
tx.S = sig[32:64]
|
||||
tx.R = common.Bytes2Big(sig[:32])
|
||||
tx.S = common.Bytes2Big(sig[32:64])
|
||||
tx.V = sig[64] + 27
|
||||
return nil
|
||||
}
|
||||
|
|
@ -137,7 +153,7 @@ func (tx *Transaction) SignECDSA(prv *ecdsa.PrivateKey) error {
|
|||
// TODO: remove
|
||||
func (tx *Transaction) RlpData() interface{} {
|
||||
data := []interface{}{tx.AccountNonce, tx.Price, tx.GasLimit, tx.Recipient, tx.Amount, tx.Payload}
|
||||
return append(data, tx.V, new(big.Int).SetBytes(tx.R).Bytes(), new(big.Int).SetBytes(tx.S).Bytes())
|
||||
return append(data, tx.V, tx.R.Bytes(), tx.S.Bytes())
|
||||
}
|
||||
|
||||
func (tx *Transaction) String() string {
|
||||
|
|
|
|||
|
|
@ -30,8 +30,8 @@ var (
|
|||
Amount: big.NewInt(10),
|
||||
Payload: common.FromHex("5544"),
|
||||
V: 28,
|
||||
R: common.FromHex("98ff921201554726367d2be8c804a7ff89ccf285ebc57dff8ae4c44b9c19ac4a"),
|
||||
S: common.FromHex("8887321be575c8095f789dd4c743dfe42c1820f9231f98a962b210e3ac2452a3"),
|
||||
R: common.String2Big("0x98ff921201554726367d2be8c804a7ff89ccf285ebc57dff8ae4c44b9c19ac4a"),
|
||||
S: common.String2Big("0x8887321be575c8095f789dd4c743dfe42c1820f9231f98a962b210e3ac2452a3"),
|
||||
}
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -5,11 +5,9 @@ import (
|
|||
"math/big"
|
||||
|
||||
"github.com/ethereum/go-ethereum/common"
|
||||
"github.com/ethereum/go-ethereum/logger"
|
||||
"github.com/ethereum/go-ethereum/logger/glog"
|
||||
)
|
||||
|
||||
var vmlogger = logger.NewLogger("VM")
|
||||
|
||||
// Global Debug flag indicating Debug VM (full logging)
|
||||
var Debug bool
|
||||
|
||||
|
|
@ -41,7 +39,7 @@ func NewVm(env Environment) VirtualMachine {
|
|||
case JitVmTy:
|
||||
return NewJitVm(env)
|
||||
default:
|
||||
vmlogger.Infoln("unsupported vm type %d", env.VmType())
|
||||
glog.V(0).Infoln("unsupported vm type %d", env.VmType())
|
||||
fallthrough
|
||||
case StdVmTy:
|
||||
return New(env)
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import (
|
|||
"github.com/ethereum/go-ethereum/common"
|
||||
"github.com/ethereum/go-ethereum/core/state"
|
||||
"github.com/ethereum/go-ethereum/crypto"
|
||||
"github.com/ethereum/go-ethereum/logger/glog"
|
||||
"github.com/ethereum/go-ethereum/params"
|
||||
)
|
||||
|
||||
|
|
@ -885,21 +886,17 @@ func (self *Vm) RunPrecompiled(p *PrecompiledAccount, callData []byte, context *
|
|||
|
||||
func (self *Vm) Printf(format string, v ...interface{}) VirtualMachine {
|
||||
if self.debug {
|
||||
if self.logTy == LogTyPretty {
|
||||
self.logStr += fmt.Sprintf(format, v...)
|
||||
}
|
||||
}
|
||||
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *Vm) Endl() VirtualMachine {
|
||||
if self.debug {
|
||||
if self.logTy == LogTyPretty {
|
||||
vmlogger.Infoln(self.logStr)
|
||||
glog.V(0).Infoln(self.logStr)
|
||||
self.logStr = ""
|
||||
}
|
||||
}
|
||||
|
||||
return self
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,13 +1,17 @@
|
|||
package secp256k1
|
||||
|
||||
// TODO: set USE_SCALAR_4X64 depending on platform?
|
||||
|
||||
/*
|
||||
#cgo CFLAGS: -std=gnu99 -Wno-error
|
||||
#cgo CFLAGS: -I./secp256k1
|
||||
#cgo darwin CFLAGS: -I/usr/local/include
|
||||
#cgo LDFLAGS: -lgmp
|
||||
#cgo darwin LDFLAGS: -L/usr/local/lib
|
||||
#define USE_FIELD_10X26
|
||||
#define USE_NUM_GMP
|
||||
#define USE_FIELD_10X26
|
||||
#define USE_FIELD_INV_BUILTIN
|
||||
#define USE_SCALAR_8X32
|
||||
#define USE_SCALAR_INV_BUILTIN
|
||||
#include "./secp256k1/src/secp256k1.c"
|
||||
*/
|
||||
import "C"
|
||||
|
|
@ -38,32 +42,14 @@ import (
|
|||
*/
|
||||
|
||||
func init() {
|
||||
C.secp256k1_start() //takes 10ms to 100ms
|
||||
//takes 10ms to 100ms
|
||||
C.secp256k1_start(3) // SECP256K1_START_SIGN | SECP256K1_START_VERIFY
|
||||
}
|
||||
|
||||
func Stop() {
|
||||
C.secp256k1_stop()
|
||||
}
|
||||
|
||||
/*
|
||||
int secp256k1_ecdsa_pubkey_create(
|
||||
unsigned char *pubkey, int *pubkeylen,
|
||||
const unsigned char *seckey, int compressed);
|
||||
*/
|
||||
|
||||
/** Compute the public key for a secret key.
|
||||
* In: compressed: whether the computed public key should be compressed
|
||||
* seckey: pointer to a 32-byte private key.
|
||||
* Out: pubkey: pointer to a 33-byte (if compressed) or 65-byte (if uncompressed)
|
||||
* area to store the public key.
|
||||
* pubkeylen: pointer to int that will be updated to contains the pubkey's
|
||||
* length.
|
||||
* Returns: 1: secret was valid, public key stores
|
||||
* 0: secret was invalid, try again.
|
||||
*/
|
||||
|
||||
//pubkey, seckey
|
||||
|
||||
func GenerateKeyPair() ([]byte, []byte) {
|
||||
|
||||
pubkey_len := C.int(65)
|
||||
|
|
@ -75,7 +61,7 @@ func GenerateKeyPair() ([]byte, []byte) {
|
|||
var pubkey_ptr *C.uchar = (*C.uchar)(unsafe.Pointer(&pubkey[0]))
|
||||
var seckey_ptr *C.uchar = (*C.uchar)(unsafe.Pointer(&seckey[0]))
|
||||
|
||||
ret := C.secp256k1_ecdsa_pubkey_create(
|
||||
ret := C.secp256k1_ec_pubkey_create(
|
||||
pubkey_ptr, &pubkey_len,
|
||||
seckey_ptr, 0)
|
||||
|
||||
|
|
@ -98,7 +84,7 @@ func GeneratePubKey(seckey []byte) ([]byte, error) {
|
|||
var pubkey_ptr *C.uchar = (*C.uchar)(unsafe.Pointer(&pubkey[0]))
|
||||
var seckey_ptr *C.uchar = (*C.uchar)(unsafe.Pointer(&seckey[0]))
|
||||
|
||||
ret := C.secp256k1_ecdsa_pubkey_create(
|
||||
ret := C.secp256k1_ec_pubkey_create(
|
||||
pubkey_ptr, &pubkey_len,
|
||||
seckey_ptr, 0)
|
||||
|
||||
|
|
@ -109,26 +95,6 @@ func GeneratePubKey(seckey []byte) ([]byte, error) {
|
|||
return pubkey, nil
|
||||
}
|
||||
|
||||
/*
|
||||
* Create a compact ECDSA signature (64 byte + recovery id).
|
||||
* Returns: 1: signature created
|
||||
* 0: nonce invalid, try another one
|
||||
* In: msg: the message being signed
|
||||
* msglen: the length of the message being signed
|
||||
* seckey: pointer to a 32-byte secret key (assumed to be valid)
|
||||
* nonce: pointer to a 32-byte nonce (generated with a cryptographic PRNG)
|
||||
* Out: sig: pointer to a 64-byte array where the signature will be placed.
|
||||
* recid: pointer to an int, which will be updated to contain the recovery id.
|
||||
*/
|
||||
|
||||
/*
|
||||
int secp256k1_ecdsa_sign_compact(const unsigned char *msg, int msglen,
|
||||
unsigned char *sig64,
|
||||
const unsigned char *seckey,
|
||||
const unsigned char *nonce,
|
||||
int *recid);
|
||||
*/
|
||||
|
||||
func Sign(msg []byte, seckey []byte) ([]byte, error) {
|
||||
nonce := randentropy.GetEntropyMixed(32)
|
||||
|
||||
|
|
@ -136,19 +102,22 @@ func Sign(msg []byte, seckey []byte) ([]byte, error) {
|
|||
var recid C.int
|
||||
|
||||
var msg_ptr *C.uchar = (*C.uchar)(unsafe.Pointer(&msg[0]))
|
||||
var seckey_ptr *C.uchar = (*C.uchar)(unsafe.Pointer(&seckey[0]))
|
||||
var nonce_ptr *C.uchar = (*C.uchar)(unsafe.Pointer(&nonce[0]))
|
||||
var sig_ptr *C.uchar = (*C.uchar)(unsafe.Pointer(&sig[0]))
|
||||
var seckey_ptr *C.uchar = (*C.uchar)(unsafe.Pointer(&seckey[0]))
|
||||
|
||||
if C.secp256k1_ecdsa_seckey_verify(seckey_ptr) != C.int(1) {
|
||||
var noncefp_ptr = &(*C.secp256k1_nonce_function_default)
|
||||
var ndata_ptr = unsafe.Pointer(&nonce[0])
|
||||
|
||||
if C.secp256k1_ec_seckey_verify(seckey_ptr) != C.int(1) {
|
||||
return nil, errors.New("Invalid secret key")
|
||||
}
|
||||
|
||||
ret := C.secp256k1_ecdsa_sign_compact(
|
||||
msg_ptr, C.int(len(msg)),
|
||||
msg_ptr,
|
||||
sig_ptr,
|
||||
seckey_ptr,
|
||||
nonce_ptr,
|
||||
noncefp_ptr,
|
||||
ndata_ptr,
|
||||
&recid)
|
||||
|
||||
sig[64] = byte(int(recid))
|
||||
|
|
@ -162,37 +131,24 @@ func Sign(msg []byte, seckey []byte) ([]byte, error) {
|
|||
|
||||
}
|
||||
|
||||
/*
|
||||
* Verify an ECDSA secret key.
|
||||
* Returns: 1: secret key is valid
|
||||
* 0: secret key is invalid
|
||||
* In: seckey: pointer to a 32-byte secret key
|
||||
*/
|
||||
|
||||
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_ecdsa_seckey_verify(seckey_ptr)
|
||||
ret := C.secp256k1_ec_seckey_verify(seckey_ptr)
|
||||
if int(ret) != 1 {
|
||||
return errors.New("invalid seckey")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
/*
|
||||
* Validate a public key.
|
||||
* Returns: 1: valid public key
|
||||
* 0: invalid public key
|
||||
*/
|
||||
|
||||
func VerifyPubkeyValidity(pubkey []byte) error {
|
||||
if len(pubkey) != 65 {
|
||||
return errors.New("pub key is not 65 bytes")
|
||||
}
|
||||
var pubkey_ptr *C.uchar = (*C.uchar)(unsafe.Pointer(&pubkey[0]))
|
||||
ret := C.secp256k1_ecdsa_pubkey_verify(pubkey_ptr, 65)
|
||||
ret := C.secp256k1_ec_pubkey_verify(pubkey_ptr, 65)
|
||||
if int(ret) != 1 {
|
||||
return errors.New("invalid pubkey")
|
||||
}
|
||||
|
|
@ -254,25 +210,6 @@ func VerifySignature(msg []byte, sig []byte, pubkey1 []byte) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
/*
|
||||
int secp256k1_ecdsa_recover_compact(const unsigned char *msg, int msglen,
|
||||
const unsigned char *sig64,
|
||||
unsigned char *pubkey, int *pubkeylen,
|
||||
int compressed, int recid);
|
||||
*/
|
||||
|
||||
/*
|
||||
* Recover an ECDSA public key from a compact signature.
|
||||
* Returns: 1: public key succesfully recovered (which guarantees a correct signature).
|
||||
* 0: otherwise.
|
||||
* In: msg: the message assumed to be signed
|
||||
* msglen: the length of the message
|
||||
* compressed: whether to recover a compressed or uncompressed pubkey
|
||||
* recid: the recovery id (as returned by ecdsa_sign_compact)
|
||||
* Out: pubkey: pointer to a 33 or 65 byte array to put the pubkey.
|
||||
* pubkeylen: pointer to an int that will contain the pubkey length.
|
||||
*/
|
||||
|
||||
//recovers the public key from the signature
|
||||
//recovery of pubkey means correct signature
|
||||
func RecoverPubkey(msg []byte, sig []byte) ([]byte, error) {
|
||||
|
|
@ -289,10 +226,12 @@ func RecoverPubkey(msg []byte, sig []byte) ([]byte, error) {
|
|||
var pubkeylen C.int
|
||||
|
||||
ret := C.secp256k1_ecdsa_recover_compact(
|
||||
msg_ptr, C.int(len(msg)),
|
||||
msg_ptr,
|
||||
sig_ptr,
|
||||
pubkey_ptr, &pubkeylen,
|
||||
C.int(0), C.int(sig[64]),
|
||||
pubkey_ptr,
|
||||
&pubkeylen,
|
||||
C.int(0),
|
||||
C.int(sig[64]),
|
||||
)
|
||||
|
||||
if ret == C.int(0) {
|
||||
|
|
|
|||
32
crypto/secp256k1/secp256k1/.travis.yml
Normal file
32
crypto/secp256k1/secp256k1/.travis.yml
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
language: c
|
||||
compiler:
|
||||
- clang
|
||||
- gcc
|
||||
install:
|
||||
- sudo apt-get install -qq libssl-dev
|
||||
- if [ "$BIGNUM" = "gmp" -o "$BIGNUM" = "auto" ]; then sudo apt-get install --no-install-recommends --no-upgrade -qq libgmp-dev; fi
|
||||
- if [ -n "$EXTRAPACKAGES" ]; then sudo apt-get update && sudo apt-get install --no-install-recommends --no-upgrade $EXTRAPACKAGES; fi
|
||||
env:
|
||||
global:
|
||||
- FIELD=auto BIGNUM=auto SCALAR=auto ENDOMORPHISM=no ASM=no BUILD=check EXTRAFLAGS= HOST= EXTRAPACKAGES=
|
||||
matrix:
|
||||
- SCALAR=32bit
|
||||
- SCALAR=64bit
|
||||
- FIELD=64bit
|
||||
- FIELD=64bit ENDOMORPHISM=yes
|
||||
- FIELD=64bit ASM=x86_64
|
||||
- FIELD=64bit ENDOMORPHISM=yes ASM=x86_64
|
||||
- FIELD=32bit
|
||||
- FIELD=32bit ENDOMORPHISM=yes
|
||||
- BIGNUM=no
|
||||
- BIGNUM=no ENDOMORPHISM=yes
|
||||
- BUILD=distcheck
|
||||
- EXTRAFLAGS=CFLAGS=-DDETERMINISTIC
|
||||
- HOST=i686-linux-gnu EXTRAPACKAGES="gcc-multilib"
|
||||
- HOST=i686-linux-gnu EXTRAPACKAGES="gcc-multilib" ENDOMORPHISM=yes
|
||||
before_script: ./autogen.sh
|
||||
script:
|
||||
- if [ -n "$HOST" ]; then export USE_HOST="--host=$HOST"; fi
|
||||
- if [ "x$HOST" = "xi686-linux-gnu" ]; then export CC="$CC -m32"; fi
|
||||
- ./configure --enable-endomorphism=$ENDOMORPHISM --with-field=$FIELD --with-bignum=$BIGNUM --with-scalar=$SCALAR $EXTRAFLAGS $USE_HOST && make -j2 $BUILD
|
||||
os: linux
|
||||
|
|
@ -1,55 +0,0 @@
|
|||
$(shell CC=$(CC) YASM=$(YASM) ./configure)
|
||||
include config.mk
|
||||
|
||||
FILES := src/*.h src/impl/*.h
|
||||
|
||||
JAVA_FILES := src/java/org_bitcoin_NativeSecp256k1.h src/java/org_bitcoin_NativeSecp256k1.c
|
||||
|
||||
OBJS :=
|
||||
|
||||
ifeq ($(USE_ASM), 1)
|
||||
OBJS := $(OBJS) obj/field_5x$(HAVE_LIMB)_asm.o
|
||||
endif
|
||||
STD="gnu99"
|
||||
|
||||
default: tests libsecp256k1.a libsecp256k1.so
|
||||
|
||||
clean:
|
||||
rm -rf obj/*.o bench tests *.a *.so config.mk
|
||||
|
||||
obj/field_5x52_asm.o: src/field_5x52_asm.asm
|
||||
$(YASM) -f elf64 -o obj/field_5x52_asm.o src/field_5x52_asm.asm
|
||||
|
||||
obj/field_5x64_asm.o: src/field_5x64_asm.asm
|
||||
$(YASM) -f elf64 -o obj/field_5x64_asm.o src/field_5x64_asm.asm
|
||||
|
||||
obj/secp256k1.o: $(FILES) src/secp256k1.c include/secp256k1.h
|
||||
$(CC) -fPIC -std=$(STD) $(CFLAGS) $(CFLAGS_EXTRA) -DNDEBUG -$(OPTLEVEL) src/secp256k1.c -c -o obj/secp256k1.o
|
||||
|
||||
bench: $(FILES) src/bench.c $(OBJS)
|
||||
$(CC) -fPIC -std=$(STD) $(CFLAGS) $(CFLAGS_EXTRA) $(CFLAGS_TEST_EXTRA) -DNDEBUG -$(OPTLEVEL) src/bench.c $(OBJS) $(LDFLAGS_EXTRA) $(LDFLAGS_TEST_EXTRA) -o bench
|
||||
|
||||
tests: $(FILES) src/tests.c $(OBJS)
|
||||
$(CC) -std=$(STD) $(CFLAGS) $(CFLAGS_EXTRA) $(CFLAGS_TEST_EXTRA) -DVERIFY -fstack-protector-all -$(OPTLEVEL) -ggdb3 src/tests.c $(OBJS) $(LDFLAGS_EXTRA) $(LDFLAGS_TEST_EXTRA) -o tests
|
||||
|
||||
tests_fuzzer: $(FILES) src/tests_fuzzer.c obj/secp256k1.o $(OBJS)
|
||||
$(CC) -std=$(STD) $(CFLAGS) $(CFLAGS_EXTRA) $(CFLAGS_TEST_EXTRA) -DVERIFY -fstack-protector-all -$(OPTLEVEL) -ggdb3 src/tests_fuzzer.c $(OBJS) obj/secp256k1.o $(LDFLAGS_EXTRA) $(LDFLAGS_TEST_EXTRA) -o tests_fuzzer
|
||||
|
||||
coverage: $(FILES) src/tests.c $(OBJS)
|
||||
rm -rf tests.gcno tests.gcda tests_cov
|
||||
$(CC) -std=$(STD) $(CFLAGS) $(CFLAGS_EXTRA) $(CFLAGS_TEST_EXTRA) -DVERIFY --coverage -$(OPTLEVEL) -g src/tests.c $(OBJS) $(LDFLAGS_EXTRA) $(LDFLAGS_TEST_EXTRA) -o tests_cov
|
||||
rm -rf lcov
|
||||
mkdir -p lcov
|
||||
cd lcov; lcov --directory ../ --zerocounters
|
||||
cd lcov; ../tests_cov
|
||||
cd lcov; lcov --directory ../ --capture --output-file secp256k1.info
|
||||
cd lcov; genhtml -o . secp256k1.info
|
||||
|
||||
libsecp256k1.a: obj/secp256k1.o $(OBJS)
|
||||
$(AR) -rs $@ $(OBJS) obj/secp256k1.o
|
||||
|
||||
libsecp256k1.so: obj/secp256k1.o $(OBJS)
|
||||
$(CC) -std=$(STD) $(LDFLAGS_EXTRA) $(OBJS) obj/secp256k1.o -shared -o libsecp256k1.so
|
||||
|
||||
libjavasecp256k1.so: $(OBJS) obj/secp256k1.o $(JAVA_FILES)
|
||||
$(CC) -fPIC -std=$(STD) $(CFLAGS) $(CFLAGS_EXTRA) -DNDEBUG -$(OPTLEVEL) -I. src/java/org_bitcoin_NativeSecp256k1.c $(LDFLAGS_EXTRA) $(OBJS) obj/secp256k1.o -shared -o libjavasecp256k1.so
|
||||
77
crypto/secp256k1/secp256k1/Makefile.am
Normal file
77
crypto/secp256k1/secp256k1/Makefile.am
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
ACLOCAL_AMFLAGS = -I build-aux/m4
|
||||
|
||||
lib_LTLIBRARIES = libsecp256k1.la
|
||||
include_HEADERS = include/secp256k1.h
|
||||
noinst_HEADERS =
|
||||
noinst_HEADERS += src/scalar.h
|
||||
noinst_HEADERS += src/scalar_4x64.h
|
||||
noinst_HEADERS += src/scalar_8x32.h
|
||||
noinst_HEADERS += src/scalar_impl.h
|
||||
noinst_HEADERS += src/scalar_4x64_impl.h
|
||||
noinst_HEADERS += src/scalar_8x32_impl.h
|
||||
noinst_HEADERS += src/group.h
|
||||
noinst_HEADERS += src/group_impl.h
|
||||
noinst_HEADERS += src/num_gmp.h
|
||||
noinst_HEADERS += src/num_gmp_impl.h
|
||||
noinst_HEADERS += src/ecdsa.h
|
||||
noinst_HEADERS += src/ecdsa_impl.h
|
||||
noinst_HEADERS += src/eckey.h
|
||||
noinst_HEADERS += src/eckey_impl.h
|
||||
noinst_HEADERS += src/ecmult.h
|
||||
noinst_HEADERS += src/ecmult_impl.h
|
||||
noinst_HEADERS += src/ecmult_gen.h
|
||||
noinst_HEADERS += src/ecmult_gen_impl.h
|
||||
noinst_HEADERS += src/num.h
|
||||
noinst_HEADERS += src/num_impl.h
|
||||
noinst_HEADERS += src/field_10x26.h
|
||||
noinst_HEADERS += src/field_10x26_impl.h
|
||||
noinst_HEADERS += src/field_5x52.h
|
||||
noinst_HEADERS += src/field_5x52_impl.h
|
||||
noinst_HEADERS += src/field_5x52_int128_impl.h
|
||||
noinst_HEADERS += src/field_5x52_asm_impl.h
|
||||
noinst_HEADERS += src/java/org_bitcoin_NativeSecp256k1.h
|
||||
noinst_HEADERS += src/util.h
|
||||
noinst_HEADERS += src/testrand.h
|
||||
noinst_HEADERS += src/testrand_impl.h
|
||||
noinst_HEADERS += src/hash.h
|
||||
noinst_HEADERS += src/hash_impl.h
|
||||
noinst_HEADERS += src/field.h
|
||||
noinst_HEADERS += src/field_impl.h
|
||||
noinst_HEADERS += src/bench.h
|
||||
|
||||
pkgconfigdir = $(libdir)/pkgconfig
|
||||
pkgconfig_DATA = libsecp256k1.pc
|
||||
|
||||
libsecp256k1_la_SOURCES = src/secp256k1.c
|
||||
libsecp256k1_la_CPPFLAGS = -I$(top_srcdir)/include $(SECP_INCLUDES)
|
||||
libsecp256k1_la_LIBADD = $(SECP_LIBS)
|
||||
|
||||
|
||||
noinst_PROGRAMS =
|
||||
if USE_BENCHMARK
|
||||
noinst_PROGRAMS += bench_verify bench_recover bench_sign bench_internal
|
||||
bench_verify_SOURCES = src/bench_verify.c
|
||||
bench_verify_LDADD = libsecp256k1.la $(SECP_LIBS)
|
||||
bench_verify_LDFLAGS = -static
|
||||
bench_recover_SOURCES = src/bench_recover.c
|
||||
bench_recover_LDADD = libsecp256k1.la $(SECP_LIBS)
|
||||
bench_recover_LDFLAGS = -static
|
||||
bench_sign_SOURCES = src/bench_sign.c
|
||||
bench_sign_LDADD = libsecp256k1.la $(SECP_LIBS)
|
||||
bench_sign_LDFLAGS = -static
|
||||
bench_internal_SOURCES = src/bench_internal.c
|
||||
bench_internal_LDADD = $(SECP_LIBS)
|
||||
bench_internal_LDFLAGS = -static
|
||||
bench_internal_CPPFLAGS = $(SECP_INCLUDES)
|
||||
endif
|
||||
|
||||
if USE_TESTS
|
||||
noinst_PROGRAMS += tests
|
||||
tests_SOURCES = src/tests.c
|
||||
tests_CPPFLAGS = -DVERIFY $(SECP_INCLUDES) $(SECP_TEST_INCLUDES)
|
||||
tests_LDADD = $(SECP_LIBS) $(SECP_TEST_LIBS)
|
||||
tests_LDFLAGS = -static
|
||||
TESTS = tests
|
||||
endif
|
||||
|
||||
EXTRA_DIST = autogen.sh
|
||||
61
crypto/secp256k1/secp256k1/README.md
Normal file
61
crypto/secp256k1/secp256k1/README.md
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
libsecp256k1
|
||||
============
|
||||
|
||||
[](https://travis-ci.org/bitcoin/secp256k1)
|
||||
|
||||
Optimized C library for EC operations on curve secp256k1.
|
||||
|
||||
This library is a work in progress and is being used to research best practices. Use at your own risk.
|
||||
|
||||
Features:
|
||||
* secp256k1 ECDSA signing/verification and key generation.
|
||||
* Adding/multiplying private/public keys.
|
||||
* Serialization/parsing of private keys, public keys, signatures.
|
||||
* Constant time, constant memory access signing and pubkey generation.
|
||||
* Derandomized DSA (via RFC6979 or with a caller provided function.)
|
||||
* Very efficient implementation.
|
||||
|
||||
Implementation details
|
||||
----------------------
|
||||
|
||||
* General
|
||||
* No runtime heap allocation.
|
||||
* Extensive testing infrastructure.
|
||||
* Structured to facilitate review and analysis.
|
||||
* Intended to be portable to any system with a C89 compiler and uint64_t support.
|
||||
* Expose only higher level interfaces to minimize the API surface and improve application security. ("Be difficult to use insecurely.")
|
||||
* Field operations
|
||||
* Optimized implementation of arithmetic modulo the curve's field size (2^256 - 0x1000003D1).
|
||||
* Using 5 52-bit limbs (including hand-optimized assembly for x86_64, by Diederik Huys).
|
||||
* Using 10 26-bit limbs.
|
||||
* Field inverses and square roots using a sliding window over blocks of 1s (by Peter Dettman).
|
||||
* Scalar operations
|
||||
* Optimized implementation without data-dependent branches of arithmetic modulo the curve's order.
|
||||
* Using 4 64-bit limbs (relying on __int128 support in the compiler).
|
||||
* Using 8 32-bit limbs.
|
||||
* Group operations
|
||||
* Point addition formula specifically simplified for the curve equation (y^2 = x^3 + 7).
|
||||
* Use addition between points in Jacobian and affine coordinates where possible.
|
||||
* Use a unified addition/doubling formula where necessary to avoid data-dependent branches.
|
||||
* Point/x comparison without a field inversion by comparison in the Jacobian coordinate space.
|
||||
* Point multiplication for verification (a*P + b*G).
|
||||
* Use wNAF notation for point multiplicands.
|
||||
* Use a much larger window for multiples of G, using precomputed multiples.
|
||||
* Use Shamir's trick to do the multiplication with the public key and the generator simultaneously.
|
||||
* Optionally (off by default) use secp256k1's efficiently-computable endomorphism to split the P multiplicand into 2 half-sized ones.
|
||||
* Point multiplication for signing
|
||||
* Use a precomputed table of multiples of powers of 16 multiplied with the generator, so general multiplication becomes a series of additions.
|
||||
* Access the table with branch-free conditional moves so memory access is uniform.
|
||||
* No data-dependent branches
|
||||
* 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.
|
||||
|
||||
Build steps
|
||||
-----------
|
||||
|
||||
libsecp256k1 is built using autotools:
|
||||
|
||||
$ ./autogen.sh
|
||||
$ ./configure
|
||||
$ make
|
||||
$ ./tests
|
||||
$ sudo make install # optional
|
||||
3
crypto/secp256k1/secp256k1/autogen.sh
Executable file
3
crypto/secp256k1/secp256k1/autogen.sh
Executable file
|
|
@ -0,0 +1,3 @@
|
|||
#!/bin/sh
|
||||
set -e
|
||||
autoreconf -if --warnings=all
|
||||
61
crypto/secp256k1/secp256k1/build-aux/m4/bitcoin_secp.m4
Normal file
61
crypto/secp256k1/secp256k1/build-aux/m4/bitcoin_secp.m4
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
dnl libsecp25k1 helper checks
|
||||
AC_DEFUN([SECP_INT128_CHECK],[
|
||||
has_int128=$ac_cv_type___int128
|
||||
])
|
||||
|
||||
dnl
|
||||
AC_DEFUN([SECP_64BIT_ASM_CHECK],[
|
||||
AC_MSG_CHECKING(for x86_64 assembly availability)
|
||||
AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
|
||||
#include <stdint.h>]],[[
|
||||
uint64_t a = 11, tmp;
|
||||
__asm__ __volatile__("movq $0x100000000,%1; mulq %%rsi" : "+a"(a) : "S"(tmp) : "cc", "%rdx");
|
||||
]])],[has_64bit_asm=yes],[has_64bit_asm=no])
|
||||
AC_MSG_RESULT([$has_64bit_asm])
|
||||
])
|
||||
|
||||
dnl
|
||||
AC_DEFUN([SECP_OPENSSL_CHECK],[
|
||||
if test x"$use_pkgconfig" = x"yes"; then
|
||||
: #NOP
|
||||
m4_ifdef([PKG_CHECK_MODULES],[
|
||||
PKG_CHECK_MODULES([CRYPTO], [libcrypto], [has_libcrypto=yes],[has_libcrypto=no])
|
||||
if test x"$has_libcrypto" = x"yes"; then
|
||||
TEMP_LIBS="$LIBS"
|
||||
LIBS="$LIBS $CRYPTO_LIBS"
|
||||
AC_CHECK_LIB(crypto, main,[AC_DEFINE(HAVE_LIBCRYPTO,1,[Define this symbol if libcrypto is installed])],[has_libcrypto=no])
|
||||
LIBS="$TEMP_LIBS"
|
||||
fi
|
||||
])
|
||||
else
|
||||
AC_CHECK_HEADER(openssl/crypto.h,[AC_CHECK_LIB(crypto, main,[has_libcrypto=yes; CRYPTO_LIBS=-lcrypto; AC_DEFINE(HAVE_LIBCRYPTO,1,[Define this symbol if libcrypto is installed])]
|
||||
)])
|
||||
LIBS=
|
||||
fi
|
||||
if test x"$has_libcrypto" = x"yes" && test x"$has_openssl_ec" = x; then
|
||||
AC_MSG_CHECKING(for EC functions in libcrypto)
|
||||
AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
|
||||
#include <openssl/ec.h>
|
||||
#include <openssl/ecdsa.h>
|
||||
#include <openssl/obj_mac.h>]],[[
|
||||
EC_KEY *eckey = EC_KEY_new_by_curve_name(NID_secp256k1);
|
||||
ECDSA_sign(0, NULL, 0, NULL, NULL, eckey);
|
||||
ECDSA_verify(0, NULL, 0, NULL, 0, eckey);
|
||||
EC_KEY_free(eckey);
|
||||
]])],[has_openssl_ec=yes],[has_openssl_ec=no])
|
||||
AC_MSG_RESULT([$has_openssl_ec])
|
||||
fi
|
||||
])
|
||||
|
||||
dnl
|
||||
AC_DEFUN([SECP_GMP_CHECK],[
|
||||
if test x"$has_gmp" != x"yes"; then
|
||||
CPPFLAGS_TEMP="$CPPFLAGS"
|
||||
CPPFLAGS="$GMP_CPPFLAGS $CPPFLAGS"
|
||||
LIBS_TEMP="$LIBS"
|
||||
LIBS="$GMP_LIBS $LIBS"
|
||||
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])])])
|
||||
CPPFLAGS="$CPPFLAGS_TEMP"
|
||||
LIBS="$LIBS_TEMP"
|
||||
fi
|
||||
])
|
||||
|
|
@ -1,9 +0,0 @@
|
|||
CC=cc
|
||||
YASM=yasm
|
||||
CFLAGS_EXTRA=-DUSE_FIELD_5X52 -DUSE_FIELD_5X52_ASM -DUSE_NUM_GMP -DUSE_FIELD_INV_NUM
|
||||
CFLAGS_TEST_EXTRA=-DENABLE_OPENSSL_TESTS
|
||||
LDFLAGS_EXTRA=-lgmp
|
||||
LDFLAGS_TEST_EXTRA=-lcrypto
|
||||
USE_ASM=1
|
||||
HAVE_LIMB=52
|
||||
OPTLEVEL=O2
|
||||
175
crypto/secp256k1/secp256k1/configure
vendored
175
crypto/secp256k1/secp256k1/configure
vendored
|
|
@ -1,175 +0,0 @@
|
|||
#!/bin/sh
|
||||
|
||||
if test -f config.mk; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if test -z "$CC"; then
|
||||
CC=cc
|
||||
fi
|
||||
|
||||
if test -z "$YASM"; then
|
||||
YASM=yasm
|
||||
fi
|
||||
|
||||
# test yasm
|
||||
$YASM -f elf64 -o /tmp/secp256k1-$$.o - <<EOF
|
||||
BITS 64
|
||||
GLOBAL testyasm
|
||||
ALIGN 32
|
||||
testyasm:
|
||||
xor r9,r9
|
||||
EOF
|
||||
if [ "$?" = 0 ]; then
|
||||
$CC $CFLAGS -std=c99 -x c -c - -o /tmp/secp256k1-$$-2.o 2>/dev/null <<EOF
|
||||
void __attribute__ ((sysv_abi)) testyasm(void);
|
||||
int main() {
|
||||
testyasm();
|
||||
return 0;
|
||||
}
|
||||
EOF
|
||||
$CC $CFLAGS -std=c99 /tmp/secp256k1-$$-2.o /tmp/secp256k1-$$.o -o /dev/null 2>/dev/null
|
||||
if [ "$?" = 0 ]; then
|
||||
HAVE_YASM=1
|
||||
fi
|
||||
rm -rf /tmp/secp256k1-$$-2.o /tmp/secp256k1-$$.o
|
||||
fi
|
||||
|
||||
# test openssl
|
||||
HAVE_OPENSSL=0
|
||||
$CC $CFLAGS -std=c99 -x c - -o /dev/null -lcrypto 2>/dev/null <<EOF
|
||||
#include <openssl/bn.h>
|
||||
int main() {
|
||||
BN_CTX *ctx = BN_CTX_new();
|
||||
BN_CTX_free(ctx);
|
||||
return 0;
|
||||
}
|
||||
EOF
|
||||
if [ "$?" = 0 ]; then
|
||||
HAVE_OPENSSL=1
|
||||
fi
|
||||
|
||||
# test openssl/EC
|
||||
HAVE_OPENSSL_EC=0
|
||||
if [ "$HAVE_OPENSSL" = "1" ]; then
|
||||
$CC $CFLAGS -std=c99 -x c - -o /dev/null -lcrypto 2>/dev/null <<EOF
|
||||
#include <openssl/ec.h>
|
||||
#include <openssl/ecdsa.h>
|
||||
#include <openssl/obj_mac.h>
|
||||
int main() {
|
||||
EC_KEY *eckey = EC_KEY_new_by_curve_name(NID_secp256k1);
|
||||
ECDSA_sign(0, NULL, 0, NULL, NULL, eckey);
|
||||
ECDSA_verify(0, NULL, 0, NULL, 0, eckey);
|
||||
EC_KEY_free(eckey);
|
||||
return 0;
|
||||
}
|
||||
EOF
|
||||
if [ "$?" = 0 ]; then
|
||||
HAVE_OPENSSL_EC=1
|
||||
fi
|
||||
fi
|
||||
|
||||
# test gmp
|
||||
HAVE_GMP=0
|
||||
$CC $CFLAGS -std=c99 -x c - -o /dev/null -lgmp 2>/dev/null <<EOF
|
||||
#include <gmp.h>
|
||||
int main() {
|
||||
mpz_t n;
|
||||
mpz_init(n);
|
||||
mpz_clear(n);
|
||||
return 0;
|
||||
}
|
||||
EOF
|
||||
if [ "$?" = 0 ]; then
|
||||
HAVE_GMP=1
|
||||
fi
|
||||
|
||||
# test __int128
|
||||
HAVE_INT128=0
|
||||
$CC $CFLAGS -std=c99 -x c - -o /dev/null 2>/dev/null <<EOF
|
||||
#include <stdint.h>
|
||||
int main() {
|
||||
__int128 x = 0;
|
||||
return 0;
|
||||
}
|
||||
EOF
|
||||
if [ "$?" = 0 ]; then
|
||||
HAVE_INT128=1
|
||||
fi
|
||||
|
||||
#default limb size
|
||||
HAVE_LIMB=52
|
||||
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
--no-yasm)
|
||||
HAVE_YASM=0
|
||||
;;
|
||||
--no-gmp)
|
||||
HAVE_GMP=0
|
||||
;;
|
||||
--no-openssl)
|
||||
HAVE_OPENSSL=0
|
||||
;;
|
||||
--use-5x64)
|
||||
HAVE_LIMB=64
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
LINK_OPENSSL=0
|
||||
LINK_GMP=0
|
||||
USE_ASM=0
|
||||
|
||||
# select field implementation
|
||||
if [ "$HAVE_YASM" = "1" ]; then
|
||||
CFLAGS_FIELD="-DUSE_FIELD_5X$HAVE_LIMB -DUSE_FIELD_5X${HAVE_LIMB}_ASM"
|
||||
USE_ASM=1
|
||||
elif [ "$HAVE_INT128" = "1" ]; then
|
||||
CFLAGS_FIELD="-DUSE_FIELD_5X$HAVE_LIMB -DUSE_FIELD_5X${HAVE_LIMB}_INT128"
|
||||
elif [ "$HAVE_GMP" = "1" ]; then
|
||||
CFLAGS_FIELD="-DUSE_FIELD_GMP"
|
||||
LINK_GMP=1
|
||||
else
|
||||
CFLAGS_FIELD="-DUSE_FIELD_10X26"
|
||||
fi
|
||||
|
||||
# select num implementation
|
||||
if [ "$HAVE_GMP" = "1" ]; then
|
||||
CFLAGS_NUM="-DUSE_NUM_GMP -DUSE_FIELD_INV_NUM"
|
||||
LINK_GMP=1
|
||||
elif [ "$HAVE_OPENSSL" = "1" ]; then
|
||||
CFLAGS_NUM="-DUSE_NUM_OPENSSL -DUSE_FIELD_INV_BUILTIN"
|
||||
LINK_OPENSSL=1
|
||||
else
|
||||
echo "No usable num implementation found" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
CFLAGS_EXTRA="$CFLAGS_FIELD $CFLAGS_NUM"
|
||||
LDFLAGS_EXTRA=""
|
||||
if [ "$LINK_GMP" = "1" ]; then
|
||||
LDFLAGS_EXTRA="-lgmp"
|
||||
fi
|
||||
if [ "$LINK_OPENSSL" = "1" ]; then
|
||||
LDFLAGS_EXTRA="-lcrypto"
|
||||
else
|
||||
if [ "$HAVE_OPENSSL_EC" = "1" ]; then
|
||||
LDFLAGS_TEST_EXTRA="-lcrypto"
|
||||
fi
|
||||
fi
|
||||
|
||||
CFLAGS_TEST_EXTRA=""
|
||||
if [ "$HAVE_OPENSSL_EC" = "1" ]; then
|
||||
CFLAGS_TEST_EXTRA="-DENABLE_OPENSSL_TESTS"
|
||||
fi
|
||||
|
||||
echo "CC=$CC" > config.mk
|
||||
echo "YASM=$YASM" >>config.mk
|
||||
echo "CFLAGS_EXTRA=$CFLAGS_EXTRA" >> config.mk
|
||||
echo "CFLAGS_TEST_EXTRA=$CFLAGS_TEST_EXTRA" >> config.mk
|
||||
echo "LDFLAGS_EXTRA=$LDFLAGS_EXTRA" >> config.mk
|
||||
echo "LDFLAGS_TEST_EXTRA=$LDFLAGS_TEST_EXTRA" >> config.mk
|
||||
echo "USE_ASM=$USE_ASM" >>config.mk
|
||||
echo "HAVE_LIMB=$HAVE_LIMB" >>config.mk
|
||||
echo "OPTLEVEL=O2" >>config.mk
|
||||
330
crypto/secp256k1/secp256k1/configure.ac
Normal file
330
crypto/secp256k1/secp256k1/configure.ac
Normal file
|
|
@ -0,0 +1,330 @@
|
|||
AC_PREREQ([2.60])
|
||||
AC_INIT([libsecp256k1],[0.1])
|
||||
AC_CONFIG_AUX_DIR([build-aux])
|
||||
AC_CONFIG_MACRO_DIR([build-aux/m4])
|
||||
AC_CANONICAL_HOST
|
||||
AH_TOP([#ifndef LIBSECP256K1_CONFIG_H])
|
||||
AH_TOP([#define LIBSECP256K1_CONFIG_H])
|
||||
AH_BOTTOM([#endif /*LIBSECP256K1_CONFIG_H*/])
|
||||
AM_INIT_AUTOMAKE([foreign subdir-objects])
|
||||
LT_INIT
|
||||
|
||||
dnl make the compilation flags quiet unless V=1 is used
|
||||
m4_ifdef([AM_SILENT_RULES], [AM_SILENT_RULES([yes])])
|
||||
|
||||
PKG_PROG_PKG_CONFIG
|
||||
|
||||
AC_PATH_TOOL(AR, ar)
|
||||
AC_PATH_TOOL(RANLIB, ranlib)
|
||||
AC_PATH_TOOL(STRIP, strip)
|
||||
|
||||
if test "x$CFLAGS" = "x"; then
|
||||
CFLAGS="-O3 -g"
|
||||
fi
|
||||
|
||||
AC_PROG_CC_C89
|
||||
if test x"$ac_cv_prog_cc_c89" = x"no"; then
|
||||
AC_MSG_ERROR([c89 compiler support required])
|
||||
fi
|
||||
|
||||
case $host in
|
||||
*mingw*)
|
||||
use_pkgconfig=no
|
||||
;;
|
||||
*)
|
||||
use_pkgconfig=yes
|
||||
;;
|
||||
esac
|
||||
|
||||
case $host_os in
|
||||
*darwin*)
|
||||
if test x$cross_compiling != xyes; then
|
||||
AC_PATH_PROG([BREW],brew,)
|
||||
if test x$BREW != x; then
|
||||
dnl These Homebrew packages may be keg-only, meaning that they won't be found
|
||||
dnl in expected paths because they may conflict with system files. Ask
|
||||
dnl Homebrew where each one is located, then adjust paths accordingly.
|
||||
|
||||
openssl_prefix=`$BREW --prefix openssl 2>/dev/null`
|
||||
gmp_prefix=`$BREW --prefix gmp 2>/dev/null`
|
||||
if test x$openssl_prefix != x; then
|
||||
PKG_CONFIG_PATH="$openssl_prefix/lib/pkgconfig:$PKG_CONFIG_PATH"
|
||||
export PKG_CONFIG_PATH
|
||||
fi
|
||||
if test x$gmp_prefix != x; then
|
||||
GMP_CPPFLAGS="-I$gmp_prefix/include"
|
||||
GMP_LIBS="-L$gmp_prefix/lib"
|
||||
fi
|
||||
else
|
||||
AC_PATH_PROG([PORT],port,)
|
||||
dnl if homebrew isn't installed and macports is, add the macports default paths
|
||||
dnl as a last resort.
|
||||
if test x$PORT != x; then
|
||||
CPPFLAGS="$CPPFLAGS -isystem /opt/local/include"
|
||||
LDFLAGS="$LDFLAGS -L/opt/local/lib"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
|
||||
CFLAGS="$CFLAGS -W"
|
||||
|
||||
warn_CFLAGS="-std=c89 -pedantic -Wall -Wextra -Wcast-align -Wnested-externs -Wshadow -Wstrict-prototypes -Wno-unused-function -Wno-long-long -Wno-overlength-strings"
|
||||
saved_CFLAGS="$CFLAGS"
|
||||
CFLAGS="$CFLAGS $warn_CFLAGS"
|
||||
AC_MSG_CHECKING([if ${CC} supports ${warn_CFLAGS}])
|
||||
AC_COMPILE_IFELSE([AC_LANG_SOURCE([[char foo;]])],
|
||||
[ AC_MSG_RESULT([yes]) ],
|
||||
[ AC_MSG_RESULT([no])
|
||||
CFLAGS="$saved_CFLAGS"
|
||||
])
|
||||
|
||||
|
||||
AC_ARG_ENABLE(benchmark,
|
||||
AS_HELP_STRING([--enable-benchmark],[compile benchmark (default is no)]),
|
||||
[use_benchmark=$enableval],
|
||||
[use_benchmark=no])
|
||||
|
||||
AC_ARG_ENABLE(tests,
|
||||
AS_HELP_STRING([--enable-tests],[compile tests (default is yes)]),
|
||||
[use_tests=$enableval],
|
||||
[use_tests=yes])
|
||||
|
||||
AC_ARG_ENABLE(endomorphism,
|
||||
AS_HELP_STRING([--enable-endomorphism],[enable endomorphism (default is no)]),
|
||||
[use_endomorphism=$enableval],
|
||||
[use_endomorphism=no])
|
||||
|
||||
AC_ARG_WITH([field], [AS_HELP_STRING([--with-field=64bit|32bit|auto],
|
||||
[Specify Field Implementation. Default is auto])],[req_field=$withval], [req_field=auto])
|
||||
|
||||
AC_ARG_WITH([bignum], [AS_HELP_STRING([--with-bignum=gmp|no|auto],
|
||||
[Specify Bignum Implementation. Default is auto])],[req_bignum=$withval], [req_bignum=auto])
|
||||
|
||||
AC_ARG_WITH([scalar], [AS_HELP_STRING([--with-scalar=64bit|32bit|auto],
|
||||
[Specify scalar implementation. Default is auto])],[req_scalar=$withval], [req_scalar=auto])
|
||||
|
||||
AC_ARG_WITH([asm], [AS_HELP_STRING([--with-asm=x86_64|no|auto]
|
||||
[Specify assembly optimizations to use. Default is auto])],[req_asm=$withval], [req_asm=auto])
|
||||
|
||||
AC_CHECK_TYPES([__int128])
|
||||
|
||||
AC_MSG_CHECKING([for __builtin_expect])
|
||||
AC_COMPILE_IFELSE([AC_LANG_SOURCE([[void myfunc() {__builtin_expect(0,0);}]])],
|
||||
[ AC_MSG_RESULT([yes]);AC_DEFINE(HAVE_BUILTIN_EXPECT,1,[Define this symbol if __builtin_expect is available]) ],
|
||||
[ AC_MSG_RESULT([no])
|
||||
])
|
||||
|
||||
if test x"$req_asm" = x"auto"; then
|
||||
SECP_64BIT_ASM_CHECK
|
||||
if test x"$has_64bit_asm" = x"yes"; then
|
||||
set_asm=x86_64
|
||||
fi
|
||||
if test x"$set_asm" = x; then
|
||||
set_asm=no
|
||||
fi
|
||||
else
|
||||
set_asm=$req_asm
|
||||
case $set_asm in
|
||||
x86_64)
|
||||
SECP_64BIT_ASM_CHECK
|
||||
if test x"$has_64bit_asm" != x"yes"; then
|
||||
AC_MSG_ERROR([x86_64 assembly optimization requested but not available])
|
||||
fi
|
||||
;;
|
||||
no)
|
||||
;;
|
||||
*)
|
||||
AC_MSG_ERROR([invalid assembly optimization selection])
|
||||
;;
|
||||
esac
|
||||
fi
|
||||
|
||||
if test x"$req_field" = x"auto"; then
|
||||
if test x"set_asm" = x"x86_64"; then
|
||||
set_field=64bit
|
||||
fi
|
||||
if test x"$set_field" = x; then
|
||||
SECP_INT128_CHECK
|
||||
if test x"$has_int128" = x"yes"; then
|
||||
set_field=64bit
|
||||
fi
|
||||
fi
|
||||
if test x"$set_field" = x; then
|
||||
set_field=32bit
|
||||
fi
|
||||
else
|
||||
set_field=$req_field
|
||||
case $set_field in
|
||||
64bit)
|
||||
if test x"$set_asm" != x"x86_64"; then
|
||||
SECP_INT128_CHECK
|
||||
if test x"$has_int128" != x"yes"; then
|
||||
AC_MSG_ERROR([64bit field explicitly requested but neither __int128 support or x86_64 assembly available])
|
||||
fi
|
||||
fi
|
||||
;;
|
||||
32bit)
|
||||
;;
|
||||
*)
|
||||
AC_MSG_ERROR([invalid field implementation selection])
|
||||
;;
|
||||
esac
|
||||
fi
|
||||
|
||||
if test x"$req_scalar" = x"auto"; then
|
||||
SECP_INT128_CHECK
|
||||
if test x"$has_int128" = x"yes"; then
|
||||
set_scalar=64bit
|
||||
fi
|
||||
if test x"$set_scalar" = x; then
|
||||
set_scalar=32bit
|
||||
fi
|
||||
else
|
||||
set_scalar=$req_scalar
|
||||
case $set_scalar in
|
||||
64bit)
|
||||
SECP_INT128_CHECK
|
||||
if test x"$has_int128" != x"yes"; then
|
||||
AC_MSG_ERROR([64bit scalar explicitly requested but __int128 support not available])
|
||||
fi
|
||||
;;
|
||||
32bit)
|
||||
;;
|
||||
*)
|
||||
AC_MSG_ERROR([invalid scalar implementation selected])
|
||||
;;
|
||||
esac
|
||||
fi
|
||||
|
||||
if test x"$req_bignum" = x"auto"; then
|
||||
SECP_GMP_CHECK
|
||||
if test x"$has_gmp" = x"yes"; then
|
||||
set_bignum=gmp
|
||||
fi
|
||||
|
||||
if test x"$set_bignum" = x; then
|
||||
set_bignum=no
|
||||
fi
|
||||
else
|
||||
set_bignum=$req_bignum
|
||||
case $set_bignum in
|
||||
gmp)
|
||||
SECP_GMP_CHECK
|
||||
if test x"$has_gmp" != x"yes"; then
|
||||
AC_MSG_ERROR([gmp bignum explicitly requested but libgmp not available])
|
||||
fi
|
||||
;;
|
||||
no)
|
||||
;;
|
||||
*)
|
||||
AC_MSG_ERROR([invalid bignum implementation selection])
|
||||
;;
|
||||
esac
|
||||
fi
|
||||
|
||||
# select assembly optimization
|
||||
case $set_asm in
|
||||
x86_64)
|
||||
AC_DEFINE(USE_ASM_X86_64, 1, [Define this symbol to enable x86_64 assembly optimizations])
|
||||
;;
|
||||
no)
|
||||
;;
|
||||
*)
|
||||
AC_MSG_ERROR([invalid assembly optimizations])
|
||||
;;
|
||||
esac
|
||||
|
||||
# select field implementation
|
||||
case $set_field in
|
||||
64bit)
|
||||
AC_DEFINE(USE_FIELD_5X52, 1, [Define this symbol to use the FIELD_5X52 implementation])
|
||||
;;
|
||||
32bit)
|
||||
AC_DEFINE(USE_FIELD_10X26, 1, [Define this symbol to use the FIELD_10X26 implementation])
|
||||
;;
|
||||
*)
|
||||
AC_MSG_ERROR([invalid field implementation])
|
||||
;;
|
||||
esac
|
||||
|
||||
# select bignum implementation
|
||||
case $set_bignum in
|
||||
gmp)
|
||||
AC_DEFINE(HAVE_LIBGMP, 1, [Define this symbol if libgmp is installed])
|
||||
AC_DEFINE(USE_NUM_GMP, 1, [Define this symbol to use the gmp implementation for num])
|
||||
AC_DEFINE(USE_FIELD_INV_NUM, 1, [Define this symbol to use the num-based field inverse implementation])
|
||||
AC_DEFINE(USE_SCALAR_INV_NUM, 1, [Define this symbol to use the num-based scalar inverse implementation])
|
||||
;;
|
||||
no)
|
||||
AC_DEFINE(USE_NUM_NONE, 1, [Define this symbol to use no num implementation])
|
||||
AC_DEFINE(USE_FIELD_INV_BUILTIN, 1, [Define this symbol to use the native field inverse implementation])
|
||||
AC_DEFINE(USE_SCALAR_INV_BUILTIN, 1, [Define this symbol to use the native scalar inverse implementation])
|
||||
;;
|
||||
*)
|
||||
AC_MSG_ERROR([invalid bignum implementation])
|
||||
;;
|
||||
esac
|
||||
|
||||
#select scalar implementation
|
||||
case $set_scalar in
|
||||
64bit)
|
||||
AC_DEFINE(USE_SCALAR_4X64, 1, [Define this symbol to use the 4x64 scalar implementation])
|
||||
;;
|
||||
32bit)
|
||||
AC_DEFINE(USE_SCALAR_8X32, 1, [Define this symbol to use the 8x32 scalar implementation])
|
||||
;;
|
||||
*)
|
||||
AC_MSG_ERROR([invalid scalar implementation])
|
||||
;;
|
||||
esac
|
||||
|
||||
if test x"$use_tests" = x"yes"; then
|
||||
SECP_OPENSSL_CHECK
|
||||
if test x"$has_openssl_ec" = x"yes"; then
|
||||
AC_DEFINE(ENABLE_OPENSSL_TESTS, 1, [Define this symbol if OpenSSL EC functions are available])
|
||||
SECP_TEST_INCLUDES="$SSL_CFLAGS $CRYPTO_CFLAGS"
|
||||
SECP_TEST_LIBS="$CRYPTO_LIBS"
|
||||
|
||||
case $host in
|
||||
*mingw*)
|
||||
SECP_TEST_LIBS="$SECP_TEST_LIBS -lgdi32"
|
||||
;;
|
||||
esac
|
||||
|
||||
fi
|
||||
fi
|
||||
|
||||
if test x"$set_bignum" = x"gmp"; then
|
||||
SECP_LIBS="$SECP_LIBS $GMP_LIBS"
|
||||
SECP_INCLUDES="$SECP_INCLUDES $GMP_CPPFLAGS"
|
||||
fi
|
||||
|
||||
if test x"$use_endomorphism" = x"yes"; then
|
||||
AC_DEFINE(USE_ENDOMORPHISM, 1, [Define this symbol to use endomorphism optimization])
|
||||
fi
|
||||
|
||||
AC_C_BIGENDIAN()
|
||||
|
||||
AC_MSG_NOTICE([Using assembly optimizations: $set_asm])
|
||||
AC_MSG_NOTICE([Using field implementation: $set_field])
|
||||
AC_MSG_NOTICE([Using bignum implementation: $set_bignum])
|
||||
AC_MSG_NOTICE([Using scalar implementation: $set_scalar])
|
||||
AC_MSG_NOTICE([Using endomorphism optimizations: $use_endomorphism])
|
||||
|
||||
AC_CONFIG_HEADERS([src/libsecp256k1-config.h])
|
||||
AC_CONFIG_FILES([Makefile libsecp256k1.pc])
|
||||
AC_SUBST(SECP_INCLUDES)
|
||||
AC_SUBST(SECP_LIBS)
|
||||
AC_SUBST(SECP_TEST_LIBS)
|
||||
AC_SUBST(SECP_TEST_INCLUDES)
|
||||
AM_CONDITIONAL([USE_TESTS], [test x"$use_tests" != x"no"])
|
||||
AM_CONDITIONAL([USE_BENCHMARK], [test x"$use_benchmark" = x"yes"])
|
||||
|
||||
dnl make sure nothing new is exported so that we don't break the cache
|
||||
PKGCONFIG_PATH_TEMP="$PKG_CONFIG_PATH"
|
||||
unset PKG_CONFIG_PATH
|
||||
PKG_CONFIG_PATH="$PKGCONFIG_PATH_TEMP"
|
||||
|
||||
AC_OUTPUT
|
||||
|
|
@ -1,16 +1,56 @@
|
|||
#ifndef _SECP256K1_
|
||||
#define _SECP256K1_
|
||||
# define _SECP256K1_
|
||||
|
||||
#ifdef __cplusplus
|
||||
# ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
# endif
|
||||
|
||||
# if !defined(SECP256K1_GNUC_PREREQ)
|
||||
# if defined(__GNUC__)&&defined(__GNUC_MINOR__)
|
||||
# define SECP256K1_GNUC_PREREQ(_maj,_min) \
|
||||
((__GNUC__<<16)+__GNUC_MINOR__>=((_maj)<<16)+(_min))
|
||||
# else
|
||||
# define SECP256K1_GNUC_PREREQ(_maj,_min) 0
|
||||
# endif
|
||||
# endif
|
||||
|
||||
# if (!defined(__STDC_VERSION__) || (__STDC_VERSION__ < 199901L) )
|
||||
# if SECP256K1_GNUC_PREREQ(2,7)
|
||||
# define SECP256K1_INLINE __inline__
|
||||
# elif (defined(_MSC_VER))
|
||||
# define SECP256K1_INLINE __inline
|
||||
# else
|
||||
# define SECP256K1_INLINE
|
||||
# endif
|
||||
# else
|
||||
# define SECP256K1_INLINE inline
|
||||
# endif
|
||||
|
||||
/**Warning attributes
|
||||
* NONNULL is not used if SECP256K1_BUILD is set to avoid the compiler optimizing out
|
||||
* some paranoid null checks. */
|
||||
# if defined(__GNUC__) && SECP256K1_GNUC_PREREQ(3, 4)
|
||||
# define SECP256K1_WARN_UNUSED_RESULT __attribute__ ((__warn_unused_result__))
|
||||
# else
|
||||
# define SECP256K1_WARN_UNUSED_RESULT
|
||||
# endif
|
||||
# if !defined(SECP256K1_BUILD) && defined(__GNUC__) && SECP256K1_GNUC_PREREQ(3, 4)
|
||||
# define SECP256K1_ARG_NONNULL(_x) __attribute__ ((__nonnull__(_x)))
|
||||
# else
|
||||
# define SECP256K1_ARG_NONNULL(_x)
|
||||
# endif
|
||||
|
||||
|
||||
/** Flags to pass to secp256k1_start. */
|
||||
# define SECP256K1_START_VERIFY (1 << 0)
|
||||
# define SECP256K1_START_SIGN (1 << 1)
|
||||
|
||||
/** Initialize the library. This may take some time (10-100 ms).
|
||||
* You need to call this before calling any other function.
|
||||
* It cannot run in parallel with any other functions, but once
|
||||
* secp256k1_start() returns, all other functions are thread-safe.
|
||||
*/
|
||||
void secp256k1_start(void);
|
||||
void secp256k1_start(unsigned int flags);
|
||||
|
||||
/** Free all memory associated with this library. After this, no
|
||||
* functions can be called anymore, except secp256k1_start()
|
||||
|
|
@ -22,100 +62,234 @@ void secp256k1_stop(void);
|
|||
* 0: incorrect signature
|
||||
* -1: invalid public key
|
||||
* -2: invalid signature
|
||||
* In: msg32: the 32-byte message hash being verified (cannot be NULL)
|
||||
* sig: the signature being verified (cannot be NULL)
|
||||
* siglen: the length of the signature
|
||||
* pubkey: the public key to verify with (cannot be NULL)
|
||||
* pubkeylen: the length of pubkey
|
||||
* Requires starting using SECP256K1_START_VERIFY.
|
||||
*/
|
||||
int secp256k1_ecdsa_verify(const unsigned char *msg, int msglen,
|
||||
const unsigned char *sig, int siglen,
|
||||
const unsigned char *pubkey, int pubkeylen);
|
||||
SECP256K1_WARN_UNUSED_RESULT int secp256k1_ecdsa_verify(
|
||||
const unsigned char *msg32,
|
||||
const unsigned char *sig,
|
||||
int siglen,
|
||||
const unsigned char *pubkey,
|
||||
int pubkeylen
|
||||
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(4);
|
||||
|
||||
/** A pointer to a function to deterministically generate a nonce.
|
||||
* Returns: 1 if a nonce was successfully generated. 0 will cause signing to fail.
|
||||
* In: msg32: the 32-byte message hash being verified (will not be NULL)
|
||||
* key32: pointer to a 32-byte secret key (will not be NULL)
|
||||
* attempt: how many iterations we have tried to find a nonce.
|
||||
* This will almost always be 0, but different attempt values
|
||||
* are required to result in a different nonce.
|
||||
* data: Arbitrary data pointer that is passed through.
|
||||
* Out: nonce32: pointer to a 32-byte array to be filled by the function.
|
||||
* Except for test cases, this function should compute some cryptographic hash of
|
||||
* the message, the key and the attempt.
|
||||
*/
|
||||
typedef int (*secp256k1_nonce_function_t)(
|
||||
unsigned char *nonce32,
|
||||
const unsigned char *msg32,
|
||||
const unsigned char *key32,
|
||||
unsigned int attempt,
|
||||
const void *data
|
||||
);
|
||||
|
||||
/** An implementation of RFC6979 (using HMAC-SHA256) as nonce generation function.
|
||||
* If a data pointer is passed, it is assumed to be a pointer to 32 bytes of
|
||||
* extra entropy.
|
||||
*/
|
||||
extern const secp256k1_nonce_function_t secp256k1_nonce_function_rfc6979;
|
||||
|
||||
/** A default safe nonce generation function (currently equal to secp256k1_nonce_function_rfc6979). */
|
||||
extern const secp256k1_nonce_function_t secp256k1_nonce_function_default;
|
||||
|
||||
|
||||
/** Create an ECDSA signature.
|
||||
* Returns: 1: signature created
|
||||
* 0: nonce invalid, try another one
|
||||
* In: msg: the message being signed
|
||||
* msglen: the length of the message being signed
|
||||
* seckey: pointer to a 32-byte secret key (assumed to be valid)
|
||||
* nonce: pointer to a 32-byte nonce (generated with a cryptographic PRNG)
|
||||
* Out: sig: pointer to a 72-byte array where the signature will be placed.
|
||||
* siglen: pointer to an int, which will be updated to the signature length (<=72).
|
||||
* 0: the nonce generation function failed, the private key was invalid, or there is not
|
||||
* enough space in the signature (as indicated by siglen).
|
||||
* In: msg32: the 32-byte message hash being signed (cannot be NULL)
|
||||
* seckey: pointer to a 32-byte secret key (cannot be NULL)
|
||||
* noncefp:pointer to a nonce generation function. If NULL, secp256k1_nonce_function_default is used
|
||||
* ndata: pointer to arbitrary data used by the nonce generation function (can be NULL)
|
||||
* Out: sig: pointer to an array where the signature will be placed (cannot be NULL)
|
||||
* In/Out: siglen: pointer to an int with the length of sig, which will be updated
|
||||
* to contain the actual signature length (<=72). If 0 is returned, this will be
|
||||
* set to zero.
|
||||
* Requires starting using SECP256K1_START_SIGN.
|
||||
*
|
||||
* The sig always has an s value in the lower half of the range (From 0x1
|
||||
* to 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0,
|
||||
* inclusive), unlike many other implementations.
|
||||
* With ECDSA a third-party can can forge a second distinct signature
|
||||
* of the same message given a single initial signature without knowing
|
||||
* the key by setting s to its additive inverse mod-order, 'flipping' the
|
||||
* sign of the random point R which is not included in the signature.
|
||||
* Since the forgery is of the same message this isn't universally
|
||||
* problematic, but in systems where message malleability or uniqueness
|
||||
* of signatures is important this can cause issues. This forgery can be
|
||||
* blocked by all verifiers forcing signers to use a canonical form. The
|
||||
* lower-S form reduces the size of signatures slightly on average when
|
||||
* variable length encodings (such as DER) are used and is cheap to
|
||||
* verify, making it a good choice. Security of always using lower-S is
|
||||
* assured because anyone can trivially modify a signature after the
|
||||
* fact to enforce this property. Adjusting it inside the signing
|
||||
* function avoids the need to re-serialize or have curve specific
|
||||
* constants outside of the library. By always using a canonical form
|
||||
* even in applications where it isn't needed it becomes possible to
|
||||
* impose a requirement later if a need is discovered.
|
||||
* No other forms of ECDSA malleability are known and none seem likely,
|
||||
* but there is no formal proof that ECDSA, even with this additional
|
||||
* restriction, is free of other malleability. Commonly used serialization
|
||||
* schemes will also accept various non-unique encodings, so care should
|
||||
* be taken when this property is required for an application.
|
||||
*/
|
||||
int secp256k1_ecdsa_sign(const unsigned char *msg, int msglen,
|
||||
unsigned char *sig, int *siglen,
|
||||
int secp256k1_ecdsa_sign(
|
||||
const unsigned char *msg32,
|
||||
unsigned char *sig,
|
||||
int *siglen,
|
||||
const unsigned char *seckey,
|
||||
const unsigned char *nonce);
|
||||
secp256k1_nonce_function_t noncefp,
|
||||
const void *ndata
|
||||
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4);
|
||||
|
||||
/** Create a compact ECDSA signature (64 byte + recovery id).
|
||||
* Returns: 1: signature created
|
||||
* 0: nonce invalid, try another one
|
||||
* In: msg: the message being signed
|
||||
* msglen: the length of the message being signed
|
||||
* seckey: pointer to a 32-byte secret key (assumed to be valid)
|
||||
* nonce: pointer to a 32-byte nonce (generated with a cryptographic PRNG)
|
||||
* Out: sig: pointer to a 64-byte array where the signature will be placed.
|
||||
* recid: pointer to an int, which will be updated to contain the recovery id.
|
||||
* 0: the nonce generation function failed, or the secret key was invalid.
|
||||
* In: msg32: the 32-byte message hash being signed (cannot be NULL)
|
||||
* seckey: pointer to a 32-byte secret key (cannot be NULL)
|
||||
* noncefp:pointer to a nonce generation function. If NULL, secp256k1_nonce_function_default is used
|
||||
* ndata: pointer to arbitrary data used by the nonce generation function (can be NULL)
|
||||
* Out: sig: pointer to a 64-byte array where the signature will be placed (cannot be NULL)
|
||||
* In case 0 is returned, the returned signature length will be zero.
|
||||
* recid: pointer to an int, which will be updated to contain the recovery id (can be NULL)
|
||||
* Requires starting using SECP256K1_START_SIGN.
|
||||
*/
|
||||
int secp256k1_ecdsa_sign_compact(const unsigned char *msg, int msglen,
|
||||
int secp256k1_ecdsa_sign_compact(
|
||||
const unsigned char *msg32,
|
||||
unsigned char *sig64,
|
||||
const unsigned char *seckey,
|
||||
const unsigned char *nonce,
|
||||
int *recid);
|
||||
secp256k1_nonce_function_t noncefp,
|
||||
const void *ndata,
|
||||
int *recid
|
||||
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
|
||||
|
||||
/** Recover an ECDSA public key from a compact signature.
|
||||
* Returns: 1: public key succesfully recovered (which guarantees a correct signature).
|
||||
* Returns: 1: public key successfully recovered (which guarantees a correct signature).
|
||||
* 0: otherwise.
|
||||
* In: msg: the message assumed to be signed
|
||||
* msglen: the length of the message
|
||||
* sig64: signature as 64 byte array
|
||||
* In: msg32: the 32-byte message hash assumed to be signed (cannot be NULL)
|
||||
* sig64: signature as 64 byte array (cannot be NULL)
|
||||
* compressed: whether to recover a compressed or uncompressed pubkey
|
||||
* recid: the recovery id (as returned by ecdsa_sign_compact)
|
||||
* Out: pubkey: pointer to a 33 or 65 byte array to put the pubkey.
|
||||
* pubkeylen: pointer to an int that will contain the pubkey length.
|
||||
* recid: the recovery id (0-3, as returned by ecdsa_sign_compact)
|
||||
* Out: pubkey: pointer to a 33 or 65 byte array to put the pubkey (cannot be NULL)
|
||||
* pubkeylen: pointer to an int that will contain the pubkey length (cannot be NULL)
|
||||
* Requires starting using SECP256K1_START_VERIFY.
|
||||
*/
|
||||
|
||||
int secp256k1_ecdsa_recover_compact(const unsigned char *msg, int msglen,
|
||||
SECP256K1_WARN_UNUSED_RESULT int secp256k1_ecdsa_recover_compact(
|
||||
const unsigned char *msg32,
|
||||
const unsigned char *sig64,
|
||||
unsigned char *pubkey, int *pubkeylen,
|
||||
int compressed, int recid);
|
||||
unsigned char *pubkey,
|
||||
int *pubkeylen,
|
||||
int compressed,
|
||||
int recid
|
||||
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4);
|
||||
|
||||
/** Verify an ECDSA secret key.
|
||||
* Returns: 1: secret key is valid
|
||||
* 0: secret key is invalid
|
||||
* In: seckey: pointer to a 32-byte secret key
|
||||
* In: seckey: pointer to a 32-byte secret key (cannot be NULL)
|
||||
*/
|
||||
int secp256k1_ecdsa_seckey_verify(const unsigned char *seckey);
|
||||
SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_seckey_verify(const unsigned char *seckey) SECP256K1_ARG_NONNULL(1);
|
||||
|
||||
/** Just validate a public key.
|
||||
* Returns: 1: valid public key
|
||||
* 0: invalid public key
|
||||
* In: pubkey: pointer to a 33-byte or 65-byte public key (cannot be NULL).
|
||||
* pubkeylen: length of pubkey
|
||||
*/
|
||||
int secp256k1_ecdsa_pubkey_verify(const unsigned char *pubkey, int pubkeylen);
|
||||
SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_pubkey_verify(const unsigned char *pubkey, int pubkeylen) SECP256K1_ARG_NONNULL(1);
|
||||
|
||||
/** Compute the public key for a secret key.
|
||||
* In: compressed: whether the computed public key should be compressed
|
||||
* seckey: pointer to a 32-byte private key.
|
||||
* seckey: pointer to a 32-byte private key (cannot be NULL)
|
||||
* Out: pubkey: pointer to a 33-byte (if compressed) or 65-byte (if uncompressed)
|
||||
* area to store the public key.
|
||||
* area to store the public key (cannot be NULL)
|
||||
* pubkeylen: pointer to int that will be updated to contains the pubkey's
|
||||
* length.
|
||||
* length (cannot be NULL)
|
||||
* Returns: 1: secret was valid, public key stores
|
||||
* 0: secret was invalid, try again.
|
||||
* Requires starting using SECP256K1_START_SIGN.
|
||||
*/
|
||||
int secp256k1_ecdsa_pubkey_create(unsigned char *pubkey, int *pubkeylen, const unsigned char *seckey, int compressed);
|
||||
SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_pubkey_create(
|
||||
unsigned char *pubkey,
|
||||
int *pubkeylen,
|
||||
const unsigned char *seckey,
|
||||
int compressed
|
||||
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
|
||||
|
||||
int secp256k1_ecdsa_pubkey_decompress(unsigned char *pubkey, int *pubkeylen);
|
||||
/** Decompress a public key.
|
||||
* In/Out: pubkey: pointer to a 65-byte array to put the decompressed public key.
|
||||
It must contain a 33-byte or 65-byte public key already (cannot be NULL)
|
||||
* pubkeylen: pointer to the size of the public key pointed to by pubkey (cannot be NULL)
|
||||
It will be updated to reflect the new size.
|
||||
* Returns: 0 if the passed public key was invalid, 1 otherwise. If 1 is returned, the
|
||||
pubkey is replaced with its decompressed version.
|
||||
*/
|
||||
SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_pubkey_decompress(
|
||||
unsigned char *pubkey,
|
||||
int *pubkeylen
|
||||
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2);
|
||||
|
||||
int secp256k1_ecdsa_privkey_export(const unsigned char *seckey,
|
||||
unsigned char *privkey, int *privkeylen,
|
||||
int compressed);
|
||||
/** Export a private key in DER format. */
|
||||
SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_privkey_export(
|
||||
const unsigned char *seckey,
|
||||
unsigned char *privkey,
|
||||
int *privkeylen,
|
||||
int compressed
|
||||
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
|
||||
|
||||
int secp256k1_ecdsa_privkey_import(unsigned char *seckey,
|
||||
const unsigned char *privkey, int privkeylen);
|
||||
/** Import a private key in DER format. */
|
||||
SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_privkey_import(
|
||||
unsigned char *seckey,
|
||||
const unsigned char *privkey,
|
||||
int privkeylen
|
||||
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2);
|
||||
|
||||
int secp256k1_ecdsa_privkey_tweak_add(unsigned char *seckey, const unsigned char *tweak);
|
||||
int secp256k1_ecdsa_pubkey_tweak_add(unsigned char *pubkey, int pubkeylen, const unsigned char *tweak);
|
||||
int secp256k1_ecdsa_privkey_tweak_mul(unsigned char *seckey, const unsigned char *tweak);
|
||||
int secp256k1_ecdsa_pubkey_tweak_mul(unsigned char *pubkey, int pubkeylen, const unsigned char *tweak);
|
||||
/** Tweak a private key by adding tweak to it. */
|
||||
SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_privkey_tweak_add(
|
||||
unsigned char *seckey,
|
||||
const unsigned char *tweak
|
||||
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2);
|
||||
|
||||
#ifdef __cplusplus
|
||||
/** Tweak a public key by adding tweak times the generator to it.
|
||||
* Requires starting with SECP256K1_START_VERIFY.
|
||||
*/
|
||||
SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_pubkey_tweak_add(
|
||||
unsigned char *pubkey,
|
||||
int pubkeylen,
|
||||
const unsigned char *tweak
|
||||
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(3);
|
||||
|
||||
/** Tweak a private key by multiplying it with tweak. */
|
||||
SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_privkey_tweak_mul(
|
||||
unsigned char *seckey,
|
||||
const unsigned char *tweak
|
||||
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2);
|
||||
|
||||
/** Tweak a public key by multiplying it with tweak.
|
||||
* Requires starting with SECP256K1_START_VERIFY.
|
||||
*/
|
||||
SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_pubkey_tweak_mul(
|
||||
unsigned char *pubkey,
|
||||
int pubkeylen,
|
||||
const unsigned char *tweak
|
||||
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(3);
|
||||
|
||||
# ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
# endif
|
||||
|
||||
#endif
|
||||
|
|
|
|||
13
crypto/secp256k1/secp256k1/libsecp256k1.pc.in
Normal file
13
crypto/secp256k1/secp256k1/libsecp256k1.pc.in
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
prefix=@prefix@
|
||||
exec_prefix=@exec_prefix@
|
||||
libdir=@libdir@
|
||||
includedir=@includedir@
|
||||
|
||||
Name: libsecp256k1
|
||||
Description: Optimized C library for EC operations on curve secp256k1
|
||||
URL: https://github.com/bitcoin/secp256k1
|
||||
Version: @PACKAGE_VERSION@
|
||||
Cflags: -I${includedir}
|
||||
Libs.private: @SECP_LIBS@
|
||||
Libs: -L${libdir} -lsecp256k1
|
||||
|
||||
0
crypto/secp256k1/secp256k1/obj/.gitignore
vendored
Normal file
0
crypto/secp256k1/secp256k1/obj/.gitignore
vendored
Normal file
|
|
@ -1,64 +0,0 @@
|
|||
// Copyright (c) 2013 Pieter Wuille
|
||||
// Distributed under the MIT/X11 software license, see the accompanying
|
||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||
|
||||
#include <stdio.h>
|
||||
|
||||
#include "impl/num.h"
|
||||
#include "impl/field.h"
|
||||
#include "impl/group.h"
|
||||
#include "impl/ecmult.h"
|
||||
#include "impl/ecdsa.h"
|
||||
#include "impl/util.h"
|
||||
|
||||
void random_num_order(secp256k1_num_t *num) {
|
||||
do {
|
||||
unsigned char b32[32];
|
||||
secp256k1_rand256(b32);
|
||||
secp256k1_num_set_bin(num, b32, 32);
|
||||
if (secp256k1_num_is_zero(num))
|
||||
continue;
|
||||
if (secp256k1_num_cmp(num, &secp256k1_ge_consts->order) >= 0)
|
||||
continue;
|
||||
break;
|
||||
} while(1);
|
||||
}
|
||||
|
||||
int main() {
|
||||
secp256k1_fe_start();
|
||||
secp256k1_ge_start();
|
||||
secp256k1_ecmult_start();
|
||||
|
||||
secp256k1_fe_t x;
|
||||
const secp256k1_num_t *order = &secp256k1_ge_consts->order;
|
||||
secp256k1_num_t r, s, m;
|
||||
secp256k1_num_init(&r);
|
||||
secp256k1_num_init(&s);
|
||||
secp256k1_num_init(&m);
|
||||
secp256k1_ecdsa_sig_t sig;
|
||||
secp256k1_ecdsa_sig_init(&sig);
|
||||
secp256k1_fe_set_hex(&x, "a357ae915c4a65281309edf20504740f0eb3343990216b4f81063cb65f2f7e0f", 64);
|
||||
int cnt = 0;
|
||||
int good = 0;
|
||||
for (int i=0; i<1000000; i++) {
|
||||
random_num_order(&r);
|
||||
random_num_order(&s);
|
||||
random_num_order(&m);
|
||||
secp256k1_ecdsa_sig_set_rs(&sig, &r, &s);
|
||||
secp256k1_ge_t pubkey; secp256k1_ge_set_xo(&pubkey, &x, 1);
|
||||
if (secp256k1_ge_is_valid(&pubkey)) {
|
||||
cnt++;
|
||||
good += secp256k1_ecdsa_sig_verify(&sig, &pubkey, &m);
|
||||
}
|
||||
}
|
||||
printf("%i/%i\n", good, cnt);
|
||||
secp256k1_num_free(&r);
|
||||
secp256k1_num_free(&s);
|
||||
secp256k1_num_free(&m);
|
||||
secp256k1_ecdsa_sig_free(&sig);
|
||||
|
||||
secp256k1_ecmult_stop();
|
||||
secp256k1_ge_stop();
|
||||
secp256k1_fe_stop();
|
||||
return 0;
|
||||
}
|
||||
56
crypto/secp256k1/secp256k1/src/bench.h
Normal file
56
crypto/secp256k1/secp256k1/src/bench.h
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
/**********************************************************************
|
||||
* Copyright (c) 2014 Pieter Wuille *
|
||||
* Distributed under the MIT software license, see the accompanying *
|
||||
* file COPYING or http://www.opensource.org/licenses/mit-license.php.*
|
||||
**********************************************************************/
|
||||
|
||||
#ifndef _SECP256K1_BENCH_H_
|
||||
#define _SECP256K1_BENCH_H_
|
||||
|
||||
#include <stdio.h>
|
||||
#include <math.h>
|
||||
#include "sys/time.h"
|
||||
|
||||
static double gettimedouble(void) {
|
||||
struct timeval tv;
|
||||
gettimeofday(&tv, NULL);
|
||||
return tv.tv_usec * 0.000001 + tv.tv_sec;
|
||||
}
|
||||
|
||||
void print_number(double x) {
|
||||
double y = x;
|
||||
int c = 0;
|
||||
if (y < 0.0) y = -y;
|
||||
while (y < 100.0) {
|
||||
y *= 10.0;
|
||||
c++;
|
||||
}
|
||||
printf("%.*f", c, x);
|
||||
}
|
||||
|
||||
void run_benchmark(char *name, void (*benchmark)(void*), void (*setup)(void*), void (*teardown)(void*), void* data, int count, int iter) {
|
||||
int i;
|
||||
double min = HUGE_VAL;
|
||||
double sum = 0.0;
|
||||
double max = 0.0;
|
||||
for (i = 0; i < count; i++) {
|
||||
double begin, total;
|
||||
if (setup) setup(data);
|
||||
begin = gettimedouble();
|
||||
benchmark(data);
|
||||
total = gettimedouble() - begin;
|
||||
if (teardown) teardown(data);
|
||||
if (total < min) min = total;
|
||||
if (total > max) max = total;
|
||||
sum += total;
|
||||
}
|
||||
printf("%s: min ", name);
|
||||
print_number(min * 1000000.0 / iter);
|
||||
printf("us / avg ");
|
||||
print_number((sum / count) * 1000000.0 / iter);
|
||||
printf("us / avg ");
|
||||
print_number(max * 1000000.0 / iter);
|
||||
printf("us\n");
|
||||
}
|
||||
|
||||
#endif
|
||||
318
crypto/secp256k1/secp256k1/src/bench_internal.c
Normal file
318
crypto/secp256k1/secp256k1/src/bench_internal.c
Normal file
|
|
@ -0,0 +1,318 @@
|
|||
/**********************************************************************
|
||||
* Copyright (c) 2014-2015 Pieter Wuille *
|
||||
* Distributed under the MIT software license, see the accompanying *
|
||||
* file COPYING or http://www.opensource.org/licenses/mit-license.php.*
|
||||
**********************************************************************/
|
||||
#include <stdio.h>
|
||||
|
||||
#include "include/secp256k1.h"
|
||||
|
||||
#include "util.h"
|
||||
#include "hash_impl.h"
|
||||
#include "num_impl.h"
|
||||
#include "field_impl.h"
|
||||
#include "group_impl.h"
|
||||
#include "scalar_impl.h"
|
||||
#include "ecmult_impl.h"
|
||||
#include "bench.h"
|
||||
|
||||
typedef struct {
|
||||
secp256k1_scalar_t scalar_x, scalar_y;
|
||||
secp256k1_fe_t fe_x, fe_y;
|
||||
secp256k1_ge_t ge_x, ge_y;
|
||||
secp256k1_gej_t gej_x, gej_y;
|
||||
unsigned char data[32];
|
||||
int wnaf[256];
|
||||
} bench_inv_t;
|
||||
|
||||
void bench_setup(void* arg) {
|
||||
bench_inv_t *data = (bench_inv_t*)arg;
|
||||
|
||||
static const unsigned char init_x[32] = {
|
||||
0x02, 0x03, 0x05, 0x07, 0x0b, 0x0d, 0x11, 0x13,
|
||||
0x17, 0x1d, 0x1f, 0x25, 0x29, 0x2b, 0x2f, 0x35,
|
||||
0x3b, 0x3d, 0x43, 0x47, 0x49, 0x4f, 0x53, 0x59,
|
||||
0x61, 0x65, 0x67, 0x6b, 0x6d, 0x71, 0x7f, 0x83
|
||||
};
|
||||
|
||||
static const unsigned char init_y[32] = {
|
||||
0x82, 0x83, 0x85, 0x87, 0x8b, 0x8d, 0x81, 0x83,
|
||||
0x97, 0xad, 0xaf, 0xb5, 0xb9, 0xbb, 0xbf, 0xc5,
|
||||
0xdb, 0xdd, 0xe3, 0xe7, 0xe9, 0xef, 0xf3, 0xf9,
|
||||
0x11, 0x15, 0x17, 0x1b, 0x1d, 0xb1, 0xbf, 0xd3
|
||||
};
|
||||
|
||||
secp256k1_scalar_set_b32(&data->scalar_x, init_x, NULL);
|
||||
secp256k1_scalar_set_b32(&data->scalar_y, init_y, NULL);
|
||||
secp256k1_fe_set_b32(&data->fe_x, init_x);
|
||||
secp256k1_fe_set_b32(&data->fe_y, init_y);
|
||||
CHECK(secp256k1_ge_set_xo_var(&data->ge_x, &data->fe_x, 0));
|
||||
CHECK(secp256k1_ge_set_xo_var(&data->ge_y, &data->fe_y, 1));
|
||||
secp256k1_gej_set_ge(&data->gej_x, &data->ge_x);
|
||||
secp256k1_gej_set_ge(&data->gej_y, &data->ge_y);
|
||||
memcpy(data->data, init_x, 32);
|
||||
}
|
||||
|
||||
void bench_scalar_add(void* arg) {
|
||||
int i;
|
||||
bench_inv_t *data = (bench_inv_t*)arg;
|
||||
|
||||
for (i = 0; i < 2000000; i++) {
|
||||
secp256k1_scalar_add(&data->scalar_x, &data->scalar_x, &data->scalar_y);
|
||||
}
|
||||
}
|
||||
|
||||
void bench_scalar_negate(void* arg) {
|
||||
int i;
|
||||
bench_inv_t *data = (bench_inv_t*)arg;
|
||||
|
||||
for (i = 0; i < 2000000; i++) {
|
||||
secp256k1_scalar_negate(&data->scalar_x, &data->scalar_x);
|
||||
}
|
||||
}
|
||||
|
||||
void bench_scalar_sqr(void* arg) {
|
||||
int i;
|
||||
bench_inv_t *data = (bench_inv_t*)arg;
|
||||
|
||||
for (i = 0; i < 200000; i++) {
|
||||
secp256k1_scalar_sqr(&data->scalar_x, &data->scalar_x);
|
||||
}
|
||||
}
|
||||
|
||||
void bench_scalar_mul(void* arg) {
|
||||
int i;
|
||||
bench_inv_t *data = (bench_inv_t*)arg;
|
||||
|
||||
for (i = 0; i < 200000; i++) {
|
||||
secp256k1_scalar_mul(&data->scalar_x, &data->scalar_x, &data->scalar_y);
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef USE_ENDOMORPHISM
|
||||
void bench_scalar_split(void* arg) {
|
||||
int i;
|
||||
bench_inv_t *data = (bench_inv_t*)arg;
|
||||
|
||||
for (i = 0; i < 20000; i++) {
|
||||
secp256k1_scalar_t l, r;
|
||||
secp256k1_scalar_split_lambda_var(&l, &r, &data->scalar_x);
|
||||
secp256k1_scalar_add(&data->scalar_x, &data->scalar_x, &data->scalar_y);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
void bench_scalar_inverse(void* arg) {
|
||||
int i;
|
||||
bench_inv_t *data = (bench_inv_t*)arg;
|
||||
|
||||
for (i = 0; i < 2000; i++) {
|
||||
secp256k1_scalar_inverse(&data->scalar_x, &data->scalar_x);
|
||||
secp256k1_scalar_add(&data->scalar_x, &data->scalar_x, &data->scalar_y);
|
||||
}
|
||||
}
|
||||
|
||||
void bench_scalar_inverse_var(void* arg) {
|
||||
int i;
|
||||
bench_inv_t *data = (bench_inv_t*)arg;
|
||||
|
||||
for (i = 0; i < 2000; i++) {
|
||||
secp256k1_scalar_inverse_var(&data->scalar_x, &data->scalar_x);
|
||||
secp256k1_scalar_add(&data->scalar_x, &data->scalar_x, &data->scalar_y);
|
||||
}
|
||||
}
|
||||
|
||||
void bench_field_normalize(void* arg) {
|
||||
int i;
|
||||
bench_inv_t *data = (bench_inv_t*)arg;
|
||||
|
||||
for (i = 0; i < 2000000; i++) {
|
||||
secp256k1_fe_normalize(&data->fe_x);
|
||||
}
|
||||
}
|
||||
|
||||
void bench_field_normalize_weak(void* arg) {
|
||||
int i;
|
||||
bench_inv_t *data = (bench_inv_t*)arg;
|
||||
|
||||
for (i = 0; i < 2000000; i++) {
|
||||
secp256k1_fe_normalize_weak(&data->fe_x);
|
||||
}
|
||||
}
|
||||
|
||||
void bench_field_mul(void* arg) {
|
||||
int i;
|
||||
bench_inv_t *data = (bench_inv_t*)arg;
|
||||
|
||||
for (i = 0; i < 200000; i++) {
|
||||
secp256k1_fe_mul(&data->fe_x, &data->fe_x, &data->fe_y);
|
||||
}
|
||||
}
|
||||
|
||||
void bench_field_sqr(void* arg) {
|
||||
int i;
|
||||
bench_inv_t *data = (bench_inv_t*)arg;
|
||||
|
||||
for (i = 0; i < 200000; i++) {
|
||||
secp256k1_fe_sqr(&data->fe_x, &data->fe_x);
|
||||
}
|
||||
}
|
||||
|
||||
void bench_field_inverse(void* arg) {
|
||||
int i;
|
||||
bench_inv_t *data = (bench_inv_t*)arg;
|
||||
|
||||
for (i = 0; i < 20000; i++) {
|
||||
secp256k1_fe_inv(&data->fe_x, &data->fe_x);
|
||||
secp256k1_fe_add(&data->fe_x, &data->fe_y);
|
||||
}
|
||||
}
|
||||
|
||||
void bench_field_inverse_var(void* arg) {
|
||||
int i;
|
||||
bench_inv_t *data = (bench_inv_t*)arg;
|
||||
|
||||
for (i = 0; i < 20000; i++) {
|
||||
secp256k1_fe_inv_var(&data->fe_x, &data->fe_x);
|
||||
secp256k1_fe_add(&data->fe_x, &data->fe_y);
|
||||
}
|
||||
}
|
||||
|
||||
void bench_field_sqrt_var(void* arg) {
|
||||
int i;
|
||||
bench_inv_t *data = (bench_inv_t*)arg;
|
||||
|
||||
for (i = 0; i < 20000; i++) {
|
||||
secp256k1_fe_sqrt_var(&data->fe_x, &data->fe_x);
|
||||
secp256k1_fe_add(&data->fe_x, &data->fe_y);
|
||||
}
|
||||
}
|
||||
|
||||
void bench_group_double_var(void* arg) {
|
||||
int i;
|
||||
bench_inv_t *data = (bench_inv_t*)arg;
|
||||
|
||||
for (i = 0; i < 200000; i++) {
|
||||
secp256k1_gej_double_var(&data->gej_x, &data->gej_x);
|
||||
}
|
||||
}
|
||||
|
||||
void bench_group_add_var(void* arg) {
|
||||
int i;
|
||||
bench_inv_t *data = (bench_inv_t*)arg;
|
||||
|
||||
for (i = 0; i < 200000; i++) {
|
||||
secp256k1_gej_add_var(&data->gej_x, &data->gej_x, &data->gej_y);
|
||||
}
|
||||
}
|
||||
|
||||
void bench_group_add_affine(void* arg) {
|
||||
int i;
|
||||
bench_inv_t *data = (bench_inv_t*)arg;
|
||||
|
||||
for (i = 0; i < 200000; i++) {
|
||||
secp256k1_gej_add_ge(&data->gej_x, &data->gej_x, &data->ge_y);
|
||||
}
|
||||
}
|
||||
|
||||
void bench_group_add_affine_var(void* arg) {
|
||||
int i;
|
||||
bench_inv_t *data = (bench_inv_t*)arg;
|
||||
|
||||
for (i = 0; i < 200000; i++) {
|
||||
secp256k1_gej_add_ge_var(&data->gej_x, &data->gej_x, &data->ge_y);
|
||||
}
|
||||
}
|
||||
|
||||
void bench_ecmult_wnaf(void* arg) {
|
||||
int i;
|
||||
bench_inv_t *data = (bench_inv_t*)arg;
|
||||
|
||||
for (i = 0; i < 20000; i++) {
|
||||
secp256k1_ecmult_wnaf(data->wnaf, &data->scalar_x, WINDOW_A);
|
||||
secp256k1_scalar_add(&data->scalar_x, &data->scalar_x, &data->scalar_y);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void bench_sha256(void* arg) {
|
||||
int i;
|
||||
bench_inv_t *data = (bench_inv_t*)arg;
|
||||
secp256k1_sha256_t sha;
|
||||
|
||||
for (i = 0; i < 20000; i++) {
|
||||
secp256k1_sha256_initialize(&sha);
|
||||
secp256k1_sha256_write(&sha, data->data, 32);
|
||||
secp256k1_sha256_finalize(&sha, data->data);
|
||||
}
|
||||
}
|
||||
|
||||
void bench_hmac_sha256(void* arg) {
|
||||
int i;
|
||||
bench_inv_t *data = (bench_inv_t*)arg;
|
||||
secp256k1_hmac_sha256_t hmac;
|
||||
|
||||
for (i = 0; i < 20000; i++) {
|
||||
secp256k1_hmac_sha256_initialize(&hmac, data->data, 32);
|
||||
secp256k1_hmac_sha256_write(&hmac, data->data, 32);
|
||||
secp256k1_hmac_sha256_finalize(&hmac, data->data);
|
||||
}
|
||||
}
|
||||
|
||||
void bench_rfc6979_hmac_sha256(void* arg) {
|
||||
int i;
|
||||
bench_inv_t *data = (bench_inv_t*)arg;
|
||||
secp256k1_rfc6979_hmac_sha256_t rng;
|
||||
|
||||
for (i = 0; i < 20000; i++) {
|
||||
secp256k1_rfc6979_hmac_sha256_initialize(&rng, data->data, 32, data->data, 32, NULL, 0);
|
||||
secp256k1_rfc6979_hmac_sha256_generate(&rng, data->data, 32);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
int have_flag(int argc, char** argv, char *flag) {
|
||||
char** argm = argv + argc;
|
||||
argv++;
|
||||
if (argv == argm) {
|
||||
return 1;
|
||||
}
|
||||
while (argv != NULL && argv != argm) {
|
||||
if (strcmp(*argv, flag) == 0) return 1;
|
||||
argv++;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
bench_inv_t data;
|
||||
if (have_flag(argc, argv, "scalar") || have_flag(argc, argv, "add")) run_benchmark("scalar_add", bench_scalar_add, bench_setup, NULL, &data, 10, 2000000);
|
||||
if (have_flag(argc, argv, "scalar") || have_flag(argc, argv, "negate")) run_benchmark("scalar_negate", bench_scalar_negate, bench_setup, NULL, &data, 10, 2000000);
|
||||
if (have_flag(argc, argv, "scalar") || have_flag(argc, argv, "sqr")) run_benchmark("scalar_sqr", bench_scalar_sqr, bench_setup, NULL, &data, 10, 200000);
|
||||
if (have_flag(argc, argv, "scalar") || have_flag(argc, argv, "mul")) run_benchmark("scalar_mul", bench_scalar_mul, bench_setup, NULL, &data, 10, 200000);
|
||||
#ifdef USE_ENDOMORPHISM
|
||||
if (have_flag(argc, argv, "scalar") || have_flag(argc, argv, "split")) run_benchmark("scalar_split", bench_scalar_split, bench_setup, NULL, &data, 10, 20000);
|
||||
#endif
|
||||
if (have_flag(argc, argv, "scalar") || have_flag(argc, argv, "inverse")) run_benchmark("scalar_inverse", bench_scalar_inverse, bench_setup, NULL, &data, 10, 2000);
|
||||
if (have_flag(argc, argv, "scalar") || have_flag(argc, argv, "inverse")) run_benchmark("scalar_inverse_var", bench_scalar_inverse_var, bench_setup, NULL, &data, 10, 2000);
|
||||
|
||||
if (have_flag(argc, argv, "field") || have_flag(argc, argv, "normalize")) run_benchmark("field_normalize", bench_field_normalize, bench_setup, NULL, &data, 10, 2000000);
|
||||
if (have_flag(argc, argv, "field") || have_flag(argc, argv, "normalize")) run_benchmark("field_normalize_weak", bench_field_normalize_weak, bench_setup, NULL, &data, 10, 2000000);
|
||||
if (have_flag(argc, argv, "field") || have_flag(argc, argv, "sqr")) run_benchmark("field_sqr", bench_field_sqr, bench_setup, NULL, &data, 10, 200000);
|
||||
if (have_flag(argc, argv, "field") || have_flag(argc, argv, "mul")) run_benchmark("field_mul", bench_field_mul, bench_setup, NULL, &data, 10, 200000);
|
||||
if (have_flag(argc, argv, "field") || have_flag(argc, argv, "inverse")) run_benchmark("field_inverse", bench_field_inverse, bench_setup, NULL, &data, 10, 20000);
|
||||
if (have_flag(argc, argv, "field") || have_flag(argc, argv, "inverse")) run_benchmark("field_inverse_var", bench_field_inverse_var, bench_setup, NULL, &data, 10, 20000);
|
||||
if (have_flag(argc, argv, "field") || have_flag(argc, argv, "sqrt")) run_benchmark("field_sqrt_var", bench_field_sqrt_var, bench_setup, NULL, &data, 10, 20000);
|
||||
|
||||
if (have_flag(argc, argv, "group") || have_flag(argc, argv, "double")) run_benchmark("group_double_var", bench_group_double_var, bench_setup, NULL, &data, 10, 200000);
|
||||
if (have_flag(argc, argv, "group") || have_flag(argc, argv, "add")) run_benchmark("group_add_var", bench_group_add_var, bench_setup, NULL, &data, 10, 200000);
|
||||
if (have_flag(argc, argv, "group") || have_flag(argc, argv, "add")) run_benchmark("group_add_affine", bench_group_add_affine, bench_setup, NULL, &data, 10, 200000);
|
||||
if (have_flag(argc, argv, "group") || have_flag(argc, argv, "add")) run_benchmark("group_add_affine_var", bench_group_add_affine_var, bench_setup, NULL, &data, 10, 200000);
|
||||
|
||||
if (have_flag(argc, argv, "ecmult") || have_flag(argc, argv, "wnaf")) run_benchmark("ecmult_wnaf", bench_ecmult_wnaf, bench_setup, NULL, &data, 10, 20000);
|
||||
|
||||
if (have_flag(argc, argv, "hash") || have_flag(argc, argv, "sha256")) run_benchmark("hash_sha256", bench_sha256, bench_setup, NULL, &data, 10, 20000);
|
||||
if (have_flag(argc, argv, "hash") || have_flag(argc, argv, "hmac")) run_benchmark("hash_hmac_sha256", bench_hmac_sha256, bench_setup, NULL, &data, 10, 20000);
|
||||
if (have_flag(argc, argv, "hash") || have_flag(argc, argv, "rng6979")) run_benchmark("hash_rfc6979_hmac_sha256", bench_rfc6979_hmac_sha256, bench_setup, NULL, &data, 10, 20000);
|
||||
return 0;
|
||||
}
|
||||
49
crypto/secp256k1/secp256k1/src/bench_recover.c
Normal file
49
crypto/secp256k1/secp256k1/src/bench_recover.c
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
/**********************************************************************
|
||||
* Copyright (c) 2014 Pieter Wuille *
|
||||
* Distributed under the MIT software license, see the accompanying *
|
||||
* file COPYING or http://www.opensource.org/licenses/mit-license.php.*
|
||||
**********************************************************************/
|
||||
|
||||
#include "include/secp256k1.h"
|
||||
#include "util.h"
|
||||
#include "bench.h"
|
||||
|
||||
typedef struct {
|
||||
unsigned char msg[32];
|
||||
unsigned char sig[64];
|
||||
} bench_recover_t;
|
||||
|
||||
void bench_recover(void* arg) {
|
||||
int i;
|
||||
bench_recover_t *data = (bench_recover_t*)arg;
|
||||
unsigned char pubkey[33];
|
||||
|
||||
for (i = 0; i < 20000; i++) {
|
||||
int j;
|
||||
int pubkeylen = 33;
|
||||
CHECK(secp256k1_ecdsa_recover_compact(data->msg, data->sig, pubkey, &pubkeylen, 1, i % 2));
|
||||
for (j = 0; j < 32; j++) {
|
||||
data->sig[j + 32] = data->msg[j]; /* Move former message to S. */
|
||||
data->msg[j] = data->sig[j]; /* Move former R to message. */
|
||||
data->sig[j] = pubkey[j + 1]; /* Move recovered pubkey X coordinate to R (which must be a valid X coordinate). */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void bench_recover_setup(void* arg) {
|
||||
int i;
|
||||
bench_recover_t *data = (bench_recover_t*)arg;
|
||||
|
||||
for (i = 0; i < 32; i++) data->msg[i] = 1 + i;
|
||||
for (i = 0; i < 64; i++) data->sig[i] = 65 + i;
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
bench_recover_t data;
|
||||
secp256k1_start(SECP256K1_START_VERIFY);
|
||||
|
||||
run_benchmark("ecdsa_recover", bench_recover, bench_recover_setup, NULL, &data, 10, 20000);
|
||||
|
||||
secp256k1_stop();
|
||||
return 0;
|
||||
}
|
||||
48
crypto/secp256k1/secp256k1/src/bench_sign.c
Normal file
48
crypto/secp256k1/secp256k1/src/bench_sign.c
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
/**********************************************************************
|
||||
* Copyright (c) 2014 Pieter Wuille *
|
||||
* Distributed under the MIT software license, see the accompanying *
|
||||
* file COPYING or http://www.opensource.org/licenses/mit-license.php.*
|
||||
**********************************************************************/
|
||||
|
||||
#include "include/secp256k1.h"
|
||||
#include "util.h"
|
||||
#include "bench.h"
|
||||
|
||||
typedef struct {
|
||||
unsigned char msg[32];
|
||||
unsigned char key[32];
|
||||
} bench_sign_t;
|
||||
|
||||
static void bench_sign_setup(void* arg) {
|
||||
int i;
|
||||
bench_sign_t *data = (bench_sign_t*)arg;
|
||||
|
||||
for (i = 0; i < 32; i++) data->msg[i] = i + 1;
|
||||
for (i = 0; i < 32; i++) data->key[i] = i + 65;
|
||||
}
|
||||
|
||||
static void bench_sign(void* arg) {
|
||||
int i;
|
||||
bench_sign_t *data = (bench_sign_t*)arg;
|
||||
|
||||
unsigned char sig[64];
|
||||
for (i = 0; i < 20000; i++) {
|
||||
int j;
|
||||
int recid = 0;
|
||||
CHECK(secp256k1_ecdsa_sign_compact(data->msg, sig, data->key, NULL, NULL, &recid));
|
||||
for (j = 0; j < 32; j++) {
|
||||
data->msg[j] = sig[j]; /* Move former R to message. */
|
||||
data->key[j] = sig[j + 32]; /* Move former S to key. */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
bench_sign_t data;
|
||||
secp256k1_start(SECP256K1_START_SIGN);
|
||||
|
||||
run_benchmark("ecdsa_sign", bench_sign, bench_sign_setup, NULL, &data, 10, 20000);
|
||||
|
||||
secp256k1_stop();
|
||||
return 0;
|
||||
}
|
||||
55
crypto/secp256k1/secp256k1/src/bench_verify.c
Normal file
55
crypto/secp256k1/secp256k1/src/bench_verify.c
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
/**********************************************************************
|
||||
* Copyright (c) 2014 Pieter Wuille *
|
||||
* Distributed under the MIT software license, see the accompanying *
|
||||
* file COPYING or http://www.opensource.org/licenses/mit-license.php.*
|
||||
**********************************************************************/
|
||||
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "include/secp256k1.h"
|
||||
#include "util.h"
|
||||
#include "bench.h"
|
||||
|
||||
typedef struct {
|
||||
unsigned char msg[32];
|
||||
unsigned char key[32];
|
||||
unsigned char sig[72];
|
||||
int siglen;
|
||||
unsigned char pubkey[33];
|
||||
int pubkeylen;
|
||||
} benchmark_verify_t;
|
||||
|
||||
static void benchmark_verify(void* arg) {
|
||||
int i;
|
||||
benchmark_verify_t* data = (benchmark_verify_t*)arg;
|
||||
|
||||
for (i = 0; i < 20000; i++) {
|
||||
data->sig[data->siglen - 1] ^= (i & 0xFF);
|
||||
data->sig[data->siglen - 2] ^= ((i >> 8) & 0xFF);
|
||||
data->sig[data->siglen - 3] ^= ((i >> 16) & 0xFF);
|
||||
CHECK(secp256k1_ecdsa_verify(data->msg, data->sig, data->siglen, data->pubkey, data->pubkeylen) == (i == 0));
|
||||
data->sig[data->siglen - 1] ^= (i & 0xFF);
|
||||
data->sig[data->siglen - 2] ^= ((i >> 8) & 0xFF);
|
||||
data->sig[data->siglen - 3] ^= ((i >> 16) & 0xFF);
|
||||
}
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
int i;
|
||||
benchmark_verify_t data;
|
||||
|
||||
secp256k1_start(SECP256K1_START_VERIFY | SECP256K1_START_SIGN);
|
||||
|
||||
for (i = 0; i < 32; i++) data.msg[i] = 1 + i;
|
||||
for (i = 0; i < 32; i++) data.key[i] = 33 + i;
|
||||
data.siglen = 72;
|
||||
secp256k1_ecdsa_sign(data.msg, data.sig, &data.siglen, data.key, NULL, NULL);
|
||||
data.pubkeylen = 33;
|
||||
CHECK(secp256k1_ec_pubkey_create(data.pubkey, &data.pubkeylen, data.key, 1));
|
||||
|
||||
run_benchmark("ecdsa_verify", benchmark_verify, NULL, NULL, &data, 10, 20000);
|
||||
|
||||
secp256k1_stop();
|
||||
return 0;
|
||||
}
|
||||
|
|
@ -1,28 +1,23 @@
|
|||
// Copyright (c) 2013 Pieter Wuille
|
||||
// Distributed under the MIT/X11 software license, see the accompanying
|
||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||
/**********************************************************************
|
||||
* Copyright (c) 2013, 2014 Pieter Wuille *
|
||||
* Distributed under the MIT software license, see the accompanying *
|
||||
* file COPYING or http://www.opensource.org/licenses/mit-license.php.*
|
||||
**********************************************************************/
|
||||
|
||||
#ifndef _SECP256K1_ECDSA_
|
||||
#define _SECP256K1_ECDSA_
|
||||
|
||||
#include "num.h"
|
||||
#include "scalar.h"
|
||||
#include "group.h"
|
||||
|
||||
typedef struct {
|
||||
secp256k1_num_t r, s;
|
||||
secp256k1_scalar_t r, s;
|
||||
} secp256k1_ecdsa_sig_t;
|
||||
|
||||
void static secp256k1_ecdsa_sig_init(secp256k1_ecdsa_sig_t *r);
|
||||
void static secp256k1_ecdsa_sig_free(secp256k1_ecdsa_sig_t *r);
|
||||
|
||||
int static secp256k1_ecdsa_pubkey_parse(secp256k1_ge_t *elem, const unsigned char *pub, int size);
|
||||
void static secp256k1_ecdsa_pubkey_serialize(secp256k1_ge_t *elem, unsigned char *pub, int *size, int compressed);
|
||||
int static secp256k1_ecdsa_sig_parse(secp256k1_ecdsa_sig_t *r, const unsigned char *sig, int size);
|
||||
int static secp256k1_ecdsa_sig_serialize(unsigned char *sig, int *size, const secp256k1_ecdsa_sig_t *a);
|
||||
int static secp256k1_ecdsa_sig_verify(const secp256k1_ecdsa_sig_t *sig, const secp256k1_ge_t *pubkey, const secp256k1_num_t *message);
|
||||
int static secp256k1_ecdsa_sig_sign(secp256k1_ecdsa_sig_t *sig, const secp256k1_num_t *seckey, const secp256k1_num_t *message, const secp256k1_num_t *nonce, int *recid);
|
||||
int static secp256k1_ecdsa_sig_recover(const secp256k1_ecdsa_sig_t *sig, secp256k1_ge_t *pubkey, const secp256k1_num_t *message, int recid);
|
||||
void static secp256k1_ecdsa_sig_set_rs(secp256k1_ecdsa_sig_t *sig, const secp256k1_num_t *r, const secp256k1_num_t *s);
|
||||
int static secp256k1_ecdsa_privkey_parse(secp256k1_num_t *key, const unsigned char *privkey, int privkeylen);
|
||||
int static secp256k1_ecdsa_privkey_serialize(unsigned char *privkey, int *privkeylen, const secp256k1_num_t *key, int compressed);
|
||||
static int secp256k1_ecdsa_sig_parse(secp256k1_ecdsa_sig_t *r, const unsigned char *sig, int size);
|
||||
static int secp256k1_ecdsa_sig_serialize(unsigned char *sig, int *size, const secp256k1_ecdsa_sig_t *a);
|
||||
static int secp256k1_ecdsa_sig_verify(const secp256k1_ecdsa_sig_t *sig, const secp256k1_ge_t *pubkey, const secp256k1_scalar_t *message);
|
||||
static int secp256k1_ecdsa_sig_sign(secp256k1_ecdsa_sig_t *sig, const secp256k1_scalar_t *seckey, const secp256k1_scalar_t *message, const secp256k1_scalar_t *nonce, int *recid);
|
||||
static int secp256k1_ecdsa_sig_recover(const secp256k1_ecdsa_sig_t *sig, secp256k1_ge_t *pubkey, const secp256k1_scalar_t *message, int recid);
|
||||
|
||||
#endif
|
||||
|
|
|
|||
263
crypto/secp256k1/secp256k1/src/ecdsa_impl.h
Normal file
263
crypto/secp256k1/secp256k1/src/ecdsa_impl.h
Normal file
|
|
@ -0,0 +1,263 @@
|
|||
/**********************************************************************
|
||||
* Copyright (c) 2013, 2014 Pieter Wuille *
|
||||
* Distributed under the MIT software license, see the accompanying *
|
||||
* file COPYING or http://www.opensource.org/licenses/mit-license.php.*
|
||||
**********************************************************************/
|
||||
|
||||
|
||||
#ifndef _SECP256K1_ECDSA_IMPL_H_
|
||||
#define _SECP256K1_ECDSA_IMPL_H_
|
||||
|
||||
#include "scalar.h"
|
||||
#include "field.h"
|
||||
#include "group.h"
|
||||
#include "ecmult.h"
|
||||
#include "ecmult_gen.h"
|
||||
#include "ecdsa.h"
|
||||
|
||||
/** Group order for secp256k1 defined as 'n' in "Standards for Efficient Cryptography" (SEC2) 2.7.1
|
||||
* sage: for t in xrange(1023, -1, -1):
|
||||
* .. p = 2**256 - 2**32 - t
|
||||
* .. if p.is_prime():
|
||||
* .. print '%x'%p
|
||||
* .. break
|
||||
* 'fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'
|
||||
* sage: a = 0
|
||||
* sage: b = 7
|
||||
* sage: F = FiniteField (p)
|
||||
* sage: '%x' % (EllipticCurve ([F (a), F (b)]).order())
|
||||
* 'fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'
|
||||
*/
|
||||
static const secp256k1_fe_t secp256k1_ecdsa_const_order_as_fe = SECP256K1_FE_CONST(
|
||||
0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFEUL,
|
||||
0xBAAEDCE6UL, 0xAF48A03BUL, 0xBFD25E8CUL, 0xD0364141UL
|
||||
);
|
||||
|
||||
/** Difference between field and order, values 'p' and 'n' values defined in
|
||||
* "Standards for Efficient Cryptography" (SEC2) 2.7.1.
|
||||
* sage: p = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F
|
||||
* sage: a = 0
|
||||
* sage: b = 7
|
||||
* sage: F = FiniteField (p)
|
||||
* sage: '%x' % (p - EllipticCurve ([F (a), F (b)]).order())
|
||||
* '14551231950b75fc4402da1722fc9baee'
|
||||
*/
|
||||
static const secp256k1_fe_t secp256k1_ecdsa_const_p_minus_order = SECP256K1_FE_CONST(
|
||||
0, 0, 0, 1, 0x45512319UL, 0x50B75FC4UL, 0x402DA172UL, 0x2FC9BAEEUL
|
||||
);
|
||||
|
||||
static int secp256k1_ecdsa_sig_parse(secp256k1_ecdsa_sig_t *r, const unsigned char *sig, int size) {
|
||||
unsigned char ra[32] = {0}, sa[32] = {0};
|
||||
const unsigned char *rp;
|
||||
const unsigned char *sp;
|
||||
int lenr;
|
||||
int lens;
|
||||
int overflow;
|
||||
if (sig[0] != 0x30) {
|
||||
return 0;
|
||||
}
|
||||
lenr = sig[3];
|
||||
if (5+lenr >= size) {
|
||||
return 0;
|
||||
}
|
||||
lens = sig[lenr+5];
|
||||
if (sig[1] != lenr+lens+4) {
|
||||
return 0;
|
||||
}
|
||||
if (lenr+lens+6 > size) {
|
||||
return 0;
|
||||
}
|
||||
if (sig[2] != 0x02) {
|
||||
return 0;
|
||||
}
|
||||
if (lenr == 0) {
|
||||
return 0;
|
||||
}
|
||||
if (sig[lenr+4] != 0x02) {
|
||||
return 0;
|
||||
}
|
||||
if (lens == 0) {
|
||||
return 0;
|
||||
}
|
||||
sp = sig + 6 + lenr;
|
||||
while (lens > 0 && sp[0] == 0) {
|
||||
lens--;
|
||||
sp++;
|
||||
}
|
||||
if (lens > 32) {
|
||||
return 0;
|
||||
}
|
||||
rp = sig + 4;
|
||||
while (lenr > 0 && rp[0] == 0) {
|
||||
lenr--;
|
||||
rp++;
|
||||
}
|
||||
if (lenr > 32) {
|
||||
return 0;
|
||||
}
|
||||
memcpy(ra + 32 - lenr, rp, lenr);
|
||||
memcpy(sa + 32 - lens, sp, lens);
|
||||
overflow = 0;
|
||||
secp256k1_scalar_set_b32(&r->r, ra, &overflow);
|
||||
if (overflow) {
|
||||
return 0;
|
||||
}
|
||||
secp256k1_scalar_set_b32(&r->s, sa, &overflow);
|
||||
if (overflow) {
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int secp256k1_ecdsa_sig_serialize(unsigned char *sig, int *size, const secp256k1_ecdsa_sig_t *a) {
|
||||
unsigned char r[33] = {0}, s[33] = {0};
|
||||
unsigned char *rp = r, *sp = s;
|
||||
int lenR = 33, lenS = 33;
|
||||
secp256k1_scalar_get_b32(&r[1], &a->r);
|
||||
secp256k1_scalar_get_b32(&s[1], &a->s);
|
||||
while (lenR > 1 && rp[0] == 0 && rp[1] < 0x80) { lenR--; rp++; }
|
||||
while (lenS > 1 && sp[0] == 0 && sp[1] < 0x80) { lenS--; sp++; }
|
||||
if (*size < 6+lenS+lenR) {
|
||||
return 0;
|
||||
}
|
||||
*size = 6 + lenS + lenR;
|
||||
sig[0] = 0x30;
|
||||
sig[1] = 4 + lenS + lenR;
|
||||
sig[2] = 0x02;
|
||||
sig[3] = lenR;
|
||||
memcpy(sig+4, rp, lenR);
|
||||
sig[4+lenR] = 0x02;
|
||||
sig[5+lenR] = lenS;
|
||||
memcpy(sig+lenR+6, sp, lenS);
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int secp256k1_ecdsa_sig_verify(const secp256k1_ecdsa_sig_t *sig, const secp256k1_ge_t *pubkey, const secp256k1_scalar_t *message) {
|
||||
unsigned char c[32];
|
||||
secp256k1_scalar_t sn, u1, u2;
|
||||
secp256k1_fe_t xr;
|
||||
secp256k1_gej_t pubkeyj;
|
||||
secp256k1_gej_t pr;
|
||||
|
||||
if (secp256k1_scalar_is_zero(&sig->r) || secp256k1_scalar_is_zero(&sig->s)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
secp256k1_scalar_inverse_var(&sn, &sig->s);
|
||||
secp256k1_scalar_mul(&u1, &sn, message);
|
||||
secp256k1_scalar_mul(&u2, &sn, &sig->r);
|
||||
secp256k1_gej_set_ge(&pubkeyj, pubkey);
|
||||
secp256k1_ecmult(&pr, &pubkeyj, &u2, &u1);
|
||||
if (secp256k1_gej_is_infinity(&pr)) {
|
||||
return 0;
|
||||
}
|
||||
secp256k1_scalar_get_b32(c, &sig->r);
|
||||
secp256k1_fe_set_b32(&xr, c);
|
||||
|
||||
/** We now have the recomputed R point in pr, and its claimed x coordinate (modulo n)
|
||||
* in xr. Naively, we would extract the x coordinate from pr (requiring a inversion modulo p),
|
||||
* compute the remainder modulo n, and compare it to xr. However:
|
||||
*
|
||||
* xr == X(pr) mod n
|
||||
* <=> exists h. (xr + h * n < p && xr + h * n == X(pr))
|
||||
* [Since 2 * n > p, h can only be 0 or 1]
|
||||
* <=> (xr == X(pr)) || (xr + n < p && xr + n == X(pr))
|
||||
* [In Jacobian coordinates, X(pr) is pr.x / pr.z^2 mod p]
|
||||
* <=> (xr == pr.x / pr.z^2 mod p) || (xr + n < p && xr + n == pr.x / pr.z^2 mod p)
|
||||
* [Multiplying both sides of the equations by pr.z^2 mod p]
|
||||
* <=> (xr * pr.z^2 mod p == pr.x) || (xr + n < p && (xr + n) * pr.z^2 mod p == pr.x)
|
||||
*
|
||||
* Thus, we can avoid the inversion, but we have to check both cases separately.
|
||||
* secp256k1_gej_eq_x implements the (xr * pr.z^2 mod p == pr.x) test.
|
||||
*/
|
||||
if (secp256k1_gej_eq_x_var(&xr, &pr)) {
|
||||
/* xr.x == xr * xr.z^2 mod p, so the signature is valid. */
|
||||
return 1;
|
||||
}
|
||||
if (secp256k1_fe_cmp_var(&xr, &secp256k1_ecdsa_const_p_minus_order) >= 0) {
|
||||
/* xr + p >= n, so we can skip testing the second case. */
|
||||
return 0;
|
||||
}
|
||||
secp256k1_fe_add(&xr, &secp256k1_ecdsa_const_order_as_fe);
|
||||
if (secp256k1_gej_eq_x_var(&xr, &pr)) {
|
||||
/* (xr + n) * pr.z^2 mod p == pr.x, so the signature is valid. */
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int secp256k1_ecdsa_sig_recover(const secp256k1_ecdsa_sig_t *sig, secp256k1_ge_t *pubkey, const secp256k1_scalar_t *message, int recid) {
|
||||
unsigned char brx[32];
|
||||
secp256k1_fe_t fx;
|
||||
secp256k1_ge_t x;
|
||||
secp256k1_gej_t xj;
|
||||
secp256k1_scalar_t rn, u1, u2;
|
||||
secp256k1_gej_t qj;
|
||||
|
||||
if (secp256k1_scalar_is_zero(&sig->r) || secp256k1_scalar_is_zero(&sig->s)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
secp256k1_scalar_get_b32(brx, &sig->r);
|
||||
VERIFY_CHECK(secp256k1_fe_set_b32(&fx, brx)); /* brx comes from a scalar, so is less than the order; certainly less than p */
|
||||
if (recid & 2) {
|
||||
if (secp256k1_fe_cmp_var(&fx, &secp256k1_ecdsa_const_p_minus_order) >= 0) {
|
||||
return 0;
|
||||
}
|
||||
secp256k1_fe_add(&fx, &secp256k1_ecdsa_const_order_as_fe);
|
||||
}
|
||||
if (!secp256k1_ge_set_xo_var(&x, &fx, recid & 1)) {
|
||||
return 0;
|
||||
}
|
||||
secp256k1_gej_set_ge(&xj, &x);
|
||||
secp256k1_scalar_inverse_var(&rn, &sig->r);
|
||||
secp256k1_scalar_mul(&u1, &rn, message);
|
||||
secp256k1_scalar_negate(&u1, &u1);
|
||||
secp256k1_scalar_mul(&u2, &rn, &sig->s);
|
||||
secp256k1_ecmult(&qj, &xj, &u2, &u1);
|
||||
secp256k1_ge_set_gej_var(pubkey, &qj);
|
||||
return !secp256k1_gej_is_infinity(&qj);
|
||||
}
|
||||
|
||||
static int secp256k1_ecdsa_sig_sign(secp256k1_ecdsa_sig_t *sig, const secp256k1_scalar_t *seckey, const secp256k1_scalar_t *message, const secp256k1_scalar_t *nonce, int *recid) {
|
||||
unsigned char b[32];
|
||||
secp256k1_gej_t rp;
|
||||
secp256k1_ge_t r;
|
||||
secp256k1_scalar_t n;
|
||||
int overflow = 0;
|
||||
|
||||
secp256k1_ecmult_gen(&rp, nonce);
|
||||
secp256k1_ge_set_gej(&r, &rp);
|
||||
secp256k1_fe_normalize(&r.x);
|
||||
secp256k1_fe_normalize(&r.y);
|
||||
secp256k1_fe_get_b32(b, &r.x);
|
||||
secp256k1_scalar_set_b32(&sig->r, b, &overflow);
|
||||
if (secp256k1_scalar_is_zero(&sig->r)) {
|
||||
/* P.x = order is on the curve, so technically sig->r could end up zero, which would be an invalid signature. */
|
||||
secp256k1_gej_clear(&rp);
|
||||
secp256k1_ge_clear(&r);
|
||||
return 0;
|
||||
}
|
||||
if (recid) {
|
||||
*recid = (overflow ? 2 : 0) | (secp256k1_fe_is_odd(&r.y) ? 1 : 0);
|
||||
}
|
||||
secp256k1_scalar_mul(&n, &sig->r, seckey);
|
||||
secp256k1_scalar_add(&n, &n, message);
|
||||
secp256k1_scalar_inverse(&sig->s, nonce);
|
||||
secp256k1_scalar_mul(&sig->s, &sig->s, &n);
|
||||
secp256k1_scalar_clear(&n);
|
||||
secp256k1_gej_clear(&rp);
|
||||
secp256k1_ge_clear(&r);
|
||||
if (secp256k1_scalar_is_zero(&sig->s)) {
|
||||
return 0;
|
||||
}
|
||||
if (secp256k1_scalar_is_high(&sig->s)) {
|
||||
secp256k1_scalar_negate(&sig->s, &sig->s);
|
||||
if (recid) {
|
||||
*recid ^= 1;
|
||||
}
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
#endif
|
||||
24
crypto/secp256k1/secp256k1/src/eckey.h
Normal file
24
crypto/secp256k1/secp256k1/src/eckey.h
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
/**********************************************************************
|
||||
* Copyright (c) 2013, 2014 Pieter Wuille *
|
||||
* Distributed under the MIT software license, see the accompanying *
|
||||
* file COPYING or http://www.opensource.org/licenses/mit-license.php.*
|
||||
**********************************************************************/
|
||||
|
||||
#ifndef _SECP256K1_ECKEY_
|
||||
#define _SECP256K1_ECKEY_
|
||||
|
||||
#include "group.h"
|
||||
#include "scalar.h"
|
||||
|
||||
static int secp256k1_eckey_pubkey_parse(secp256k1_ge_t *elem, const unsigned char *pub, int size);
|
||||
static int secp256k1_eckey_pubkey_serialize(secp256k1_ge_t *elem, unsigned char *pub, int *size, int compressed);
|
||||
|
||||
static int secp256k1_eckey_privkey_parse(secp256k1_scalar_t *key, const unsigned char *privkey, int privkeylen);
|
||||
static int secp256k1_eckey_privkey_serialize(unsigned char *privkey, int *privkeylen, const secp256k1_scalar_t *key, int compressed);
|
||||
|
||||
static int secp256k1_eckey_privkey_tweak_add(secp256k1_scalar_t *key, const secp256k1_scalar_t *tweak);
|
||||
static int secp256k1_eckey_pubkey_tweak_add(secp256k1_ge_t *key, const secp256k1_scalar_t *tweak);
|
||||
static int secp256k1_eckey_privkey_tweak_mul(secp256k1_scalar_t *key, const secp256k1_scalar_t *tweak);
|
||||
static int secp256k1_eckey_pubkey_tweak_mul(secp256k1_ge_t *key, const secp256k1_scalar_t *tweak);
|
||||
|
||||
#endif
|
||||
202
crypto/secp256k1/secp256k1/src/eckey_impl.h
Normal file
202
crypto/secp256k1/secp256k1/src/eckey_impl.h
Normal file
|
|
@ -0,0 +1,202 @@
|
|||
/**********************************************************************
|
||||
* Copyright (c) 2013, 2014 Pieter Wuille *
|
||||
* Distributed under the MIT software license, see the accompanying *
|
||||
* file COPYING or http://www.opensource.org/licenses/mit-license.php.*
|
||||
**********************************************************************/
|
||||
|
||||
#ifndef _SECP256K1_ECKEY_IMPL_H_
|
||||
#define _SECP256K1_ECKEY_IMPL_H_
|
||||
|
||||
#include "eckey.h"
|
||||
|
||||
#include "scalar.h"
|
||||
#include "field.h"
|
||||
#include "group.h"
|
||||
#include "ecmult_gen.h"
|
||||
|
||||
static int secp256k1_eckey_pubkey_parse(secp256k1_ge_t *elem, const unsigned char *pub, int size) {
|
||||
if (size == 33 && (pub[0] == 0x02 || pub[0] == 0x03)) {
|
||||
secp256k1_fe_t x;
|
||||
return secp256k1_fe_set_b32(&x, pub+1) && secp256k1_ge_set_xo_var(elem, &x, pub[0] == 0x03);
|
||||
} else if (size == 65 && (pub[0] == 0x04 || pub[0] == 0x06 || pub[0] == 0x07)) {
|
||||
secp256k1_fe_t x, y;
|
||||
if (!secp256k1_fe_set_b32(&x, pub+1) || !secp256k1_fe_set_b32(&y, pub+33)) {
|
||||
return 0;
|
||||
}
|
||||
secp256k1_ge_set_xy(elem, &x, &y);
|
||||
if ((pub[0] == 0x06 || pub[0] == 0x07) && secp256k1_fe_is_odd(&y) != (pub[0] == 0x07)) {
|
||||
return 0;
|
||||
}
|
||||
return secp256k1_ge_is_valid_var(elem);
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
static int secp256k1_eckey_pubkey_serialize(secp256k1_ge_t *elem, unsigned char *pub, int *size, int compressed) {
|
||||
if (secp256k1_ge_is_infinity(elem)) {
|
||||
return 0;
|
||||
}
|
||||
secp256k1_fe_normalize_var(&elem->x);
|
||||
secp256k1_fe_normalize_var(&elem->y);
|
||||
secp256k1_fe_get_b32(&pub[1], &elem->x);
|
||||
if (compressed) {
|
||||
*size = 33;
|
||||
pub[0] = 0x02 | (secp256k1_fe_is_odd(&elem->y) ? 0x01 : 0x00);
|
||||
} else {
|
||||
*size = 65;
|
||||
pub[0] = 0x04;
|
||||
secp256k1_fe_get_b32(&pub[33], &elem->y);
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int secp256k1_eckey_privkey_parse(secp256k1_scalar_t *key, const unsigned char *privkey, int privkeylen) {
|
||||
unsigned char c[32] = {0};
|
||||
const unsigned char *end = privkey + privkeylen;
|
||||
int lenb = 0;
|
||||
int len = 0;
|
||||
int overflow = 0;
|
||||
/* sequence header */
|
||||
if (end < privkey+1 || *privkey != 0x30) {
|
||||
return 0;
|
||||
}
|
||||
privkey++;
|
||||
/* sequence length constructor */
|
||||
if (end < privkey+1 || !(*privkey & 0x80)) {
|
||||
return 0;
|
||||
}
|
||||
lenb = *privkey & ~0x80; privkey++;
|
||||
if (lenb < 1 || lenb > 2) {
|
||||
return 0;
|
||||
}
|
||||
if (end < privkey+lenb) {
|
||||
return 0;
|
||||
}
|
||||
/* sequence length */
|
||||
len = privkey[lenb-1] | (lenb > 1 ? privkey[lenb-2] << 8 : 0);
|
||||
privkey += lenb;
|
||||
if (end < privkey+len) {
|
||||
return 0;
|
||||
}
|
||||
/* sequence element 0: version number (=1) */
|
||||
if (end < privkey+3 || privkey[0] != 0x02 || privkey[1] != 0x01 || privkey[2] != 0x01) {
|
||||
return 0;
|
||||
}
|
||||
privkey += 3;
|
||||
/* sequence element 1: octet string, up to 32 bytes */
|
||||
if (end < privkey+2 || privkey[0] != 0x04 || privkey[1] > 0x20 || end < privkey+2+privkey[1]) {
|
||||
return 0;
|
||||
}
|
||||
memcpy(c + 32 - privkey[1], privkey + 2, privkey[1]);
|
||||
secp256k1_scalar_set_b32(key, c, &overflow);
|
||||
memset(c, 0, 32);
|
||||
return !overflow;
|
||||
}
|
||||
|
||||
static int secp256k1_eckey_privkey_serialize(unsigned char *privkey, int *privkeylen, const secp256k1_scalar_t *key, int compressed) {
|
||||
secp256k1_gej_t rp;
|
||||
secp256k1_ge_t r;
|
||||
int pubkeylen = 0;
|
||||
secp256k1_ecmult_gen(&rp, key);
|
||||
secp256k1_ge_set_gej(&r, &rp);
|
||||
if (compressed) {
|
||||
static const unsigned char begin[] = {
|
||||
0x30,0x81,0xD3,0x02,0x01,0x01,0x04,0x20
|
||||
};
|
||||
static const unsigned char middle[] = {
|
||||
0xA0,0x81,0x85,0x30,0x81,0x82,0x02,0x01,0x01,0x30,0x2C,0x06,0x07,0x2A,0x86,0x48,
|
||||
0xCE,0x3D,0x01,0x01,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
|
||||
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
|
||||
0xFF,0xFF,0xFE,0xFF,0xFF,0xFC,0x2F,0x30,0x06,0x04,0x01,0x00,0x04,0x01,0x07,0x04,
|
||||
0x21,0x02,0x79,0xBE,0x66,0x7E,0xF9,0xDC,0xBB,0xAC,0x55,0xA0,0x62,0x95,0xCE,0x87,
|
||||
0x0B,0x07,0x02,0x9B,0xFC,0xDB,0x2D,0xCE,0x28,0xD9,0x59,0xF2,0x81,0x5B,0x16,0xF8,
|
||||
0x17,0x98,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
|
||||
0xFF,0xFF,0xFF,0xFF,0xFE,0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B,0xBF,0xD2,0x5E,
|
||||
0x8C,0xD0,0x36,0x41,0x41,0x02,0x01,0x01,0xA1,0x24,0x03,0x22,0x00
|
||||
};
|
||||
unsigned char *ptr = privkey;
|
||||
memcpy(ptr, begin, sizeof(begin)); ptr += sizeof(begin);
|
||||
secp256k1_scalar_get_b32(ptr, key); ptr += 32;
|
||||
memcpy(ptr, middle, sizeof(middle)); ptr += sizeof(middle);
|
||||
if (!secp256k1_eckey_pubkey_serialize(&r, ptr, &pubkeylen, 1)) {
|
||||
return 0;
|
||||
}
|
||||
ptr += pubkeylen;
|
||||
*privkeylen = ptr - privkey;
|
||||
} else {
|
||||
static const unsigned char begin[] = {
|
||||
0x30,0x82,0x01,0x13,0x02,0x01,0x01,0x04,0x20
|
||||
};
|
||||
static const unsigned char middle[] = {
|
||||
0xA0,0x81,0xA5,0x30,0x81,0xA2,0x02,0x01,0x01,0x30,0x2C,0x06,0x07,0x2A,0x86,0x48,
|
||||
0xCE,0x3D,0x01,0x01,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
|
||||
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
|
||||
0xFF,0xFF,0xFE,0xFF,0xFF,0xFC,0x2F,0x30,0x06,0x04,0x01,0x00,0x04,0x01,0x07,0x04,
|
||||
0x41,0x04,0x79,0xBE,0x66,0x7E,0xF9,0xDC,0xBB,0xAC,0x55,0xA0,0x62,0x95,0xCE,0x87,
|
||||
0x0B,0x07,0x02,0x9B,0xFC,0xDB,0x2D,0xCE,0x28,0xD9,0x59,0xF2,0x81,0x5B,0x16,0xF8,
|
||||
0x17,0x98,0x48,0x3A,0xDA,0x77,0x26,0xA3,0xC4,0x65,0x5D,0xA4,0xFB,0xFC,0x0E,0x11,
|
||||
0x08,0xA8,0xFD,0x17,0xB4,0x48,0xA6,0x85,0x54,0x19,0x9C,0x47,0xD0,0x8F,0xFB,0x10,
|
||||
0xD4,0xB8,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
|
||||
0xFF,0xFF,0xFF,0xFF,0xFE,0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B,0xBF,0xD2,0x5E,
|
||||
0x8C,0xD0,0x36,0x41,0x41,0x02,0x01,0x01,0xA1,0x44,0x03,0x42,0x00
|
||||
};
|
||||
unsigned char *ptr = privkey;
|
||||
memcpy(ptr, begin, sizeof(begin)); ptr += sizeof(begin);
|
||||
secp256k1_scalar_get_b32(ptr, key); ptr += 32;
|
||||
memcpy(ptr, middle, sizeof(middle)); ptr += sizeof(middle);
|
||||
if (!secp256k1_eckey_pubkey_serialize(&r, ptr, &pubkeylen, 0)) {
|
||||
return 0;
|
||||
}
|
||||
ptr += pubkeylen;
|
||||
*privkeylen = ptr - privkey;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int secp256k1_eckey_privkey_tweak_add(secp256k1_scalar_t *key, const secp256k1_scalar_t *tweak) {
|
||||
secp256k1_scalar_add(key, key, tweak);
|
||||
if (secp256k1_scalar_is_zero(key)) {
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int secp256k1_eckey_pubkey_tweak_add(secp256k1_ge_t *key, const secp256k1_scalar_t *tweak) {
|
||||
secp256k1_gej_t pt;
|
||||
secp256k1_scalar_t one;
|
||||
secp256k1_gej_set_ge(&pt, key);
|
||||
secp256k1_scalar_set_int(&one, 1);
|
||||
secp256k1_ecmult(&pt, &pt, &one, tweak);
|
||||
|
||||
if (secp256k1_gej_is_infinity(&pt)) {
|
||||
return 0;
|
||||
}
|
||||
secp256k1_ge_set_gej(key, &pt);
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int secp256k1_eckey_privkey_tweak_mul(secp256k1_scalar_t *key, const secp256k1_scalar_t *tweak) {
|
||||
if (secp256k1_scalar_is_zero(tweak)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
secp256k1_scalar_mul(key, key, tweak);
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int secp256k1_eckey_pubkey_tweak_mul(secp256k1_ge_t *key, const secp256k1_scalar_t *tweak) {
|
||||
secp256k1_scalar_t zero;
|
||||
secp256k1_gej_t pt;
|
||||
if (secp256k1_scalar_is_zero(tweak)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
secp256k1_scalar_set_int(&zero, 0);
|
||||
secp256k1_gej_set_ge(&pt, key);
|
||||
secp256k1_ecmult(&pt, &pt, tweak, &zero);
|
||||
secp256k1_ge_set_gej(key, &pt);
|
||||
return 1;
|
||||
}
|
||||
|
||||
#endif
|
||||
|
|
@ -1,6 +1,8 @@
|
|||
// Copyright (c) 2013 Pieter Wuille
|
||||
// Distributed under the MIT/X11 software license, see the accompanying
|
||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||
/**********************************************************************
|
||||
* Copyright (c) 2013, 2014 Pieter Wuille *
|
||||
* Distributed under the MIT software license, see the accompanying *
|
||||
* file COPYING or http://www.opensource.org/licenses/mit-license.php.*
|
||||
**********************************************************************/
|
||||
|
||||
#ifndef _SECP256K1_ECMULT_
|
||||
#define _SECP256K1_ECMULT_
|
||||
|
|
@ -11,9 +13,7 @@
|
|||
static void secp256k1_ecmult_start(void);
|
||||
static void secp256k1_ecmult_stop(void);
|
||||
|
||||
/** Multiply with the generator: R = a*G */
|
||||
static void secp256k1_ecmult_gen(secp256k1_gej_t *r, const secp256k1_num_t *a);
|
||||
/** Double multiply: R = na*A + ng*G */
|
||||
static void secp256k1_ecmult(secp256k1_gej_t *r, const secp256k1_gej_t *a, const secp256k1_num_t *na, const secp256k1_num_t *ng);
|
||||
static void secp256k1_ecmult(secp256k1_gej_t *r, const secp256k1_gej_t *a, const secp256k1_scalar_t *na, const secp256k1_scalar_t *ng);
|
||||
|
||||
#endif
|
||||
|
|
|
|||
19
crypto/secp256k1/secp256k1/src/ecmult_gen.h
Normal file
19
crypto/secp256k1/secp256k1/src/ecmult_gen.h
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
/**********************************************************************
|
||||
* Copyright (c) 2013, 2014 Pieter Wuille *
|
||||
* Distributed under the MIT software license, see the accompanying *
|
||||
* file COPYING or http://www.opensource.org/licenses/mit-license.php.*
|
||||
**********************************************************************/
|
||||
|
||||
#ifndef _SECP256K1_ECMULT_GEN_
|
||||
#define _SECP256K1_ECMULT_GEN_
|
||||
|
||||
#include "scalar.h"
|
||||
#include "group.h"
|
||||
|
||||
static void secp256k1_ecmult_gen_start(void);
|
||||
static void secp256k1_ecmult_gen_stop(void);
|
||||
|
||||
/** Multiply with the generator: R = a*G */
|
||||
static void secp256k1_ecmult_gen(secp256k1_gej_t *r, const secp256k1_scalar_t *a);
|
||||
|
||||
#endif
|
||||
128
crypto/secp256k1/secp256k1/src/ecmult_gen_impl.h
Normal file
128
crypto/secp256k1/secp256k1/src/ecmult_gen_impl.h
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
/**********************************************************************
|
||||
* Copyright (c) 2013, 2014 Pieter Wuille *
|
||||
* Distributed under the MIT software license, see the accompanying *
|
||||
* file COPYING or http://www.opensource.org/licenses/mit-license.php.*
|
||||
**********************************************************************/
|
||||
|
||||
#ifndef _SECP256K1_ECMULT_GEN_IMPL_H_
|
||||
#define _SECP256K1_ECMULT_GEN_IMPL_H_
|
||||
|
||||
#include "scalar.h"
|
||||
#include "group.h"
|
||||
#include "ecmult_gen.h"
|
||||
|
||||
typedef struct {
|
||||
/* For accelerating the computation of a*G:
|
||||
* To harden against timing attacks, use the following mechanism:
|
||||
* * Break up the multiplicand into groups of 4 bits, called n_0, n_1, n_2, ..., n_63.
|
||||
* * Compute sum(n_i * 16^i * G + U_i, i=0..63), where:
|
||||
* * U_i = U * 2^i (for i=0..62)
|
||||
* * U_i = U * (1-2^63) (for i=63)
|
||||
* where U is a point with no known corresponding scalar. Note that sum(U_i, i=0..63) = 0.
|
||||
* For each i, and each of the 16 possible values of n_i, (n_i * 16^i * G + U_i) is
|
||||
* precomputed (call it prec(i, n_i)). The formula now becomes sum(prec(i, n_i), i=0..63).
|
||||
* None of the resulting prec group elements have a known scalar, and neither do any of
|
||||
* the intermediate sums while computing a*G.
|
||||
*/
|
||||
secp256k1_ge_storage_t prec[64][16]; /* prec[j][i] = 16^j * i * G + U_i */
|
||||
} secp256k1_ecmult_gen_consts_t;
|
||||
|
||||
static const secp256k1_ecmult_gen_consts_t *secp256k1_ecmult_gen_consts = NULL;
|
||||
|
||||
static void secp256k1_ecmult_gen_start(void) {
|
||||
secp256k1_ge_t prec[1024];
|
||||
secp256k1_gej_t gj;
|
||||
secp256k1_gej_t nums_gej;
|
||||
secp256k1_ecmult_gen_consts_t *ret;
|
||||
int i, j;
|
||||
if (secp256k1_ecmult_gen_consts != NULL) {
|
||||
return;
|
||||
}
|
||||
|
||||
/* Allocate the precomputation table. */
|
||||
ret = (secp256k1_ecmult_gen_consts_t*)checked_malloc(sizeof(secp256k1_ecmult_gen_consts_t));
|
||||
|
||||
/* get the generator */
|
||||
secp256k1_gej_set_ge(&gj, &secp256k1_ge_const_g);
|
||||
|
||||
/* Construct a group element with no known corresponding scalar (nothing up my sleeve). */
|
||||
{
|
||||
static const unsigned char nums_b32[33] = "The scalar for this x is unknown";
|
||||
secp256k1_fe_t nums_x;
|
||||
secp256k1_ge_t nums_ge;
|
||||
VERIFY_CHECK(secp256k1_fe_set_b32(&nums_x, nums_b32));
|
||||
VERIFY_CHECK(secp256k1_ge_set_xo_var(&nums_ge, &nums_x, 0));
|
||||
secp256k1_gej_set_ge(&nums_gej, &nums_ge);
|
||||
/* Add G to make the bits in x uniformly distributed. */
|
||||
secp256k1_gej_add_ge_var(&nums_gej, &nums_gej, &secp256k1_ge_const_g);
|
||||
}
|
||||
|
||||
/* compute prec. */
|
||||
{
|
||||
secp256k1_gej_t precj[1024]; /* Jacobian versions of prec. */
|
||||
secp256k1_gej_t gbase;
|
||||
secp256k1_gej_t numsbase;
|
||||
gbase = gj; /* 16^j * G */
|
||||
numsbase = nums_gej; /* 2^j * nums. */
|
||||
for (j = 0; j < 64; j++) {
|
||||
/* Set precj[j*16 .. j*16+15] to (numsbase, numsbase + gbase, ..., numsbase + 15*gbase). */
|
||||
precj[j*16] = numsbase;
|
||||
for (i = 1; i < 16; i++) {
|
||||
secp256k1_gej_add_var(&precj[j*16 + i], &precj[j*16 + i - 1], &gbase);
|
||||
}
|
||||
/* Multiply gbase by 16. */
|
||||
for (i = 0; i < 4; i++) {
|
||||
secp256k1_gej_double_var(&gbase, &gbase);
|
||||
}
|
||||
/* Multiply numbase by 2. */
|
||||
secp256k1_gej_double_var(&numsbase, &numsbase);
|
||||
if (j == 62) {
|
||||
/* In the last iteration, numsbase is (1 - 2^j) * nums instead. */
|
||||
secp256k1_gej_neg(&numsbase, &numsbase);
|
||||
secp256k1_gej_add_var(&numsbase, &numsbase, &nums_gej);
|
||||
}
|
||||
}
|
||||
secp256k1_ge_set_all_gej_var(1024, prec, precj);
|
||||
}
|
||||
for (j = 0; j < 64; j++) {
|
||||
for (i = 0; i < 16; i++) {
|
||||
secp256k1_ge_to_storage(&ret->prec[j][i], &prec[j*16 + i]);
|
||||
}
|
||||
}
|
||||
|
||||
/* Set the global pointer to the precomputation table. */
|
||||
secp256k1_ecmult_gen_consts = ret;
|
||||
}
|
||||
|
||||
static void secp256k1_ecmult_gen_stop(void) {
|
||||
secp256k1_ecmult_gen_consts_t *c;
|
||||
if (secp256k1_ecmult_gen_consts == NULL) {
|
||||
return;
|
||||
}
|
||||
|
||||
c = (secp256k1_ecmult_gen_consts_t*)secp256k1_ecmult_gen_consts;
|
||||
secp256k1_ecmult_gen_consts = NULL;
|
||||
free(c);
|
||||
}
|
||||
|
||||
static void secp256k1_ecmult_gen(secp256k1_gej_t *r, const secp256k1_scalar_t *gn) {
|
||||
const secp256k1_ecmult_gen_consts_t *c = secp256k1_ecmult_gen_consts;
|
||||
secp256k1_ge_t add;
|
||||
secp256k1_ge_storage_t adds;
|
||||
int bits;
|
||||
int i, j;
|
||||
secp256k1_gej_set_infinity(r);
|
||||
add.infinity = 0;
|
||||
for (j = 0; j < 64; j++) {
|
||||
bits = secp256k1_scalar_get_bits(gn, j * 4, 4);
|
||||
for (i = 0; i < 16; i++) {
|
||||
secp256k1_ge_storage_cmov(&adds, &c->prec[j][i], i == bits);
|
||||
}
|
||||
secp256k1_ge_from_storage(&add, &adds);
|
||||
secp256k1_gej_add_ge(r, r, &add);
|
||||
}
|
||||
bits = 0;
|
||||
secp256k1_ge_clear(&add);
|
||||
}
|
||||
|
||||
#endif
|
||||
302
crypto/secp256k1/secp256k1/src/ecmult_impl.h
Normal file
302
crypto/secp256k1/secp256k1/src/ecmult_impl.h
Normal file
|
|
@ -0,0 +1,302 @@
|
|||
/**********************************************************************
|
||||
* Copyright (c) 2013, 2014 Pieter Wuille *
|
||||
* Distributed under the MIT software license, see the accompanying *
|
||||
* file COPYING or http://www.opensource.org/licenses/mit-license.php.*
|
||||
**********************************************************************/
|
||||
|
||||
#ifndef _SECP256K1_ECMULT_IMPL_H_
|
||||
#define _SECP256K1_ECMULT_IMPL_H_
|
||||
|
||||
#include "group.h"
|
||||
#include "scalar.h"
|
||||
#include "ecmult.h"
|
||||
|
||||
/* optimal for 128-bit and 256-bit exponents. */
|
||||
#define WINDOW_A 5
|
||||
|
||||
/** larger numbers may result in slightly better performance, at the cost of
|
||||
exponentially larger precomputed tables. */
|
||||
#ifdef USE_ENDOMORPHISM
|
||||
/** Two tables for window size 15: 1.375 MiB. */
|
||||
#define WINDOW_G 15
|
||||
#else
|
||||
/** One table for window size 16: 1.375 MiB. */
|
||||
#define WINDOW_G 16
|
||||
#endif
|
||||
|
||||
/** Fill a table 'pre' with precomputed odd multiples of a. W determines the size of the table.
|
||||
* pre will contains the values [1*a,3*a,5*a,...,(2^(w-1)-1)*a], so it needs place for
|
||||
* 2^(w-2) entries.
|
||||
*
|
||||
* There are two versions of this function:
|
||||
* - secp256k1_ecmult_precomp_wnaf_gej, which operates on group elements in jacobian notation,
|
||||
* fast to precompute, but slower to use in later additions.
|
||||
* - secp256k1_ecmult_precomp_wnaf_ge, which operates on group elements in affine notations,
|
||||
* (much) slower to precompute, but a bit faster to use in later additions.
|
||||
* To compute a*P + b*G, we use the jacobian version for P, and the affine version for G, as
|
||||
* G is constant, so it only needs to be done once in advance.
|
||||
*/
|
||||
static void secp256k1_ecmult_table_precomp_gej_var(secp256k1_gej_t *pre, const secp256k1_gej_t *a, int w) {
|
||||
secp256k1_gej_t d;
|
||||
int i;
|
||||
pre[0] = *a;
|
||||
secp256k1_gej_double_var(&d, &pre[0]);
|
||||
for (i = 1; i < (1 << (w-2)); i++) {
|
||||
secp256k1_gej_add_var(&pre[i], &d, &pre[i-1]);
|
||||
}
|
||||
}
|
||||
|
||||
static void secp256k1_ecmult_table_precomp_ge_storage_var(secp256k1_ge_storage_t *pre, const secp256k1_gej_t *a, int w) {
|
||||
secp256k1_gej_t d;
|
||||
int i;
|
||||
const int table_size = 1 << (w-2);
|
||||
secp256k1_gej_t *prej = (secp256k1_gej_t *)checked_malloc(sizeof(secp256k1_gej_t) * table_size);
|
||||
secp256k1_ge_t *prea = (secp256k1_ge_t *)checked_malloc(sizeof(secp256k1_ge_t) * table_size);
|
||||
prej[0] = *a;
|
||||
secp256k1_gej_double_var(&d, a);
|
||||
for (i = 1; i < table_size; i++) {
|
||||
secp256k1_gej_add_var(&prej[i], &d, &prej[i-1]);
|
||||
}
|
||||
secp256k1_ge_set_all_gej_var(table_size, prea, prej);
|
||||
for (i = 0; i < table_size; i++) {
|
||||
secp256k1_ge_to_storage(&pre[i], &prea[i]);
|
||||
}
|
||||
free(prej);
|
||||
free(prea);
|
||||
}
|
||||
|
||||
/** The number of entries a table with precomputed multiples needs to have. */
|
||||
#define ECMULT_TABLE_SIZE(w) (1 << ((w)-2))
|
||||
|
||||
/** The following two macro retrieves a particular odd multiple from a table
|
||||
* of precomputed multiples. */
|
||||
#define ECMULT_TABLE_GET_GEJ(r,pre,n,w) do { \
|
||||
VERIFY_CHECK(((n) & 1) == 1); \
|
||||
VERIFY_CHECK((n) >= -((1 << ((w)-1)) - 1)); \
|
||||
VERIFY_CHECK((n) <= ((1 << ((w)-1)) - 1)); \
|
||||
if ((n) > 0) { \
|
||||
*(r) = (pre)[((n)-1)/2]; \
|
||||
} else { \
|
||||
secp256k1_gej_neg((r), &(pre)[(-(n)-1)/2]); \
|
||||
} \
|
||||
} while(0)
|
||||
#define ECMULT_TABLE_GET_GE_STORAGE(r,pre,n,w) do { \
|
||||
VERIFY_CHECK(((n) & 1) == 1); \
|
||||
VERIFY_CHECK((n) >= -((1 << ((w)-1)) - 1)); \
|
||||
VERIFY_CHECK((n) <= ((1 << ((w)-1)) - 1)); \
|
||||
if ((n) > 0) { \
|
||||
secp256k1_ge_from_storage((r), &(pre)[((n)-1)/2]); \
|
||||
} else { \
|
||||
secp256k1_ge_from_storage((r), &(pre)[(-(n)-1)/2]); \
|
||||
secp256k1_ge_neg((r), (r)); \
|
||||
} \
|
||||
} while(0)
|
||||
|
||||
typedef struct {
|
||||
/* For accelerating the computation of a*P + b*G: */
|
||||
secp256k1_ge_storage_t pre_g[ECMULT_TABLE_SIZE(WINDOW_G)]; /* odd multiples of the generator */
|
||||
#ifdef USE_ENDOMORPHISM
|
||||
secp256k1_ge_storage_t pre_g_128[ECMULT_TABLE_SIZE(WINDOW_G)]; /* odd multiples of 2^128*generator */
|
||||
#endif
|
||||
} secp256k1_ecmult_consts_t;
|
||||
|
||||
static const secp256k1_ecmult_consts_t *secp256k1_ecmult_consts = NULL;
|
||||
|
||||
static void secp256k1_ecmult_start(void) {
|
||||
secp256k1_gej_t gj;
|
||||
secp256k1_ecmult_consts_t *ret;
|
||||
if (secp256k1_ecmult_consts != NULL) {
|
||||
return;
|
||||
}
|
||||
|
||||
/* Allocate the precomputation table. */
|
||||
ret = (secp256k1_ecmult_consts_t*)checked_malloc(sizeof(secp256k1_ecmult_consts_t));
|
||||
|
||||
/* get the generator */
|
||||
secp256k1_gej_set_ge(&gj, &secp256k1_ge_const_g);
|
||||
|
||||
|
||||
/* precompute the tables with odd multiples */
|
||||
secp256k1_ecmult_table_precomp_ge_storage_var(ret->pre_g, &gj, WINDOW_G);
|
||||
|
||||
#ifdef USE_ENDOMORPHISM
|
||||
{
|
||||
secp256k1_gej_t g_128j;
|
||||
int i;
|
||||
/* calculate 2^128*generator */
|
||||
g_128j = gj;
|
||||
for (i = 0; i < 128; i++) {
|
||||
secp256k1_gej_double_var(&g_128j, &g_128j);
|
||||
}
|
||||
secp256k1_ecmult_table_precomp_ge_storage_var(ret->pre_g_128, &g_128j, WINDOW_G);
|
||||
}
|
||||
#endif
|
||||
|
||||
/* Set the global pointer to the precomputation table. */
|
||||
secp256k1_ecmult_consts = ret;
|
||||
}
|
||||
|
||||
static void secp256k1_ecmult_stop(void) {
|
||||
secp256k1_ecmult_consts_t *c;
|
||||
if (secp256k1_ecmult_consts == NULL) {
|
||||
return;
|
||||
}
|
||||
|
||||
c = (secp256k1_ecmult_consts_t*)secp256k1_ecmult_consts;
|
||||
secp256k1_ecmult_consts = NULL;
|
||||
free(c);
|
||||
}
|
||||
|
||||
/** Convert a number to WNAF notation. The number becomes represented by sum(2^i * wnaf[i], i=0..bits),
|
||||
* with the following guarantees:
|
||||
* - each wnaf[i] is either 0, or an odd integer between -(1<<(w-1) - 1) and (1<<(w-1) - 1)
|
||||
* - two non-zero entries in wnaf are separated by at least w-1 zeroes.
|
||||
* - the number of set values in wnaf is returned. This number is at most 256, and at most one more
|
||||
* - than the number of bits in the (absolute value) of the input.
|
||||
*/
|
||||
static int secp256k1_ecmult_wnaf(int *wnaf, const secp256k1_scalar_t *a, int w) {
|
||||
secp256k1_scalar_t s = *a;
|
||||
int set_bits = 0;
|
||||
int bit = 0;
|
||||
int sign = 1;
|
||||
|
||||
if (secp256k1_scalar_get_bits(&s, 255, 1)) {
|
||||
secp256k1_scalar_negate(&s, &s);
|
||||
sign = -1;
|
||||
}
|
||||
|
||||
while (bit < 256) {
|
||||
int now;
|
||||
int word;
|
||||
if (secp256k1_scalar_get_bits(&s, bit, 1) == 0) {
|
||||
bit++;
|
||||
continue;
|
||||
}
|
||||
while (set_bits < bit) {
|
||||
wnaf[set_bits++] = 0;
|
||||
}
|
||||
now = w;
|
||||
if (bit + now > 256) {
|
||||
now = 256 - bit;
|
||||
}
|
||||
word = secp256k1_scalar_get_bits_var(&s, bit, now);
|
||||
if (word & (1 << (w-1))) {
|
||||
secp256k1_scalar_add_bit(&s, bit + w);
|
||||
wnaf[set_bits++] = sign * (word - (1 << w));
|
||||
} else {
|
||||
wnaf[set_bits++] = sign * word;
|
||||
}
|
||||
bit += now;
|
||||
}
|
||||
return set_bits;
|
||||
}
|
||||
|
||||
static void secp256k1_ecmult(secp256k1_gej_t *r, const secp256k1_gej_t *a, const secp256k1_scalar_t *na, const secp256k1_scalar_t *ng) {
|
||||
secp256k1_gej_t tmpj;
|
||||
secp256k1_gej_t pre_a[ECMULT_TABLE_SIZE(WINDOW_A)];
|
||||
secp256k1_ge_t tmpa;
|
||||
const secp256k1_ecmult_consts_t *c = secp256k1_ecmult_consts;
|
||||
#ifdef USE_ENDOMORPHISM
|
||||
secp256k1_gej_t pre_a_lam[ECMULT_TABLE_SIZE(WINDOW_A)];
|
||||
secp256k1_scalar_t na_1, na_lam;
|
||||
/* Splitted G factors. */
|
||||
secp256k1_scalar_t ng_1, ng_128;
|
||||
int wnaf_na_1[130];
|
||||
int wnaf_na_lam[130];
|
||||
int bits_na_1;
|
||||
int bits_na_lam;
|
||||
int wnaf_ng_1[129];
|
||||
int bits_ng_1;
|
||||
int wnaf_ng_128[129];
|
||||
int bits_ng_128;
|
||||
#else
|
||||
int wnaf_na[256];
|
||||
int bits_na;
|
||||
int wnaf_ng[257];
|
||||
int bits_ng;
|
||||
#endif
|
||||
int i;
|
||||
int bits;
|
||||
|
||||
#ifdef USE_ENDOMORPHISM
|
||||
/* split na into na_1 and na_lam (where na = na_1 + na_lam*lambda, and na_1 and na_lam are ~128 bit) */
|
||||
secp256k1_scalar_split_lambda_var(&na_1, &na_lam, na);
|
||||
|
||||
/* build wnaf representation for na_1 and na_lam. */
|
||||
bits_na_1 = secp256k1_ecmult_wnaf(wnaf_na_1, &na_1, WINDOW_A);
|
||||
bits_na_lam = secp256k1_ecmult_wnaf(wnaf_na_lam, &na_lam, WINDOW_A);
|
||||
VERIFY_CHECK(bits_na_1 <= 130);
|
||||
VERIFY_CHECK(bits_na_lam <= 130);
|
||||
bits = bits_na_1;
|
||||
if (bits_na_lam > bits) {
|
||||
bits = bits_na_lam;
|
||||
}
|
||||
#else
|
||||
/* build wnaf representation for na. */
|
||||
bits_na = secp256k1_ecmult_wnaf(wnaf_na, na, WINDOW_A);
|
||||
bits = bits_na;
|
||||
#endif
|
||||
|
||||
/* calculate odd multiples of a */
|
||||
secp256k1_ecmult_table_precomp_gej_var(pre_a, a, WINDOW_A);
|
||||
|
||||
#ifdef USE_ENDOMORPHISM
|
||||
for (i = 0; i < ECMULT_TABLE_SIZE(WINDOW_A); i++) {
|
||||
secp256k1_gej_mul_lambda(&pre_a_lam[i], &pre_a[i]);
|
||||
}
|
||||
|
||||
/* split ng into ng_1 and ng_128 (where gn = gn_1 + gn_128*2^128, and gn_1 and gn_128 are ~128 bit) */
|
||||
secp256k1_scalar_split_128(&ng_1, &ng_128, ng);
|
||||
|
||||
/* Build wnaf representation for ng_1 and ng_128 */
|
||||
bits_ng_1 = secp256k1_ecmult_wnaf(wnaf_ng_1, &ng_1, WINDOW_G);
|
||||
bits_ng_128 = secp256k1_ecmult_wnaf(wnaf_ng_128, &ng_128, WINDOW_G);
|
||||
if (bits_ng_1 > bits) {
|
||||
bits = bits_ng_1;
|
||||
}
|
||||
if (bits_ng_128 > bits) {
|
||||
bits = bits_ng_128;
|
||||
}
|
||||
#else
|
||||
bits_ng = secp256k1_ecmult_wnaf(wnaf_ng, ng, WINDOW_G);
|
||||
if (bits_ng > bits) {
|
||||
bits = bits_ng;
|
||||
}
|
||||
#endif
|
||||
|
||||
secp256k1_gej_set_infinity(r);
|
||||
|
||||
for (i = bits-1; i >= 0; i--) {
|
||||
int n;
|
||||
secp256k1_gej_double_var(r, r);
|
||||
#ifdef USE_ENDOMORPHISM
|
||||
if (i < bits_na_1 && (n = wnaf_na_1[i])) {
|
||||
ECMULT_TABLE_GET_GEJ(&tmpj, pre_a, n, WINDOW_A);
|
||||
secp256k1_gej_add_var(r, r, &tmpj);
|
||||
}
|
||||
if (i < bits_na_lam && (n = wnaf_na_lam[i])) {
|
||||
ECMULT_TABLE_GET_GEJ(&tmpj, pre_a_lam, n, WINDOW_A);
|
||||
secp256k1_gej_add_var(r, r, &tmpj);
|
||||
}
|
||||
if (i < bits_ng_1 && (n = wnaf_ng_1[i])) {
|
||||
ECMULT_TABLE_GET_GE_STORAGE(&tmpa, c->pre_g, n, WINDOW_G);
|
||||
secp256k1_gej_add_ge_var(r, r, &tmpa);
|
||||
}
|
||||
if (i < bits_ng_128 && (n = wnaf_ng_128[i])) {
|
||||
ECMULT_TABLE_GET_GE_STORAGE(&tmpa, c->pre_g_128, n, WINDOW_G);
|
||||
secp256k1_gej_add_ge_var(r, r, &tmpa);
|
||||
}
|
||||
#else
|
||||
if (i < bits_na && (n = wnaf_na[i])) {
|
||||
ECMULT_TABLE_GET_GEJ(&tmpj, pre_a, n, WINDOW_A);
|
||||
secp256k1_gej_add_var(r, r, &tmpj);
|
||||
}
|
||||
if (i < bits_ng && (n = wnaf_ng[i])) {
|
||||
ECMULT_TABLE_GET_GE_STORAGE(&tmpa, c->pre_g, n, WINDOW_G);
|
||||
secp256k1_gej_add_ge_var(r, r, &tmpa);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
|
|
@ -1,6 +1,8 @@
|
|||
// Copyright (c) 2013 Pieter Wuille
|
||||
// Distributed under the MIT/X11 software license, see the accompanying
|
||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||
/**********************************************************************
|
||||
* Copyright (c) 2013, 2014 Pieter Wuille *
|
||||
* Distributed under the MIT software license, see the accompanying *
|
||||
* file COPYING or http://www.opensource.org/licenses/mit-license.php.*
|
||||
**********************************************************************/
|
||||
|
||||
#ifndef _SECP256K1_FIELD_
|
||||
#define _SECP256K1_FIELD_
|
||||
|
|
@ -16,86 +18,99 @@
|
|||
* normality.
|
||||
*/
|
||||
|
||||
#if defined(USE_FIELD_GMP)
|
||||
#include "field_gmp.h"
|
||||
#elif defined(USE_FIELD_10X26)
|
||||
#if defined HAVE_CONFIG_H
|
||||
#include "libsecp256k1-config.h"
|
||||
#endif
|
||||
|
||||
#if defined(USE_FIELD_10X26)
|
||||
#include "field_10x26.h"
|
||||
#elif defined(USE_FIELD_5X52)
|
||||
#include "field_5x52.h"
|
||||
#elif defined(USE_FIELD_5X64)
|
||||
#include "field_5x64.h"
|
||||
#else
|
||||
#error "Please select field implementation"
|
||||
#endif
|
||||
|
||||
typedef struct {
|
||||
secp256k1_num_t p;
|
||||
} secp256k1_fe_consts_t;
|
||||
|
||||
static const secp256k1_fe_consts_t *secp256k1_fe_consts = NULL;
|
||||
|
||||
/** Initialize field element precomputation data. */
|
||||
void static secp256k1_fe_start(void);
|
||||
|
||||
/** Unload field element precomputation data. */
|
||||
void static secp256k1_fe_stop(void);
|
||||
|
||||
/** Normalize a field element. */
|
||||
void static secp256k1_fe_normalize(secp256k1_fe_t *r);
|
||||
static void secp256k1_fe_normalize(secp256k1_fe_t *r);
|
||||
|
||||
/** Weakly normalize a field element: reduce it magnitude to 1, but don't fully normalize. */
|
||||
static void secp256k1_fe_normalize_weak(secp256k1_fe_t *r);
|
||||
|
||||
/** Normalize a field element, without constant-time guarantee. */
|
||||
static void secp256k1_fe_normalize_var(secp256k1_fe_t *r);
|
||||
|
||||
/** Verify whether a field element represents zero i.e. would normalize to a zero value. The field
|
||||
* implementation may optionally normalize the input, but this should not be relied upon. */
|
||||
static int secp256k1_fe_normalizes_to_zero(secp256k1_fe_t *r);
|
||||
|
||||
/** Verify whether a field element represents zero i.e. would normalize to a zero value. The field
|
||||
* implementation may optionally normalize the input, but this should not be relied upon. */
|
||||
static int secp256k1_fe_normalizes_to_zero_var(secp256k1_fe_t *r);
|
||||
|
||||
/** Set a field element equal to a small integer. Resulting field element is normalized. */
|
||||
void static secp256k1_fe_set_int(secp256k1_fe_t *r, int a);
|
||||
static void secp256k1_fe_set_int(secp256k1_fe_t *r, int a);
|
||||
|
||||
/** Verify whether a field element is zero. Requires the input to be normalized. */
|
||||
int static secp256k1_fe_is_zero(const secp256k1_fe_t *a);
|
||||
static int secp256k1_fe_is_zero(const secp256k1_fe_t *a);
|
||||
|
||||
/** Check the "oddness" of a field element. Requires the input to be normalized. */
|
||||
int static secp256k1_fe_is_odd(const secp256k1_fe_t *a);
|
||||
static int secp256k1_fe_is_odd(const secp256k1_fe_t *a);
|
||||
|
||||
/** Compare two field elements. Requires magnitude-1 inputs. */
|
||||
static int secp256k1_fe_equal_var(const secp256k1_fe_t *a, const secp256k1_fe_t *b);
|
||||
|
||||
/** Compare two field elements. Requires both inputs to be normalized */
|
||||
int static secp256k1_fe_equal(const secp256k1_fe_t *a, const secp256k1_fe_t *b);
|
||||
static int secp256k1_fe_cmp_var(const secp256k1_fe_t *a, const secp256k1_fe_t *b);
|
||||
|
||||
/** Set a field element equal to 32-byte big endian value. Resulting field element is normalized. */
|
||||
void static secp256k1_fe_set_b32(secp256k1_fe_t *r, const unsigned char *a);
|
||||
/** Set a field element equal to 32-byte big endian value. If succesful, the resulting field element is normalized. */
|
||||
static int secp256k1_fe_set_b32(secp256k1_fe_t *r, const unsigned char *a);
|
||||
|
||||
/** Convert a field element to a 32-byte big endian value. Requires the input to be normalized */
|
||||
void static secp256k1_fe_get_b32(unsigned char *r, const secp256k1_fe_t *a);
|
||||
static void secp256k1_fe_get_b32(unsigned char *r, const secp256k1_fe_t *a);
|
||||
|
||||
/** Set a field element equal to the additive inverse of another. Takes a maximum magnitude of the input
|
||||
* as an argument. The magnitude of the output is one higher. */
|
||||
void static secp256k1_fe_negate(secp256k1_fe_t *r, const secp256k1_fe_t *a, int m);
|
||||
static void secp256k1_fe_negate(secp256k1_fe_t *r, const secp256k1_fe_t *a, int m);
|
||||
|
||||
/** Multiplies the passed field element with a small integer constant. Multiplies the magnitude by that
|
||||
* small integer. */
|
||||
void static secp256k1_fe_mul_int(secp256k1_fe_t *r, int a);
|
||||
static void secp256k1_fe_mul_int(secp256k1_fe_t *r, int a);
|
||||
|
||||
/** Adds a field element to another. The result has the sum of the inputs' magnitudes as magnitude. */
|
||||
void static secp256k1_fe_add(secp256k1_fe_t *r, const secp256k1_fe_t *a);
|
||||
static void secp256k1_fe_add(secp256k1_fe_t *r, const secp256k1_fe_t *a);
|
||||
|
||||
/** Sets a field element to be the product of two others. Requires the inputs' magnitudes to be at most 8.
|
||||
* The output magnitude is 1 (but not guaranteed to be normalized). */
|
||||
void static secp256k1_fe_mul(secp256k1_fe_t *r, const secp256k1_fe_t *a, const secp256k1_fe_t *b);
|
||||
static void secp256k1_fe_mul(secp256k1_fe_t *r, const secp256k1_fe_t *a, const secp256k1_fe_t * SECP256K1_RESTRICT b);
|
||||
|
||||
/** Sets a field element to be the square of another. Requires the input's magnitude to be at most 8.
|
||||
* The output magnitude is 1 (but not guaranteed to be normalized). */
|
||||
void static secp256k1_fe_sqr(secp256k1_fe_t *r, const secp256k1_fe_t *a);
|
||||
static void secp256k1_fe_sqr(secp256k1_fe_t *r, const secp256k1_fe_t *a);
|
||||
|
||||
/** Sets a field element to be the (modular) square root of another. Requires the inputs' magnitude to
|
||||
* be at most 8. The output magnitude is 1 (but not guaranteed to be normalized). */
|
||||
void static secp256k1_fe_sqrt(secp256k1_fe_t *r, const secp256k1_fe_t *a);
|
||||
/** Sets a field element to be the (modular) square root (if any exist) of another. Requires the
|
||||
* input's magnitude to be at most 8. The output magnitude is 1 (but not guaranteed to be
|
||||
* normalized). Return value indicates whether a square root was found. */
|
||||
static int secp256k1_fe_sqrt_var(secp256k1_fe_t *r, const secp256k1_fe_t *a);
|
||||
|
||||
/** Sets a field element to be the (modular) inverse of another. Requires the input's magnitude to be
|
||||
* at most 8. The output magnitude is 1 (but not guaranteed to be normalized). */
|
||||
void static secp256k1_fe_inv(secp256k1_fe_t *r, const secp256k1_fe_t *a);
|
||||
static void secp256k1_fe_inv(secp256k1_fe_t *r, const secp256k1_fe_t *a);
|
||||
|
||||
/** Potentially faster version of secp256k1_fe_inv, without constant-time guarantee. */
|
||||
void static secp256k1_fe_inv_var(secp256k1_fe_t *r, const secp256k1_fe_t *a);
|
||||
static void secp256k1_fe_inv_var(secp256k1_fe_t *r, const secp256k1_fe_t *a);
|
||||
|
||||
/** Calculate the (modular) inverses of a batch of field elements. Requires the inputs' magnitudes to be
|
||||
* at most 8. The output magnitudes are 1 (but not guaranteed to be normalized). The inputs and
|
||||
* outputs must not overlap in memory. */
|
||||
static void secp256k1_fe_inv_all_var(size_t len, secp256k1_fe_t *r, const secp256k1_fe_t *a);
|
||||
|
||||
/** Convert a field element to a hexadecimal string. */
|
||||
void static secp256k1_fe_get_hex(char *r, int *rlen, const secp256k1_fe_t *a);
|
||||
/** Convert a field element to the storage type. */
|
||||
static void secp256k1_fe_to_storage(secp256k1_fe_storage_t *r, const secp256k1_fe_t*);
|
||||
|
||||
/** Convert a hexadecimal string to a field element. */
|
||||
void static secp256k1_fe_set_hex(secp256k1_fe_t *r, const char *a, int alen);
|
||||
/** Convert a field element back from the storage type. */
|
||||
static void secp256k1_fe_from_storage(secp256k1_fe_t *r, const secp256k1_fe_storage_t*);
|
||||
|
||||
/** If flag is true, set *r equal to *a; otherwise leave it. Constant-time. */
|
||||
static void secp256k1_fe_storage_cmov(secp256k1_fe_storage_t *r, const secp256k1_fe_storage_t *a, int flag);
|
||||
|
||||
#endif
|
||||
|
|
|
|||
|
|
@ -1,6 +1,8 @@
|
|||
// Copyright (c) 2013 Pieter Wuille
|
||||
// Distributed under the MIT/X11 software license, see the accompanying
|
||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||
/**********************************************************************
|
||||
* Copyright (c) 2013, 2014 Pieter Wuille *
|
||||
* Distributed under the MIT software license, see the accompanying *
|
||||
* file COPYING or http://www.opensource.org/licenses/mit-license.php.*
|
||||
**********************************************************************/
|
||||
|
||||
#ifndef _SECP256K1_FIELD_REPR_
|
||||
#define _SECP256K1_FIELD_REPR_
|
||||
|
|
@ -8,7 +10,7 @@
|
|||
#include <stdint.h>
|
||||
|
||||
typedef struct {
|
||||
// X = sum(i=0..9, elem[i]*2^26) mod n
|
||||
/* X = sum(i=0..9, elem[i]*2^26) mod n */
|
||||
uint32_t n[10];
|
||||
#ifdef VERIFY
|
||||
int magnitude;
|
||||
|
|
@ -16,4 +18,30 @@ typedef struct {
|
|||
#endif
|
||||
} secp256k1_fe_t;
|
||||
|
||||
/* Unpacks a constant into a overlapping multi-limbed FE element. */
|
||||
#define SECP256K1_FE_CONST_INNER(d7, d6, d5, d4, d3, d2, d1, d0) { \
|
||||
(d0) & 0x3FFFFFFUL, \
|
||||
((d0) >> 26) | ((d1) & 0xFFFFFUL) << 6, \
|
||||
((d1) >> 20) | ((d2) & 0x3FFFUL) << 12, \
|
||||
((d2) >> 14) | ((d3) & 0xFFUL) << 18, \
|
||||
((d3) >> 8) | ((d4) & 0x3) << 24, \
|
||||
((d4) >> 2) & 0x3FFFFFFUL, \
|
||||
((d4) >> 28) | ((d5) & 0x3FFFFFUL) << 4, \
|
||||
((d5) >> 22) | ((d6) & 0xFFFF) << 10, \
|
||||
((d6) >> 16) | ((d7) & 0x3FF) << 16, \
|
||||
((d7) >> 10) \
|
||||
}
|
||||
|
||||
#ifdef VERIFY
|
||||
#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}
|
||||
#else
|
||||
#define SECP256K1_FE_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {SECP256K1_FE_CONST_INNER((d7), (d6), (d5), (d4), (d3), (d2), (d1), (d0))}
|
||||
#endif
|
||||
|
||||
typedef struct {
|
||||
uint32_t n[8];
|
||||
} secp256k1_fe_storage_t;
|
||||
|
||||
#define SECP256K1_FE_STORAGE_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {{ (d0), (d1), (d2), (d3), (d4), (d5), (d6), (d7) }}
|
||||
|
||||
#endif
|
||||
|
|
|
|||
1116
crypto/secp256k1/secp256k1/src/field_10x26_impl.h
Normal file
1116
crypto/secp256k1/secp256k1/src/field_10x26_impl.h
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -1,6 +1,8 @@
|
|||
// Copyright (c) 2013 Pieter Wuille
|
||||
// Distributed under the MIT/X11 software license, see the accompanying
|
||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||
/**********************************************************************
|
||||
* Copyright (c) 2013, 2014 Pieter Wuille *
|
||||
* Distributed under the MIT software license, see the accompanying *
|
||||
* file COPYING or http://www.opensource.org/licenses/mit-license.php.*
|
||||
**********************************************************************/
|
||||
|
||||
#ifndef _SECP256K1_FIELD_REPR_
|
||||
#define _SECP256K1_FIELD_REPR_
|
||||
|
|
@ -8,7 +10,7 @@
|
|||
#include <stdint.h>
|
||||
|
||||
typedef struct {
|
||||
// X = sum(i=0..4, elem[i]*2^52) mod n
|
||||
/* X = sum(i=0..4, elem[i]*2^52) mod n */
|
||||
uint64_t n[5];
|
||||
#ifdef VERIFY
|
||||
int magnitude;
|
||||
|
|
@ -16,4 +18,30 @@ typedef struct {
|
|||
#endif
|
||||
} secp256k1_fe_t;
|
||||
|
||||
/* Unpacks a constant into a overlapping multi-limbed FE element. */
|
||||
#define SECP256K1_FE_CONST_INNER(d7, d6, d5, d4, d3, d2, d1, d0) { \
|
||||
(d0) | ((uint64_t)(d1) & 0xFFFFFUL) << 32, \
|
||||
((d1) >> 20) | ((uint64_t)(d2)) << 12 | ((uint64_t)(d3) & 0xFFUL) << 44, \
|
||||
((d3) >> 8) | ((uint64_t)(d4) & 0xFFFFFFFUL) << 24, \
|
||||
((d4) >> 28) | ((uint64_t)(d5)) << 4 | ((uint64_t)(d6) & 0xFFFFUL) << 36, \
|
||||
((d6) >> 16) | ((uint64_t)(d7)) << 16 \
|
||||
}
|
||||
|
||||
#ifdef VERIFY
|
||||
#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}
|
||||
#else
|
||||
#define SECP256K1_FE_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {SECP256K1_FE_CONST_INNER((d7), (d6), (d5), (d4), (d3), (d2), (d1), (d0))}
|
||||
#endif
|
||||
|
||||
typedef struct {
|
||||
uint64_t n[4];
|
||||
} secp256k1_fe_storage_t;
|
||||
|
||||
#define SECP256K1_FE_STORAGE_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {{ \
|
||||
(d0) | ((uint64_t)(d1)) << 32, \
|
||||
(d2) | ((uint64_t)(d3)) << 32, \
|
||||
(d4) | ((uint64_t)(d5)) << 32, \
|
||||
(d6) | ((uint64_t)(d7)) << 32 \
|
||||
}}
|
||||
|
||||
#endif
|
||||
|
|
|
|||
|
|
@ -1,463 +0,0 @@
|
|||
;; Added by Diederik Huys, March 2013
|
||||
;;
|
||||
;; Provided public procedures:
|
||||
;; secp256k1_fe_mul_inner
|
||||
;; secp256k1_fe_sqr_inner
|
||||
;;
|
||||
;; Needed tools: YASM (http://yasm.tortall.net)
|
||||
;;
|
||||
;;
|
||||
|
||||
BITS 64
|
||||
|
||||
;; Procedure ExSetMult
|
||||
;; Register Layout:
|
||||
;; INPUT: rdi = a->n
|
||||
;; rsi = b->n
|
||||
;; rdx = r->a
|
||||
;;
|
||||
;; INTERNAL: rdx:rax = multiplication accumulator
|
||||
;; r9:r8 = c
|
||||
;; r10-r13 = t0-t3
|
||||
;; r14 = b.n[0] / t4
|
||||
;; r15 = b.n[1] / t5
|
||||
;; rbx = b.n[2] / t6
|
||||
;; rcx = b.n[3] / t7
|
||||
;; rbp = Constant 0FFFFFFFFFFFFFh / t8
|
||||
;; rsi = b.n / b.n[4] / t9
|
||||
|
||||
GLOBAL secp256k1_fe_mul_inner
|
||||
ALIGN 32
|
||||
secp256k1_fe_mul_inner:
|
||||
push rbp
|
||||
push rbx
|
||||
push r12
|
||||
push r13
|
||||
push r14
|
||||
push r15
|
||||
push rdx
|
||||
mov r14,[rsi+8*0] ; preload b.n[0]. This will be the case until
|
||||
; b.n[0] is no longer needed, then we reassign
|
||||
; r14 to t4
|
||||
;; c=a.n[0] * b.n[0]
|
||||
mov rax,[rdi+0*8] ; load a.n[0]
|
||||
mov rbp,0FFFFFFFFFFFFFh
|
||||
mul r14 ; rdx:rax=a.n[0]*b.n[0]
|
||||
mov r15,[rsi+1*8]
|
||||
mov r10,rbp ; load modulus into target register for t0
|
||||
mov r8,rax
|
||||
and r10,rax ; only need lower qword of c
|
||||
shrd r8,rdx,52
|
||||
xor r9,r9 ; c < 2^64, so we ditch the HO part
|
||||
|
||||
;; c+=a.n[0] * b.n[1] + a.n[1] * b.n[0]
|
||||
mov rax,[rdi+0*8]
|
||||
mul r15
|
||||
add r8,rax
|
||||
adc r9,rdx
|
||||
|
||||
mov rax,[rdi+1*8]
|
||||
mul r14
|
||||
mov r11,rbp
|
||||
mov rbx,[rsi+2*8]
|
||||
add r8,rax
|
||||
adc r9,rdx
|
||||
and r11,r8
|
||||
shrd r8,r9,52
|
||||
xor r9,r9
|
||||
|
||||
;; c+=a.n[0 1 2] * b.n[2 1 0]
|
||||
mov rax,[rdi+0*8]
|
||||
mul rbx
|
||||
add r8,rax
|
||||
adc r9,rdx
|
||||
|
||||
mov rax,[rdi+1*8]
|
||||
mul r15
|
||||
add r8,rax
|
||||
adc r9,rdx
|
||||
|
||||
mov rax,[rdi+2*8]
|
||||
mul r14
|
||||
mov r12,rbp
|
||||
mov rcx,[rsi+3*8]
|
||||
add r8,rax
|
||||
adc r9,rdx
|
||||
and r12,r8
|
||||
shrd r8,r9,52
|
||||
xor r9,r9
|
||||
|
||||
;; c+=a.n[0 1 2 3] * b.n[3 2 1 0]
|
||||
mov rax,[rdi+0*8]
|
||||
mul rcx
|
||||
add r8,rax
|
||||
adc r9,rdx
|
||||
|
||||
mov rax,[rdi+1*8]
|
||||
mul rbx
|
||||
add r8,rax
|
||||
adc r9,rdx
|
||||
|
||||
mov rax,[rdi+2*8]
|
||||
mul r15
|
||||
add r8,rax
|
||||
adc r9,rdx
|
||||
|
||||
mov rax,[rdi+3*8]
|
||||
mul r14
|
||||
mov r13,rbp
|
||||
mov rsi,[rsi+4*8] ; load b.n[4] and destroy pointer
|
||||
add r8,rax
|
||||
adc r9,rdx
|
||||
and r13,r8
|
||||
|
||||
shrd r8,r9,52
|
||||
xor r9,r9
|
||||
|
||||
|
||||
;; c+=a.n[0 1 2 3 4] * b.n[4 3 2 1 0]
|
||||
mov rax,[rdi+0*8]
|
||||
mul rsi
|
||||
add r8,rax
|
||||
adc r9,rdx
|
||||
|
||||
mov rax,[rdi+1*8]
|
||||
mul rcx
|
||||
add r8,rax
|
||||
adc r9,rdx
|
||||
|
||||
mov rax,[rdi+2*8]
|
||||
mul rbx
|
||||
add r8,rax
|
||||
adc r9,rdx
|
||||
|
||||
mov rax,[rdi+3*8]
|
||||
mul r15
|
||||
add r8,rax
|
||||
adc r9,rdx
|
||||
|
||||
mov rax,[rdi+4*8]
|
||||
mul r14
|
||||
mov r14,rbp ; load modulus into t4 and destroy a.n[0]
|
||||
add r8,rax
|
||||
adc r9,rdx
|
||||
and r14,r8
|
||||
shrd r8,r9,52
|
||||
xor r9,r9
|
||||
|
||||
;; c+=a.n[1 2 3 4] * b.n[4 3 2 1]
|
||||
mov rax,[rdi+1*8]
|
||||
mul rsi
|
||||
add r8,rax
|
||||
adc r9,rdx
|
||||
|
||||
mov rax,[rdi+2*8]
|
||||
mul rcx
|
||||
add r8,rax
|
||||
adc r9,rdx
|
||||
|
||||
mov rax,[rdi+3*8]
|
||||
mul rbx
|
||||
add r8,rax
|
||||
adc r9,rdx
|
||||
|
||||
mov rax,[rdi+4*8]
|
||||
mul r15
|
||||
mov r15,rbp
|
||||
add r8,rax
|
||||
adc r9,rdx
|
||||
|
||||
and r15,r8
|
||||
shrd r8,r9,52
|
||||
xor r9,r9
|
||||
|
||||
;; c+=a.n[2 3 4] * b.n[4 3 2]
|
||||
mov rax,[rdi+2*8]
|
||||
mul rsi
|
||||
add r8,rax
|
||||
adc r9,rdx
|
||||
|
||||
mov rax,[rdi+3*8]
|
||||
mul rcx
|
||||
add r8,rax
|
||||
adc r9,rdx
|
||||
|
||||
mov rax,[rdi+4*8]
|
||||
mul rbx
|
||||
mov rbx,rbp
|
||||
add r8,rax
|
||||
adc r9,rdx
|
||||
|
||||
and rbx,r8
|
||||
shrd r8,r9,52
|
||||
xor r9,r9
|
||||
|
||||
;; c+=a.n[3 4] * b.n[4 3]
|
||||
mov rax,[rdi+3*8]
|
||||
mul rsi
|
||||
add r8,rax
|
||||
adc r9,rdx
|
||||
|
||||
mov rax,[rdi+4*8]
|
||||
mul rcx
|
||||
mov rcx,rbp
|
||||
add r8,rax
|
||||
adc r9,rdx
|
||||
and rcx,r8
|
||||
shrd r8,r9,52
|
||||
xor r9,r9
|
||||
|
||||
;; c+=a.n[4] * b.n[4]
|
||||
mov rax,[rdi+4*8]
|
||||
mul rsi
|
||||
;; mov rbp,rbp ; modulus already there!
|
||||
add r8,rax
|
||||
adc r9,rdx
|
||||
and rbp,r8
|
||||
shrd r8,r9,52
|
||||
xor r9,r9
|
||||
|
||||
mov rsi,r8 ; load c into t9 and destroy b.n[4]
|
||||
|
||||
;; *******************************************************
|
||||
common_exit_norm:
|
||||
mov rdi,01000003D10h ; load constant
|
||||
|
||||
mov rax,r15 ; get t5
|
||||
mul rdi
|
||||
add rax,r10 ; +t0
|
||||
adc rdx,0
|
||||
mov r10,0FFFFFFFFFFFFFh ; modulus. Sadly, we ran out of registers!
|
||||
mov r8,rax ; +c
|
||||
and r10,rax
|
||||
shrd r8,rdx,52
|
||||
xor r9,r9
|
||||
|
||||
mov rax,rbx ; get t6
|
||||
mul rdi
|
||||
add rax,r11 ; +t1
|
||||
adc rdx,0
|
||||
mov r11,0FFFFFFFFFFFFFh ; modulus
|
||||
add r8,rax ; +c
|
||||
adc r9,rdx
|
||||
and r11,r8
|
||||
shrd r8,r9,52
|
||||
xor r9,r9
|
||||
|
||||
mov rax,rcx ; get t7
|
||||
mul rdi
|
||||
add rax,r12 ; +t2
|
||||
adc rdx,0
|
||||
pop rbx ; retrieve pointer to this.n
|
||||
mov r12,0FFFFFFFFFFFFFh ; modulus
|
||||
add r8,rax ; +c
|
||||
adc r9,rdx
|
||||
and r12,r8
|
||||
mov [rbx+2*8],r12 ; mov into this.n[2]
|
||||
shrd r8,r9,52
|
||||
xor r9,r9
|
||||
|
||||
mov rax,rbp ; get t8
|
||||
mul rdi
|
||||
add rax,r13 ; +t3
|
||||
adc rdx,0
|
||||
mov r13,0FFFFFFFFFFFFFh ; modulus
|
||||
add r8,rax ; +c
|
||||
adc r9,rdx
|
||||
and r13,r8
|
||||
mov [rbx+3*8],r13 ; -> this.n[3]
|
||||
shrd r8,r9,52
|
||||
xor r9,r9
|
||||
|
||||
mov rax,rsi ; get t9
|
||||
mul rdi
|
||||
add rax,r14 ; +t4
|
||||
adc rdx,0
|
||||
mov r14,0FFFFFFFFFFFFh ; !!!
|
||||
add r8,rax ; +c
|
||||
adc r9,rdx
|
||||
and r14,r8
|
||||
mov [rbx+4*8],r14 ; -> this.n[4]
|
||||
shrd r8,r9,48 ; !!!
|
||||
xor r9,r9
|
||||
|
||||
mov rax,01000003D1h
|
||||
mul r8
|
||||
add rax,r10
|
||||
adc rdx,0
|
||||
mov r10,0FFFFFFFFFFFFFh ; modulus
|
||||
mov r8,rax
|
||||
and rax,r10
|
||||
shrd r8,rdx,52
|
||||
mov [rbx+0*8],rax ; -> this.n[0]
|
||||
add r8,r11
|
||||
mov [rbx+1*8],r8 ; -> this.n[1]
|
||||
|
||||
pop r15
|
||||
pop r14
|
||||
pop r13
|
||||
pop r12
|
||||
pop rbx
|
||||
pop rbp
|
||||
ret
|
||||
|
||||
|
||||
;; PROC ExSetSquare
|
||||
;; Register Layout:
|
||||
;; INPUT: rdi = a.n
|
||||
;; rsi = this.a
|
||||
;; INTERNAL: rdx:rax = multiplication accumulator
|
||||
;; r9:r8 = c
|
||||
;; r10-r13 = t0-t3
|
||||
;; r14 = a.n[0] / t4
|
||||
;; r15 = a.n[1] / t5
|
||||
;; rbx = a.n[2] / t6
|
||||
;; rcx = a.n[3] / t7
|
||||
;; rbp = 0FFFFFFFFFFFFFh / t8
|
||||
;; rsi = a.n[4] / t9
|
||||
GLOBAL secp256k1_fe_sqr_inner
|
||||
ALIGN 32
|
||||
secp256k1_fe_sqr_inner:
|
||||
push rbp
|
||||
push rbx
|
||||
push r12
|
||||
push r13
|
||||
push r14
|
||||
push r15
|
||||
push rsi
|
||||
mov rbp,0FFFFFFFFFFFFFh
|
||||
|
||||
;; c=a.n[0] * a.n[0]
|
||||
mov r14,[rdi+0*8] ; r14=a.n[0]
|
||||
mov r10,rbp ; modulus
|
||||
mov rax,r14
|
||||
mul rax
|
||||
mov r15,[rdi+1*8] ; a.n[1]
|
||||
add r14,r14 ; r14=2*a.n[0]
|
||||
mov r8,rax
|
||||
and r10,rax ; only need lower qword
|
||||
shrd r8,rdx,52
|
||||
xor r9,r9
|
||||
|
||||
;; c+=2*a.n[0] * a.n[1]
|
||||
mov rax,r14 ; r14=2*a.n[0]
|
||||
mul r15
|
||||
mov rbx,[rdi+2*8] ; rbx=a.n[2]
|
||||
mov r11,rbp ; modulus
|
||||
add r8,rax
|
||||
adc r9,rdx
|
||||
and r11,r8
|
||||
shrd r8,r9,52
|
||||
xor r9,r9
|
||||
|
||||
;; c+=2*a.n[0]*a.n[2]+a.n[1]*a.n[1]
|
||||
mov rax,r14
|
||||
mul rbx
|
||||
add r8,rax
|
||||
adc r9,rdx
|
||||
|
||||
mov rax,r15
|
||||
mov r12,rbp ; modulus
|
||||
mul rax
|
||||
mov rcx,[rdi+3*8] ; rcx=a.n[3]
|
||||
add r15,r15 ; r15=a.n[1]*2
|
||||
add r8,rax
|
||||
adc r9,rdx
|
||||
and r12,r8 ; only need lower dword
|
||||
shrd r8,r9,52
|
||||
xor r9,r9
|
||||
|
||||
;; c+=2*a.n[0]*a.n[3]+2*a.n[1]*a.n[2]
|
||||
mov rax,r14
|
||||
mul rcx
|
||||
add r8,rax
|
||||
adc r9,rdx
|
||||
|
||||
mov rax,r15 ; rax=2*a.n[1]
|
||||
mov r13,rbp ; modulus
|
||||
mul rbx
|
||||
mov rsi,[rdi+4*8] ; rsi=a.n[4]
|
||||
add r8,rax
|
||||
adc r9,rdx
|
||||
and r13,r8
|
||||
shrd r8,r9,52
|
||||
xor r9,r9
|
||||
|
||||
;; c+=2*a.n[0]*a.n[4]+2*a.n[1]*a.n[3]+a.n[2]*a.n[2]
|
||||
mov rax,r14 ; last time we need 2*a.n[0]
|
||||
mul rsi
|
||||
add r8,rax
|
||||
adc r9,rdx
|
||||
|
||||
mov rax,r15
|
||||
mul rcx
|
||||
mov r14,rbp ; modulus
|
||||
add r8,rax
|
||||
adc r9,rdx
|
||||
|
||||
mov rax,rbx
|
||||
mul rax
|
||||
add rbx,rbx ; rcx=2*a.n[2]
|
||||
add r8,rax
|
||||
adc r9,rdx
|
||||
and r14,r8
|
||||
shrd r8,r9,52
|
||||
xor r9,r9
|
||||
|
||||
;; c+=2*a.n[1]*a.n[4]+2*a.n[2]*a.n[3]
|
||||
mov rax,r15 ; last time we need 2*a.n[1]
|
||||
mul rsi
|
||||
add r8,rax
|
||||
adc r9,rdx
|
||||
|
||||
mov rax,rbx
|
||||
mul rcx
|
||||
mov r15,rbp ; modulus
|
||||
add r8,rax
|
||||
adc r9,rdx
|
||||
and r15,r8
|
||||
shrd r8,r9,52
|
||||
xor r9,r9
|
||||
|
||||
;; c+=2*a.n[2]*a.n[4]+a.n[3]*a.n[3]
|
||||
mov rax,rbx ; last time we need 2*a.n[2]
|
||||
mul rsi
|
||||
add r8,rax
|
||||
adc r9,rdx
|
||||
|
||||
mov rax,rcx ; a.n[3]
|
||||
mul rax
|
||||
mov rbx,rbp ; modulus
|
||||
add r8,rax
|
||||
adc r9,rdx
|
||||
and rbx,r8 ; only need lower dword
|
||||
lea rax,[2*rcx]
|
||||
shrd r8,r9,52
|
||||
xor r9,r9
|
||||
|
||||
;; c+=2*a.n[3]*a.n[4]
|
||||
mul rsi
|
||||
mov rcx,rbp ; modulus
|
||||
add r8,rax
|
||||
adc r9,rdx
|
||||
and rcx,r8 ; only need lower dword
|
||||
shrd r8,r9,52
|
||||
xor r9,r9
|
||||
|
||||
;; c+=a.n[4]*a.n[4]
|
||||
mov rax,rsi
|
||||
mul rax
|
||||
;; mov rbp,rbp ; modulus is already there!
|
||||
add r8,rax
|
||||
adc r9,rdx
|
||||
and rbp,r8
|
||||
shrd r8,r9,52
|
||||
xor r9,r9
|
||||
|
||||
mov rsi,r8
|
||||
|
||||
;; *******************************************************
|
||||
jmp common_exit_norm
|
||||
end
|
||||
|
||||
|
||||
502
crypto/secp256k1/secp256k1/src/field_5x52_asm_impl.h
Normal file
502
crypto/secp256k1/secp256k1/src/field_5x52_asm_impl.h
Normal file
|
|
@ -0,0 +1,502 @@
|
|||
/**********************************************************************
|
||||
* Copyright (c) 2013-2014 Diederik Huys, Pieter Wuille *
|
||||
* Distributed under the MIT software license, see the accompanying *
|
||||
* file COPYING or http://www.opensource.org/licenses/mit-license.php.*
|
||||
**********************************************************************/
|
||||
|
||||
/**
|
||||
* Changelog:
|
||||
* - March 2013, Diederik Huys: original version
|
||||
* - November 2014, Pieter Wuille: updated to use Peter Dettman's parallel multiplication algorithm
|
||||
* - December 2014, Pieter Wuille: converted from YASM to GCC inline assembly
|
||||
*/
|
||||
|
||||
#ifndef _SECP256K1_FIELD_INNER5X52_IMPL_H_
|
||||
#define _SECP256K1_FIELD_INNER5X52_IMPL_H_
|
||||
|
||||
SECP256K1_INLINE static void secp256k1_fe_mul_inner(uint64_t *r, const uint64_t *a, const uint64_t * SECP256K1_RESTRICT b) {
|
||||
/**
|
||||
* Registers: rdx:rax = multiplication accumulator
|
||||
* r9:r8 = c
|
||||
* r15:rcx = d
|
||||
* r10-r14 = a0-a4
|
||||
* rbx = b
|
||||
* rdi = r
|
||||
* rsi = a / t?
|
||||
*/
|
||||
uint64_t tmp1, tmp2, tmp3;
|
||||
__asm__ __volatile__(
|
||||
"movq 0(%%rsi),%%r10\n"
|
||||
"movq 8(%%rsi),%%r11\n"
|
||||
"movq 16(%%rsi),%%r12\n"
|
||||
"movq 24(%%rsi),%%r13\n"
|
||||
"movq 32(%%rsi),%%r14\n"
|
||||
|
||||
/* d += a3 * b0 */
|
||||
"movq 0(%%rbx),%%rax\n"
|
||||
"mulq %%r13\n"
|
||||
"movq %%rax,%%rcx\n"
|
||||
"movq %%rdx,%%r15\n"
|
||||
/* d += a2 * b1 */
|
||||
"movq 8(%%rbx),%%rax\n"
|
||||
"mulq %%r12\n"
|
||||
"addq %%rax,%%rcx\n"
|
||||
"adcq %%rdx,%%r15\n"
|
||||
/* d += a1 * b2 */
|
||||
"movq 16(%%rbx),%%rax\n"
|
||||
"mulq %%r11\n"
|
||||
"addq %%rax,%%rcx\n"
|
||||
"adcq %%rdx,%%r15\n"
|
||||
/* d = a0 * b3 */
|
||||
"movq 24(%%rbx),%%rax\n"
|
||||
"mulq %%r10\n"
|
||||
"addq %%rax,%%rcx\n"
|
||||
"adcq %%rdx,%%r15\n"
|
||||
/* c = a4 * b4 */
|
||||
"movq 32(%%rbx),%%rax\n"
|
||||
"mulq %%r14\n"
|
||||
"movq %%rax,%%r8\n"
|
||||
"movq %%rdx,%%r9\n"
|
||||
/* d += (c & M) * R */
|
||||
"movq $0xfffffffffffff,%%rdx\n"
|
||||
"andq %%rdx,%%rax\n"
|
||||
"movq $0x1000003d10,%%rdx\n"
|
||||
"mulq %%rdx\n"
|
||||
"addq %%rax,%%rcx\n"
|
||||
"adcq %%rdx,%%r15\n"
|
||||
/* c >>= 52 (%%r8 only) */
|
||||
"shrdq $52,%%r9,%%r8\n"
|
||||
/* t3 (tmp1) = d & M */
|
||||
"movq %%rcx,%%rsi\n"
|
||||
"movq $0xfffffffffffff,%%rdx\n"
|
||||
"andq %%rdx,%%rsi\n"
|
||||
"movq %%rsi,%q1\n"
|
||||
/* d >>= 52 */
|
||||
"shrdq $52,%%r15,%%rcx\n"
|
||||
"xorq %%r15,%%r15\n"
|
||||
/* d += a4 * b0 */
|
||||
"movq 0(%%rbx),%%rax\n"
|
||||
"mulq %%r14\n"
|
||||
"addq %%rax,%%rcx\n"
|
||||
"adcq %%rdx,%%r15\n"
|
||||
/* d += a3 * b1 */
|
||||
"movq 8(%%rbx),%%rax\n"
|
||||
"mulq %%r13\n"
|
||||
"addq %%rax,%%rcx\n"
|
||||
"adcq %%rdx,%%r15\n"
|
||||
/* d += a2 * b2 */
|
||||
"movq 16(%%rbx),%%rax\n"
|
||||
"mulq %%r12\n"
|
||||
"addq %%rax,%%rcx\n"
|
||||
"adcq %%rdx,%%r15\n"
|
||||
/* d += a1 * b3 */
|
||||
"movq 24(%%rbx),%%rax\n"
|
||||
"mulq %%r11\n"
|
||||
"addq %%rax,%%rcx\n"
|
||||
"adcq %%rdx,%%r15\n"
|
||||
/* d += a0 * b4 */
|
||||
"movq 32(%%rbx),%%rax\n"
|
||||
"mulq %%r10\n"
|
||||
"addq %%rax,%%rcx\n"
|
||||
"adcq %%rdx,%%r15\n"
|
||||
/* d += c * R */
|
||||
"movq %%r8,%%rax\n"
|
||||
"movq $0x1000003d10,%%rdx\n"
|
||||
"mulq %%rdx\n"
|
||||
"addq %%rax,%%rcx\n"
|
||||
"adcq %%rdx,%%r15\n"
|
||||
/* t4 = d & M (%%rsi) */
|
||||
"movq %%rcx,%%rsi\n"
|
||||
"movq $0xfffffffffffff,%%rdx\n"
|
||||
"andq %%rdx,%%rsi\n"
|
||||
/* d >>= 52 */
|
||||
"shrdq $52,%%r15,%%rcx\n"
|
||||
"xorq %%r15,%%r15\n"
|
||||
/* tx = t4 >> 48 (tmp3) */
|
||||
"movq %%rsi,%%rax\n"
|
||||
"shrq $48,%%rax\n"
|
||||
"movq %%rax,%q3\n"
|
||||
/* t4 &= (M >> 4) (tmp2) */
|
||||
"movq $0xffffffffffff,%%rax\n"
|
||||
"andq %%rax,%%rsi\n"
|
||||
"movq %%rsi,%q2\n"
|
||||
/* c = a0 * b0 */
|
||||
"movq 0(%%rbx),%%rax\n"
|
||||
"mulq %%r10\n"
|
||||
"movq %%rax,%%r8\n"
|
||||
"movq %%rdx,%%r9\n"
|
||||
/* d += a4 * b1 */
|
||||
"movq 8(%%rbx),%%rax\n"
|
||||
"mulq %%r14\n"
|
||||
"addq %%rax,%%rcx\n"
|
||||
"adcq %%rdx,%%r15\n"
|
||||
/* d += a3 * b2 */
|
||||
"movq 16(%%rbx),%%rax\n"
|
||||
"mulq %%r13\n"
|
||||
"addq %%rax,%%rcx\n"
|
||||
"adcq %%rdx,%%r15\n"
|
||||
/* d += a2 * b3 */
|
||||
"movq 24(%%rbx),%%rax\n"
|
||||
"mulq %%r12\n"
|
||||
"addq %%rax,%%rcx\n"
|
||||
"adcq %%rdx,%%r15\n"
|
||||
/* d += a1 * b4 */
|
||||
"movq 32(%%rbx),%%rax\n"
|
||||
"mulq %%r11\n"
|
||||
"addq %%rax,%%rcx\n"
|
||||
"adcq %%rdx,%%r15\n"
|
||||
/* u0 = d & M (%%rsi) */
|
||||
"movq %%rcx,%%rsi\n"
|
||||
"movq $0xfffffffffffff,%%rdx\n"
|
||||
"andq %%rdx,%%rsi\n"
|
||||
/* d >>= 52 */
|
||||
"shrdq $52,%%r15,%%rcx\n"
|
||||
"xorq %%r15,%%r15\n"
|
||||
/* u0 = (u0 << 4) | tx (%%rsi) */
|
||||
"shlq $4,%%rsi\n"
|
||||
"movq %q3,%%rax\n"
|
||||
"orq %%rax,%%rsi\n"
|
||||
/* c += u0 * (R >> 4) */
|
||||
"movq $0x1000003d1,%%rax\n"
|
||||
"mulq %%rsi\n"
|
||||
"addq %%rax,%%r8\n"
|
||||
"adcq %%rdx,%%r9\n"
|
||||
/* r[0] = c & M */
|
||||
"movq %%r8,%%rax\n"
|
||||
"movq $0xfffffffffffff,%%rdx\n"
|
||||
"andq %%rdx,%%rax\n"
|
||||
"movq %%rax,0(%%rdi)\n"
|
||||
/* c >>= 52 */
|
||||
"shrdq $52,%%r9,%%r8\n"
|
||||
"xorq %%r9,%%r9\n"
|
||||
/* c += a1 * b0 */
|
||||
"movq 0(%%rbx),%%rax\n"
|
||||
"mulq %%r11\n"
|
||||
"addq %%rax,%%r8\n"
|
||||
"adcq %%rdx,%%r9\n"
|
||||
/* c += a0 * b1 */
|
||||
"movq 8(%%rbx),%%rax\n"
|
||||
"mulq %%r10\n"
|
||||
"addq %%rax,%%r8\n"
|
||||
"adcq %%rdx,%%r9\n"
|
||||
/* d += a4 * b2 */
|
||||
"movq 16(%%rbx),%%rax\n"
|
||||
"mulq %%r14\n"
|
||||
"addq %%rax,%%rcx\n"
|
||||
"adcq %%rdx,%%r15\n"
|
||||
/* d += a3 * b3 */
|
||||
"movq 24(%%rbx),%%rax\n"
|
||||
"mulq %%r13\n"
|
||||
"addq %%rax,%%rcx\n"
|
||||
"adcq %%rdx,%%r15\n"
|
||||
/* d += a2 * b4 */
|
||||
"movq 32(%%rbx),%%rax\n"
|
||||
"mulq %%r12\n"
|
||||
"addq %%rax,%%rcx\n"
|
||||
"adcq %%rdx,%%r15\n"
|
||||
/* c += (d & M) * R */
|
||||
"movq %%rcx,%%rax\n"
|
||||
"movq $0xfffffffffffff,%%rdx\n"
|
||||
"andq %%rdx,%%rax\n"
|
||||
"movq $0x1000003d10,%%rdx\n"
|
||||
"mulq %%rdx\n"
|
||||
"addq %%rax,%%r8\n"
|
||||
"adcq %%rdx,%%r9\n"
|
||||
/* d >>= 52 */
|
||||
"shrdq $52,%%r15,%%rcx\n"
|
||||
"xorq %%r15,%%r15\n"
|
||||
/* r[1] = c & M */
|
||||
"movq %%r8,%%rax\n"
|
||||
"movq $0xfffffffffffff,%%rdx\n"
|
||||
"andq %%rdx,%%rax\n"
|
||||
"movq %%rax,8(%%rdi)\n"
|
||||
/* c >>= 52 */
|
||||
"shrdq $52,%%r9,%%r8\n"
|
||||
"xorq %%r9,%%r9\n"
|
||||
/* c += a2 * b0 */
|
||||
"movq 0(%%rbx),%%rax\n"
|
||||
"mulq %%r12\n"
|
||||
"addq %%rax,%%r8\n"
|
||||
"adcq %%rdx,%%r9\n"
|
||||
/* c += a1 * b1 */
|
||||
"movq 8(%%rbx),%%rax\n"
|
||||
"mulq %%r11\n"
|
||||
"addq %%rax,%%r8\n"
|
||||
"adcq %%rdx,%%r9\n"
|
||||
/* c += a0 * b2 (last use of %%r10 = a0) */
|
||||
"movq 16(%%rbx),%%rax\n"
|
||||
"mulq %%r10\n"
|
||||
"addq %%rax,%%r8\n"
|
||||
"adcq %%rdx,%%r9\n"
|
||||
/* fetch t3 (%%r10, overwrites a0), t4 (%%rsi) */
|
||||
"movq %q2,%%rsi\n"
|
||||
"movq %q1,%%r10\n"
|
||||
/* d += a4 * b3 */
|
||||
"movq 24(%%rbx),%%rax\n"
|
||||
"mulq %%r14\n"
|
||||
"addq %%rax,%%rcx\n"
|
||||
"adcq %%rdx,%%r15\n"
|
||||
/* d += a3 * b4 */
|
||||
"movq 32(%%rbx),%%rax\n"
|
||||
"mulq %%r13\n"
|
||||
"addq %%rax,%%rcx\n"
|
||||
"adcq %%rdx,%%r15\n"
|
||||
/* c += (d & M) * R */
|
||||
"movq %%rcx,%%rax\n"
|
||||
"movq $0xfffffffffffff,%%rdx\n"
|
||||
"andq %%rdx,%%rax\n"
|
||||
"movq $0x1000003d10,%%rdx\n"
|
||||
"mulq %%rdx\n"
|
||||
"addq %%rax,%%r8\n"
|
||||
"adcq %%rdx,%%r9\n"
|
||||
/* d >>= 52 (%%rcx only) */
|
||||
"shrdq $52,%%r15,%%rcx\n"
|
||||
/* r[2] = c & M */
|
||||
"movq %%r8,%%rax\n"
|
||||
"movq $0xfffffffffffff,%%rdx\n"
|
||||
"andq %%rdx,%%rax\n"
|
||||
"movq %%rax,16(%%rdi)\n"
|
||||
/* c >>= 52 */
|
||||
"shrdq $52,%%r9,%%r8\n"
|
||||
"xorq %%r9,%%r9\n"
|
||||
/* c += t3 */
|
||||
"addq %%r10,%%r8\n"
|
||||
/* c += d * R */
|
||||
"movq %%rcx,%%rax\n"
|
||||
"movq $0x1000003d10,%%rdx\n"
|
||||
"mulq %%rdx\n"
|
||||
"addq %%rax,%%r8\n"
|
||||
"adcq %%rdx,%%r9\n"
|
||||
/* r[3] = c & M */
|
||||
"movq %%r8,%%rax\n"
|
||||
"movq $0xfffffffffffff,%%rdx\n"
|
||||
"andq %%rdx,%%rax\n"
|
||||
"movq %%rax,24(%%rdi)\n"
|
||||
/* c >>= 52 (%%r8 only) */
|
||||
"shrdq $52,%%r9,%%r8\n"
|
||||
/* c += t4 (%%r8 only) */
|
||||
"addq %%rsi,%%r8\n"
|
||||
/* r[4] = c */
|
||||
"movq %%r8,32(%%rdi)\n"
|
||||
: "+S"(a), "=m"(tmp1), "=m"(tmp2), "=m"(tmp3)
|
||||
: "b"(b), "D"(r)
|
||||
: "%rax", "%rcx", "%rdx", "%r8", "%r9", "%r10", "%r11", "%r12", "%r13", "%r14", "%r15", "cc", "memory"
|
||||
);
|
||||
}
|
||||
|
||||
SECP256K1_INLINE static void secp256k1_fe_sqr_inner(uint64_t *r, const uint64_t *a) {
|
||||
/**
|
||||
* Registers: rdx:rax = multiplication accumulator
|
||||
* r9:r8 = c
|
||||
* rcx:rbx = d
|
||||
* r10-r14 = a0-a4
|
||||
* r15 = M (0xfffffffffffff)
|
||||
* rdi = r
|
||||
* rsi = a / t?
|
||||
*/
|
||||
uint64_t tmp1, tmp2, tmp3;
|
||||
__asm__ __volatile__(
|
||||
"movq 0(%%rsi),%%r10\n"
|
||||
"movq 8(%%rsi),%%r11\n"
|
||||
"movq 16(%%rsi),%%r12\n"
|
||||
"movq 24(%%rsi),%%r13\n"
|
||||
"movq 32(%%rsi),%%r14\n"
|
||||
"movq $0xfffffffffffff,%%r15\n"
|
||||
|
||||
/* d = (a0*2) * a3 */
|
||||
"leaq (%%r10,%%r10,1),%%rax\n"
|
||||
"mulq %%r13\n"
|
||||
"movq %%rax,%%rbx\n"
|
||||
"movq %%rdx,%%rcx\n"
|
||||
/* d += (a1*2) * a2 */
|
||||
"leaq (%%r11,%%r11,1),%%rax\n"
|
||||
"mulq %%r12\n"
|
||||
"addq %%rax,%%rbx\n"
|
||||
"adcq %%rdx,%%rcx\n"
|
||||
/* c = a4 * a4 */
|
||||
"movq %%r14,%%rax\n"
|
||||
"mulq %%r14\n"
|
||||
"movq %%rax,%%r8\n"
|
||||
"movq %%rdx,%%r9\n"
|
||||
/* d += (c & M) * R */
|
||||
"andq %%r15,%%rax\n"
|
||||
"movq $0x1000003d10,%%rdx\n"
|
||||
"mulq %%rdx\n"
|
||||
"addq %%rax,%%rbx\n"
|
||||
"adcq %%rdx,%%rcx\n"
|
||||
/* c >>= 52 (%%r8 only) */
|
||||
"shrdq $52,%%r9,%%r8\n"
|
||||
/* t3 (tmp1) = d & M */
|
||||
"movq %%rbx,%%rsi\n"
|
||||
"andq %%r15,%%rsi\n"
|
||||
"movq %%rsi,%q1\n"
|
||||
/* d >>= 52 */
|
||||
"shrdq $52,%%rcx,%%rbx\n"
|
||||
"xorq %%rcx,%%rcx\n"
|
||||
/* a4 *= 2 */
|
||||
"addq %%r14,%%r14\n"
|
||||
/* d += a0 * a4 */
|
||||
"movq %%r10,%%rax\n"
|
||||
"mulq %%r14\n"
|
||||
"addq %%rax,%%rbx\n"
|
||||
"adcq %%rdx,%%rcx\n"
|
||||
/* d+= (a1*2) * a3 */
|
||||
"leaq (%%r11,%%r11,1),%%rax\n"
|
||||
"mulq %%r13\n"
|
||||
"addq %%rax,%%rbx\n"
|
||||
"adcq %%rdx,%%rcx\n"
|
||||
/* d += a2 * a2 */
|
||||
"movq %%r12,%%rax\n"
|
||||
"mulq %%r12\n"
|
||||
"addq %%rax,%%rbx\n"
|
||||
"adcq %%rdx,%%rcx\n"
|
||||
/* d += c * R */
|
||||
"movq %%r8,%%rax\n"
|
||||
"movq $0x1000003d10,%%rdx\n"
|
||||
"mulq %%rdx\n"
|
||||
"addq %%rax,%%rbx\n"
|
||||
"adcq %%rdx,%%rcx\n"
|
||||
/* t4 = d & M (%%rsi) */
|
||||
"movq %%rbx,%%rsi\n"
|
||||
"andq %%r15,%%rsi\n"
|
||||
/* d >>= 52 */
|
||||
"shrdq $52,%%rcx,%%rbx\n"
|
||||
"xorq %%rcx,%%rcx\n"
|
||||
/* tx = t4 >> 48 (tmp3) */
|
||||
"movq %%rsi,%%rax\n"
|
||||
"shrq $48,%%rax\n"
|
||||
"movq %%rax,%q3\n"
|
||||
/* t4 &= (M >> 4) (tmp2) */
|
||||
"movq $0xffffffffffff,%%rax\n"
|
||||
"andq %%rax,%%rsi\n"
|
||||
"movq %%rsi,%q2\n"
|
||||
/* c = a0 * a0 */
|
||||
"movq %%r10,%%rax\n"
|
||||
"mulq %%r10\n"
|
||||
"movq %%rax,%%r8\n"
|
||||
"movq %%rdx,%%r9\n"
|
||||
/* d += a1 * a4 */
|
||||
"movq %%r11,%%rax\n"
|
||||
"mulq %%r14\n"
|
||||
"addq %%rax,%%rbx\n"
|
||||
"adcq %%rdx,%%rcx\n"
|
||||
/* d += (a2*2) * a3 */
|
||||
"leaq (%%r12,%%r12,1),%%rax\n"
|
||||
"mulq %%r13\n"
|
||||
"addq %%rax,%%rbx\n"
|
||||
"adcq %%rdx,%%rcx\n"
|
||||
/* u0 = d & M (%%rsi) */
|
||||
"movq %%rbx,%%rsi\n"
|
||||
"andq %%r15,%%rsi\n"
|
||||
/* d >>= 52 */
|
||||
"shrdq $52,%%rcx,%%rbx\n"
|
||||
"xorq %%rcx,%%rcx\n"
|
||||
/* u0 = (u0 << 4) | tx (%%rsi) */
|
||||
"shlq $4,%%rsi\n"
|
||||
"movq %q3,%%rax\n"
|
||||
"orq %%rax,%%rsi\n"
|
||||
/* c += u0 * (R >> 4) */
|
||||
"movq $0x1000003d1,%%rax\n"
|
||||
"mulq %%rsi\n"
|
||||
"addq %%rax,%%r8\n"
|
||||
"adcq %%rdx,%%r9\n"
|
||||
/* r[0] = c & M */
|
||||
"movq %%r8,%%rax\n"
|
||||
"andq %%r15,%%rax\n"
|
||||
"movq %%rax,0(%%rdi)\n"
|
||||
/* c >>= 52 */
|
||||
"shrdq $52,%%r9,%%r8\n"
|
||||
"xorq %%r9,%%r9\n"
|
||||
/* a0 *= 2 */
|
||||
"addq %%r10,%%r10\n"
|
||||
/* c += a0 * a1 */
|
||||
"movq %%r10,%%rax\n"
|
||||
"mulq %%r11\n"
|
||||
"addq %%rax,%%r8\n"
|
||||
"adcq %%rdx,%%r9\n"
|
||||
/* d += a2 * a4 */
|
||||
"movq %%r12,%%rax\n"
|
||||
"mulq %%r14\n"
|
||||
"addq %%rax,%%rbx\n"
|
||||
"adcq %%rdx,%%rcx\n"
|
||||
/* d += a3 * a3 */
|
||||
"movq %%r13,%%rax\n"
|
||||
"mulq %%r13\n"
|
||||
"addq %%rax,%%rbx\n"
|
||||
"adcq %%rdx,%%rcx\n"
|
||||
/* c += (d & M) * R */
|
||||
"movq %%rbx,%%rax\n"
|
||||
"andq %%r15,%%rax\n"
|
||||
"movq $0x1000003d10,%%rdx\n"
|
||||
"mulq %%rdx\n"
|
||||
"addq %%rax,%%r8\n"
|
||||
"adcq %%rdx,%%r9\n"
|
||||
/* d >>= 52 */
|
||||
"shrdq $52,%%rcx,%%rbx\n"
|
||||
"xorq %%rcx,%%rcx\n"
|
||||
/* r[1] = c & M */
|
||||
"movq %%r8,%%rax\n"
|
||||
"andq %%r15,%%rax\n"
|
||||
"movq %%rax,8(%%rdi)\n"
|
||||
/* c >>= 52 */
|
||||
"shrdq $52,%%r9,%%r8\n"
|
||||
"xorq %%r9,%%r9\n"
|
||||
/* c += a0 * a2 (last use of %%r10) */
|
||||
"movq %%r10,%%rax\n"
|
||||
"mulq %%r12\n"
|
||||
"addq %%rax,%%r8\n"
|
||||
"adcq %%rdx,%%r9\n"
|
||||
/* fetch t3 (%%r10, overwrites a0),t4 (%%rsi) */
|
||||
"movq %q2,%%rsi\n"
|
||||
"movq %q1,%%r10\n"
|
||||
/* c += a1 * a1 */
|
||||
"movq %%r11,%%rax\n"
|
||||
"mulq %%r11\n"
|
||||
"addq %%rax,%%r8\n"
|
||||
"adcq %%rdx,%%r9\n"
|
||||
/* d += a3 * a4 */
|
||||
"movq %%r13,%%rax\n"
|
||||
"mulq %%r14\n"
|
||||
"addq %%rax,%%rbx\n"
|
||||
"adcq %%rdx,%%rcx\n"
|
||||
/* c += (d & M) * R */
|
||||
"movq %%rbx,%%rax\n"
|
||||
"andq %%r15,%%rax\n"
|
||||
"movq $0x1000003d10,%%rdx\n"
|
||||
"mulq %%rdx\n"
|
||||
"addq %%rax,%%r8\n"
|
||||
"adcq %%rdx,%%r9\n"
|
||||
/* d >>= 52 (%%rbx only) */
|
||||
"shrdq $52,%%rcx,%%rbx\n"
|
||||
/* r[2] = c & M */
|
||||
"movq %%r8,%%rax\n"
|
||||
"andq %%r15,%%rax\n"
|
||||
"movq %%rax,16(%%rdi)\n"
|
||||
/* c >>= 52 */
|
||||
"shrdq $52,%%r9,%%r8\n"
|
||||
"xorq %%r9,%%r9\n"
|
||||
/* c += t3 */
|
||||
"addq %%r10,%%r8\n"
|
||||
/* c += d * R */
|
||||
"movq %%rbx,%%rax\n"
|
||||
"movq $0x1000003d10,%%rdx\n"
|
||||
"mulq %%rdx\n"
|
||||
"addq %%rax,%%r8\n"
|
||||
"adcq %%rdx,%%r9\n"
|
||||
/* r[3] = c & M */
|
||||
"movq %%r8,%%rax\n"
|
||||
"andq %%r15,%%rax\n"
|
||||
"movq %%rax,24(%%rdi)\n"
|
||||
/* c >>= 52 (%%r8 only) */
|
||||
"shrdq $52,%%r9,%%r8\n"
|
||||
/* c += t4 (%%r8 only) */
|
||||
"addq %%rsi,%%r8\n"
|
||||
/* r[4] = c */
|
||||
"movq %%r8,32(%%rdi)\n"
|
||||
: "+S"(a), "=m"(tmp1), "=m"(tmp2), "=m"(tmp3)
|
||||
: "D"(r)
|
||||
: "%rax", "%rbx", "%rcx", "%rdx", "%r8", "%r9", "%r10", "%r11", "%r12", "%r13", "%r14", "%r15", "cc", "memory"
|
||||
);
|
||||
}
|
||||
|
||||
#endif
|
||||
439
crypto/secp256k1/secp256k1/src/field_5x52_impl.h
Normal file
439
crypto/secp256k1/secp256k1/src/field_5x52_impl.h
Normal file
|
|
@ -0,0 +1,439 @@
|
|||
/**********************************************************************
|
||||
* Copyright (c) 2013, 2014 Pieter Wuille *
|
||||
* Distributed under the MIT software license, see the accompanying *
|
||||
* file COPYING or http://www.opensource.org/licenses/mit-license.php.*
|
||||
**********************************************************************/
|
||||
|
||||
#ifndef _SECP256K1_FIELD_REPR_IMPL_H_
|
||||
#define _SECP256K1_FIELD_REPR_IMPL_H_
|
||||
|
||||
#if defined HAVE_CONFIG_H
|
||||
#include "libsecp256k1-config.h"
|
||||
#endif
|
||||
|
||||
#include <string.h>
|
||||
#include "util.h"
|
||||
#include "num.h"
|
||||
#include "field.h"
|
||||
|
||||
#if defined(USE_ASM_X86_64)
|
||||
#include "field_5x52_asm_impl.h"
|
||||
#else
|
||||
#include "field_5x52_int128_impl.h"
|
||||
#endif
|
||||
|
||||
/** Implements arithmetic modulo FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE FFFFFC2F,
|
||||
* represented as 5 uint64_t's in base 2^52. The values are allowed to contain >52 each. In particular,
|
||||
* each FieldElem has a 'magnitude' associated with it. Internally, a magnitude M means each element
|
||||
* is at most M*(2^53-1), except the most significant one, which is limited to M*(2^49-1). All operations
|
||||
* accept any input with magnitude at most M, and have different rules for propagating magnitude to their
|
||||
* output.
|
||||
*/
|
||||
|
||||
#ifdef VERIFY
|
||||
static void secp256k1_fe_verify(const secp256k1_fe_t *a) {
|
||||
const uint64_t *d = a->n;
|
||||
int m = a->normalized ? 1 : 2 * a->magnitude, r = 1;
|
||||
/* secp256k1 'p' value defined in "Standards for Efficient Cryptography" (SEC2) 2.7.1. */
|
||||
r &= (d[0] <= 0xFFFFFFFFFFFFFULL * m);
|
||||
r &= (d[1] <= 0xFFFFFFFFFFFFFULL * m);
|
||||
r &= (d[2] <= 0xFFFFFFFFFFFFFULL * m);
|
||||
r &= (d[3] <= 0xFFFFFFFFFFFFFULL * m);
|
||||
r &= (d[4] <= 0x0FFFFFFFFFFFFULL * m);
|
||||
r &= (a->magnitude >= 0);
|
||||
r &= (a->magnitude <= 2048);
|
||||
if (a->normalized) {
|
||||
r &= (a->magnitude <= 1);
|
||||
if (r && (d[4] == 0x0FFFFFFFFFFFFULL) && ((d[3] & d[2] & d[1]) == 0xFFFFFFFFFFFFFULL)) {
|
||||
r &= (d[0] < 0xFFFFEFFFFFC2FULL);
|
||||
}
|
||||
}
|
||||
VERIFY_CHECK(r == 1);
|
||||
}
|
||||
#else
|
||||
static void secp256k1_fe_verify(const secp256k1_fe_t *a) {
|
||||
(void)a;
|
||||
}
|
||||
#endif
|
||||
|
||||
static void secp256k1_fe_normalize(secp256k1_fe_t *r) {
|
||||
uint64_t t0 = r->n[0], t1 = r->n[1], t2 = r->n[2], t3 = r->n[3], t4 = r->n[4];
|
||||
|
||||
/* Reduce t4 at the start so there will be at most a single carry from the first pass */
|
||||
uint64_t m;
|
||||
uint64_t x = t4 >> 48; t4 &= 0x0FFFFFFFFFFFFULL;
|
||||
|
||||
/* The first pass ensures the magnitude is 1, ... */
|
||||
t0 += x * 0x1000003D1ULL;
|
||||
t1 += (t0 >> 52); t0 &= 0xFFFFFFFFFFFFFULL;
|
||||
t2 += (t1 >> 52); t1 &= 0xFFFFFFFFFFFFFULL; m = t1;
|
||||
t3 += (t2 >> 52); t2 &= 0xFFFFFFFFFFFFFULL; m &= t2;
|
||||
t4 += (t3 >> 52); t3 &= 0xFFFFFFFFFFFFFULL; m &= t3;
|
||||
|
||||
/* ... except for a possible carry at bit 48 of t4 (i.e. bit 256 of the field element) */
|
||||
VERIFY_CHECK(t4 >> 49 == 0);
|
||||
|
||||
/* At most a single final reduction is needed; check if the value is >= the field characteristic */
|
||||
x = (t4 >> 48) | ((t4 == 0x0FFFFFFFFFFFFULL) & (m == 0xFFFFFFFFFFFFFULL)
|
||||
& (t0 >= 0xFFFFEFFFFFC2FULL));
|
||||
|
||||
/* Apply the final reduction (for constant-time behaviour, we do it always) */
|
||||
t0 += x * 0x1000003D1ULL;
|
||||
t1 += (t0 >> 52); t0 &= 0xFFFFFFFFFFFFFULL;
|
||||
t2 += (t1 >> 52); t1 &= 0xFFFFFFFFFFFFFULL;
|
||||
t3 += (t2 >> 52); t2 &= 0xFFFFFFFFFFFFFULL;
|
||||
t4 += (t3 >> 52); t3 &= 0xFFFFFFFFFFFFFULL;
|
||||
|
||||
/* If t4 didn't carry to bit 48 already, then it should have after any final reduction */
|
||||
VERIFY_CHECK(t4 >> 48 == x);
|
||||
|
||||
/* Mask off the possible multiple of 2^256 from the final reduction */
|
||||
t4 &= 0x0FFFFFFFFFFFFULL;
|
||||
|
||||
r->n[0] = t0; r->n[1] = t1; r->n[2] = t2; r->n[3] = t3; r->n[4] = t4;
|
||||
|
||||
#ifdef VERIFY
|
||||
r->magnitude = 1;
|
||||
r->normalized = 1;
|
||||
secp256k1_fe_verify(r);
|
||||
#endif
|
||||
}
|
||||
|
||||
static void secp256k1_fe_normalize_weak(secp256k1_fe_t *r) {
|
||||
uint64_t t0 = r->n[0], t1 = r->n[1], t2 = r->n[2], t3 = r->n[3], t4 = r->n[4];
|
||||
|
||||
/* Reduce t4 at the start so there will be at most a single carry from the first pass */
|
||||
uint64_t x = t4 >> 48; t4 &= 0x0FFFFFFFFFFFFULL;
|
||||
|
||||
/* The first pass ensures the magnitude is 1, ... */
|
||||
t0 += x * 0x1000003D1ULL;
|
||||
t1 += (t0 >> 52); t0 &= 0xFFFFFFFFFFFFFULL;
|
||||
t2 += (t1 >> 52); t1 &= 0xFFFFFFFFFFFFFULL;
|
||||
t3 += (t2 >> 52); t2 &= 0xFFFFFFFFFFFFFULL;
|
||||
t4 += (t3 >> 52); t3 &= 0xFFFFFFFFFFFFFULL;
|
||||
|
||||
/* ... except for a possible carry at bit 48 of t4 (i.e. bit 256 of the field element) */
|
||||
VERIFY_CHECK(t4 >> 49 == 0);
|
||||
|
||||
r->n[0] = t0; r->n[1] = t1; r->n[2] = t2; r->n[3] = t3; r->n[4] = t4;
|
||||
|
||||
#ifdef VERIFY
|
||||
r->magnitude = 1;
|
||||
secp256k1_fe_verify(r);
|
||||
#endif
|
||||
}
|
||||
|
||||
static void secp256k1_fe_normalize_var(secp256k1_fe_t *r) {
|
||||
uint64_t t0 = r->n[0], t1 = r->n[1], t2 = r->n[2], t3 = r->n[3], t4 = r->n[4];
|
||||
|
||||
/* Reduce t4 at the start so there will be at most a single carry from the first pass */
|
||||
uint64_t m;
|
||||
uint64_t x = t4 >> 48; t4 &= 0x0FFFFFFFFFFFFULL;
|
||||
|
||||
/* The first pass ensures the magnitude is 1, ... */
|
||||
t0 += x * 0x1000003D1ULL;
|
||||
t1 += (t0 >> 52); t0 &= 0xFFFFFFFFFFFFFULL;
|
||||
t2 += (t1 >> 52); t1 &= 0xFFFFFFFFFFFFFULL; m = t1;
|
||||
t3 += (t2 >> 52); t2 &= 0xFFFFFFFFFFFFFULL; m &= t2;
|
||||
t4 += (t3 >> 52); t3 &= 0xFFFFFFFFFFFFFULL; m &= t3;
|
||||
|
||||
/* ... except for a possible carry at bit 48 of t4 (i.e. bit 256 of the field element) */
|
||||
VERIFY_CHECK(t4 >> 49 == 0);
|
||||
|
||||
/* At most a single final reduction is needed; check if the value is >= the field characteristic */
|
||||
x = (t4 >> 48) | ((t4 == 0x0FFFFFFFFFFFFULL) & (m == 0xFFFFFFFFFFFFFULL)
|
||||
& (t0 >= 0xFFFFEFFFFFC2FULL));
|
||||
|
||||
if (x) {
|
||||
t0 += 0x1000003D1ULL;
|
||||
t1 += (t0 >> 52); t0 &= 0xFFFFFFFFFFFFFULL;
|
||||
t2 += (t1 >> 52); t1 &= 0xFFFFFFFFFFFFFULL;
|
||||
t3 += (t2 >> 52); t2 &= 0xFFFFFFFFFFFFFULL;
|
||||
t4 += (t3 >> 52); t3 &= 0xFFFFFFFFFFFFFULL;
|
||||
|
||||
/* If t4 didn't carry to bit 48 already, then it should have after any final reduction */
|
||||
VERIFY_CHECK(t4 >> 48 == x);
|
||||
|
||||
/* Mask off the possible multiple of 2^256 from the final reduction */
|
||||
t4 &= 0x0FFFFFFFFFFFFULL;
|
||||
}
|
||||
|
||||
r->n[0] = t0; r->n[1] = t1; r->n[2] = t2; r->n[3] = t3; r->n[4] = t4;
|
||||
|
||||
#ifdef VERIFY
|
||||
r->magnitude = 1;
|
||||
r->normalized = 1;
|
||||
secp256k1_fe_verify(r);
|
||||
#endif
|
||||
}
|
||||
|
||||
static int secp256k1_fe_normalizes_to_zero(secp256k1_fe_t *r) {
|
||||
uint64_t t0 = r->n[0], t1 = r->n[1], t2 = r->n[2], t3 = r->n[3], t4 = r->n[4];
|
||||
|
||||
/* z0 tracks a possible raw value of 0, z1 tracks a possible raw value of P */
|
||||
uint64_t z0, z1;
|
||||
|
||||
/* Reduce t4 at the start so there will be at most a single carry from the first pass */
|
||||
uint64_t x = t4 >> 48; t4 &= 0x0FFFFFFFFFFFFULL;
|
||||
|
||||
/* The first pass ensures the magnitude is 1, ... */
|
||||
t0 += x * 0x1000003D1ULL;
|
||||
t1 += (t0 >> 52); t0 &= 0xFFFFFFFFFFFFFULL; z0 = t0; z1 = t0 ^ 0x1000003D0ULL;
|
||||
t2 += (t1 >> 52); t1 &= 0xFFFFFFFFFFFFFULL; z0 |= t1; z1 &= t1;
|
||||
t3 += (t2 >> 52); t2 &= 0xFFFFFFFFFFFFFULL; z0 |= t2; z1 &= t2;
|
||||
t4 += (t3 >> 52); t3 &= 0xFFFFFFFFFFFFFULL; z0 |= t3; z1 &= t3;
|
||||
z0 |= t4; z1 &= t4 ^ 0xF000000000000ULL;
|
||||
|
||||
/* ... except for a possible carry at bit 48 of t4 (i.e. bit 256 of the field element) */
|
||||
VERIFY_CHECK(t4 >> 49 == 0);
|
||||
|
||||
return (z0 == 0) | (z1 == 0xFFFFFFFFFFFFFULL);
|
||||
}
|
||||
|
||||
static int secp256k1_fe_normalizes_to_zero_var(secp256k1_fe_t *r) {
|
||||
uint64_t t0, t1, t2, t3, t4;
|
||||
uint64_t z0, z1;
|
||||
uint64_t x;
|
||||
|
||||
t0 = r->n[0];
|
||||
t4 = r->n[4];
|
||||
|
||||
/* Reduce t4 at the start so there will be at most a single carry from the first pass */
|
||||
x = t4 >> 48;
|
||||
|
||||
/* The first pass ensures the magnitude is 1, ... */
|
||||
t0 += x * 0x1000003D1ULL;
|
||||
|
||||
/* z0 tracks a possible raw value of 0, z1 tracks a possible raw value of P */
|
||||
z0 = t0 & 0xFFFFFFFFFFFFFULL;
|
||||
z1 = z0 ^ 0x1000003D0ULL;
|
||||
|
||||
/* Fast return path should catch the majority of cases */
|
||||
if ((z0 != 0ULL) & (z1 != 0xFFFFFFFFFFFFFULL)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
t1 = r->n[1];
|
||||
t2 = r->n[2];
|
||||
t3 = r->n[3];
|
||||
|
||||
t4 &= 0x0FFFFFFFFFFFFULL;
|
||||
|
||||
t1 += (t0 >> 52); t0 = z0;
|
||||
t2 += (t1 >> 52); t1 &= 0xFFFFFFFFFFFFFULL; z0 |= t1; z1 &= t1;
|
||||
t3 += (t2 >> 52); t2 &= 0xFFFFFFFFFFFFFULL; z0 |= t2; z1 &= t2;
|
||||
t4 += (t3 >> 52); t3 &= 0xFFFFFFFFFFFFFULL; z0 |= t3; z1 &= t3;
|
||||
z0 |= t4; z1 &= t4 ^ 0xF000000000000ULL;
|
||||
|
||||
/* ... except for a possible carry at bit 48 of t4 (i.e. bit 256 of the field element) */
|
||||
VERIFY_CHECK(t4 >> 49 == 0);
|
||||
|
||||
return (z0 == 0) | (z1 == 0xFFFFFFFFFFFFFULL);
|
||||
}
|
||||
|
||||
SECP256K1_INLINE static void secp256k1_fe_set_int(secp256k1_fe_t *r, int a) {
|
||||
r->n[0] = a;
|
||||
r->n[1] = r->n[2] = r->n[3] = r->n[4] = 0;
|
||||
#ifdef VERIFY
|
||||
r->magnitude = 1;
|
||||
r->normalized = 1;
|
||||
secp256k1_fe_verify(r);
|
||||
#endif
|
||||
}
|
||||
|
||||
SECP256K1_INLINE static int secp256k1_fe_is_zero(const secp256k1_fe_t *a) {
|
||||
const uint64_t *t = a->n;
|
||||
#ifdef VERIFY
|
||||
VERIFY_CHECK(a->normalized);
|
||||
secp256k1_fe_verify(a);
|
||||
#endif
|
||||
return (t[0] | t[1] | t[2] | t[3] | t[4]) == 0;
|
||||
}
|
||||
|
||||
SECP256K1_INLINE static int secp256k1_fe_is_odd(const secp256k1_fe_t *a) {
|
||||
#ifdef VERIFY
|
||||
VERIFY_CHECK(a->normalized);
|
||||
secp256k1_fe_verify(a);
|
||||
#endif
|
||||
return a->n[0] & 1;
|
||||
}
|
||||
|
||||
SECP256K1_INLINE static void secp256k1_fe_clear(secp256k1_fe_t *a) {
|
||||
int i;
|
||||
#ifdef VERIFY
|
||||
a->magnitude = 0;
|
||||
a->normalized = 1;
|
||||
#endif
|
||||
for (i=0; i<5; i++) {
|
||||
a->n[i] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
static int secp256k1_fe_cmp_var(const secp256k1_fe_t *a, const secp256k1_fe_t *b) {
|
||||
int i;
|
||||
#ifdef VERIFY
|
||||
VERIFY_CHECK(a->normalized);
|
||||
VERIFY_CHECK(b->normalized);
|
||||
secp256k1_fe_verify(a);
|
||||
secp256k1_fe_verify(b);
|
||||
#endif
|
||||
for (i = 4; i >= 0; i--) {
|
||||
if (a->n[i] > b->n[i]) {
|
||||
return 1;
|
||||
}
|
||||
if (a->n[i] < b->n[i]) {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int secp256k1_fe_set_b32(secp256k1_fe_t *r, const unsigned char *a) {
|
||||
int i;
|
||||
r->n[0] = r->n[1] = r->n[2] = r->n[3] = r->n[4] = 0;
|
||||
for (i=0; i<32; i++) {
|
||||
int j;
|
||||
for (j=0; j<2; j++) {
|
||||
int limb = (8*i+4*j)/52;
|
||||
int shift = (8*i+4*j)%52;
|
||||
r->n[limb] |= (uint64_t)((a[31-i] >> (4*j)) & 0xF) << shift;
|
||||
}
|
||||
}
|
||||
if (r->n[4] == 0x0FFFFFFFFFFFFULL && (r->n[3] & r->n[2] & r->n[1]) == 0xFFFFFFFFFFFFFULL && r->n[0] >= 0xFFFFEFFFFFC2FULL) {
|
||||
return 0;
|
||||
}
|
||||
#ifdef VERIFY
|
||||
r->magnitude = 1;
|
||||
r->normalized = 1;
|
||||
secp256k1_fe_verify(r);
|
||||
#endif
|
||||
return 1;
|
||||
}
|
||||
|
||||
/** Convert a field element to a 32-byte big endian value. Requires the input to be normalized */
|
||||
static void secp256k1_fe_get_b32(unsigned char *r, const secp256k1_fe_t *a) {
|
||||
int i;
|
||||
#ifdef VERIFY
|
||||
VERIFY_CHECK(a->normalized);
|
||||
secp256k1_fe_verify(a);
|
||||
#endif
|
||||
for (i=0; i<32; i++) {
|
||||
int j;
|
||||
int c = 0;
|
||||
for (j=0; j<2; j++) {
|
||||
int limb = (8*i+4*j)/52;
|
||||
int shift = (8*i+4*j)%52;
|
||||
c |= ((a->n[limb] >> shift) & 0xF) << (4 * j);
|
||||
}
|
||||
r[31-i] = c;
|
||||
}
|
||||
}
|
||||
|
||||
SECP256K1_INLINE static void secp256k1_fe_negate(secp256k1_fe_t *r, const secp256k1_fe_t *a, int m) {
|
||||
#ifdef VERIFY
|
||||
VERIFY_CHECK(a->magnitude <= m);
|
||||
secp256k1_fe_verify(a);
|
||||
#endif
|
||||
r->n[0] = 0xFFFFEFFFFFC2FULL * 2 * (m + 1) - a->n[0];
|
||||
r->n[1] = 0xFFFFFFFFFFFFFULL * 2 * (m + 1) - a->n[1];
|
||||
r->n[2] = 0xFFFFFFFFFFFFFULL * 2 * (m + 1) - a->n[2];
|
||||
r->n[3] = 0xFFFFFFFFFFFFFULL * 2 * (m + 1) - a->n[3];
|
||||
r->n[4] = 0x0FFFFFFFFFFFFULL * 2 * (m + 1) - a->n[4];
|
||||
#ifdef VERIFY
|
||||
r->magnitude = m + 1;
|
||||
r->normalized = 0;
|
||||
secp256k1_fe_verify(r);
|
||||
#endif
|
||||
}
|
||||
|
||||
SECP256K1_INLINE static void secp256k1_fe_mul_int(secp256k1_fe_t *r, int a) {
|
||||
r->n[0] *= a;
|
||||
r->n[1] *= a;
|
||||
r->n[2] *= a;
|
||||
r->n[3] *= a;
|
||||
r->n[4] *= a;
|
||||
#ifdef VERIFY
|
||||
r->magnitude *= a;
|
||||
r->normalized = 0;
|
||||
secp256k1_fe_verify(r);
|
||||
#endif
|
||||
}
|
||||
|
||||
SECP256K1_INLINE static void secp256k1_fe_add(secp256k1_fe_t *r, const secp256k1_fe_t *a) {
|
||||
#ifdef VERIFY
|
||||
secp256k1_fe_verify(a);
|
||||
#endif
|
||||
r->n[0] += a->n[0];
|
||||
r->n[1] += a->n[1];
|
||||
r->n[2] += a->n[2];
|
||||
r->n[3] += a->n[3];
|
||||
r->n[4] += a->n[4];
|
||||
#ifdef VERIFY
|
||||
r->magnitude += a->magnitude;
|
||||
r->normalized = 0;
|
||||
secp256k1_fe_verify(r);
|
||||
#endif
|
||||
}
|
||||
|
||||
static void secp256k1_fe_mul(secp256k1_fe_t *r, const secp256k1_fe_t *a, const secp256k1_fe_t * SECP256K1_RESTRICT b) {
|
||||
#ifdef VERIFY
|
||||
VERIFY_CHECK(a->magnitude <= 8);
|
||||
VERIFY_CHECK(b->magnitude <= 8);
|
||||
secp256k1_fe_verify(a);
|
||||
secp256k1_fe_verify(b);
|
||||
VERIFY_CHECK(r != b);
|
||||
#endif
|
||||
secp256k1_fe_mul_inner(r->n, a->n, b->n);
|
||||
#ifdef VERIFY
|
||||
r->magnitude = 1;
|
||||
r->normalized = 0;
|
||||
secp256k1_fe_verify(r);
|
||||
#endif
|
||||
}
|
||||
|
||||
static void secp256k1_fe_sqr(secp256k1_fe_t *r, const secp256k1_fe_t *a) {
|
||||
#ifdef VERIFY
|
||||
VERIFY_CHECK(a->magnitude <= 8);
|
||||
secp256k1_fe_verify(a);
|
||||
#endif
|
||||
secp256k1_fe_sqr_inner(r->n, a->n);
|
||||
#ifdef VERIFY
|
||||
r->magnitude = 1;
|
||||
r->normalized = 0;
|
||||
secp256k1_fe_verify(r);
|
||||
#endif
|
||||
}
|
||||
|
||||
static SECP256K1_INLINE void secp256k1_fe_storage_cmov(secp256k1_fe_storage_t *r, const secp256k1_fe_storage_t *a, int flag) {
|
||||
uint64_t mask0, mask1;
|
||||
mask0 = flag + ~((uint64_t)0);
|
||||
mask1 = ~mask0;
|
||||
r->n[0] = (r->n[0] & mask0) | (a->n[0] & mask1);
|
||||
r->n[1] = (r->n[1] & mask0) | (a->n[1] & mask1);
|
||||
r->n[2] = (r->n[2] & mask0) | (a->n[2] & mask1);
|
||||
r->n[3] = (r->n[3] & mask0) | (a->n[3] & mask1);
|
||||
}
|
||||
|
||||
static void secp256k1_fe_to_storage(secp256k1_fe_storage_t *r, const secp256k1_fe_t *a) {
|
||||
#ifdef VERIFY
|
||||
VERIFY_CHECK(a->normalized);
|
||||
#endif
|
||||
r->n[0] = a->n[0] | a->n[1] << 52;
|
||||
r->n[1] = a->n[1] >> 12 | a->n[2] << 40;
|
||||
r->n[2] = a->n[2] >> 24 | a->n[3] << 28;
|
||||
r->n[3] = a->n[3] >> 36 | a->n[4] << 16;
|
||||
}
|
||||
|
||||
static SECP256K1_INLINE void secp256k1_fe_from_storage(secp256k1_fe_t *r, const secp256k1_fe_storage_t *a) {
|
||||
r->n[0] = a->n[0] & 0xFFFFFFFFFFFFFULL;
|
||||
r->n[1] = a->n[0] >> 52 | ((a->n[1] << 12) & 0xFFFFFFFFFFFFFULL);
|
||||
r->n[2] = a->n[1] >> 40 | ((a->n[2] << 24) & 0xFFFFFFFFFFFFFULL);
|
||||
r->n[3] = a->n[2] >> 28 | ((a->n[3] << 36) & 0xFFFFFFFFFFFFFULL);
|
||||
r->n[4] = a->n[3] >> 16;
|
||||
#ifdef VERIFY
|
||||
r->magnitude = 1;
|
||||
r->normalized = 1;
|
||||
#endif
|
||||
}
|
||||
|
||||
#endif
|
||||
277
crypto/secp256k1/secp256k1/src/field_5x52_int128_impl.h
Normal file
277
crypto/secp256k1/secp256k1/src/field_5x52_int128_impl.h
Normal file
|
|
@ -0,0 +1,277 @@
|
|||
/**********************************************************************
|
||||
* Copyright (c) 2013, 2014 Pieter Wuille *
|
||||
* Distributed under the MIT software license, see the accompanying *
|
||||
* file COPYING or http://www.opensource.org/licenses/mit-license.php.*
|
||||
**********************************************************************/
|
||||
|
||||
#ifndef _SECP256K1_FIELD_INNER5X52_IMPL_H_
|
||||
#define _SECP256K1_FIELD_INNER5X52_IMPL_H_
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
#ifdef VERIFY
|
||||
#define VERIFY_BITS(x, n) VERIFY_CHECK(((x) >> (n)) == 0)
|
||||
#else
|
||||
#define VERIFY_BITS(x, n) do { } while(0)
|
||||
#endif
|
||||
|
||||
SECP256K1_INLINE static void secp256k1_fe_mul_inner(uint64_t *r, const uint64_t *a, const uint64_t * SECP256K1_RESTRICT b) {
|
||||
uint128_t c, d;
|
||||
uint64_t t3, t4, tx, u0;
|
||||
uint64_t a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3], a4 = a[4];
|
||||
const uint64_t M = 0xFFFFFFFFFFFFFULL, R = 0x1000003D10ULL;
|
||||
|
||||
VERIFY_BITS(a[0], 56);
|
||||
VERIFY_BITS(a[1], 56);
|
||||
VERIFY_BITS(a[2], 56);
|
||||
VERIFY_BITS(a[3], 56);
|
||||
VERIFY_BITS(a[4], 52);
|
||||
VERIFY_BITS(b[0], 56);
|
||||
VERIFY_BITS(b[1], 56);
|
||||
VERIFY_BITS(b[2], 56);
|
||||
VERIFY_BITS(b[3], 56);
|
||||
VERIFY_BITS(b[4], 52);
|
||||
VERIFY_CHECK(r != b);
|
||||
|
||||
/* [... a b c] is a shorthand for ... + a<<104 + b<<52 + c<<0 mod n.
|
||||
* px is a shorthand for sum(a[i]*b[x-i], i=0..x).
|
||||
* Note that [x 0 0 0 0 0] = [x*R].
|
||||
*/
|
||||
|
||||
d = (uint128_t)a0 * b[3]
|
||||
+ (uint128_t)a1 * b[2]
|
||||
+ (uint128_t)a2 * b[1]
|
||||
+ (uint128_t)a3 * b[0];
|
||||
VERIFY_BITS(d, 114);
|
||||
/* [d 0 0 0] = [p3 0 0 0] */
|
||||
c = (uint128_t)a4 * b[4];
|
||||
VERIFY_BITS(c, 112);
|
||||
/* [c 0 0 0 0 d 0 0 0] = [p8 0 0 0 0 p3 0 0 0] */
|
||||
d += (c & M) * R; c >>= 52;
|
||||
VERIFY_BITS(d, 115);
|
||||
VERIFY_BITS(c, 60);
|
||||
/* [c 0 0 0 0 0 d 0 0 0] = [p8 0 0 0 0 p3 0 0 0] */
|
||||
t3 = d & M; d >>= 52;
|
||||
VERIFY_BITS(t3, 52);
|
||||
VERIFY_BITS(d, 63);
|
||||
/* [c 0 0 0 0 d t3 0 0 0] = [p8 0 0 0 0 p3 0 0 0] */
|
||||
|
||||
d += (uint128_t)a0 * b[4]
|
||||
+ (uint128_t)a1 * b[3]
|
||||
+ (uint128_t)a2 * b[2]
|
||||
+ (uint128_t)a3 * b[1]
|
||||
+ (uint128_t)a4 * b[0];
|
||||
VERIFY_BITS(d, 115);
|
||||
/* [c 0 0 0 0 d t3 0 0 0] = [p8 0 0 0 p4 p3 0 0 0] */
|
||||
d += c * R;
|
||||
VERIFY_BITS(d, 116);
|
||||
/* [d t3 0 0 0] = [p8 0 0 0 p4 p3 0 0 0] */
|
||||
t4 = d & M; d >>= 52;
|
||||
VERIFY_BITS(t4, 52);
|
||||
VERIFY_BITS(d, 64);
|
||||
/* [d t4 t3 0 0 0] = [p8 0 0 0 p4 p3 0 0 0] */
|
||||
tx = (t4 >> 48); t4 &= (M >> 4);
|
||||
VERIFY_BITS(tx, 4);
|
||||
VERIFY_BITS(t4, 48);
|
||||
/* [d t4+(tx<<48) t3 0 0 0] = [p8 0 0 0 p4 p3 0 0 0] */
|
||||
|
||||
c = (uint128_t)a0 * b[0];
|
||||
VERIFY_BITS(c, 112);
|
||||
/* [d t4+(tx<<48) t3 0 0 c] = [p8 0 0 0 p4 p3 0 0 p0] */
|
||||
d += (uint128_t)a1 * b[4]
|
||||
+ (uint128_t)a2 * b[3]
|
||||
+ (uint128_t)a3 * b[2]
|
||||
+ (uint128_t)a4 * b[1];
|
||||
VERIFY_BITS(d, 115);
|
||||
/* [d t4+(tx<<48) t3 0 0 c] = [p8 0 0 p5 p4 p3 0 0 p0] */
|
||||
u0 = d & M; d >>= 52;
|
||||
VERIFY_BITS(u0, 52);
|
||||
VERIFY_BITS(d, 63);
|
||||
/* [d u0 t4+(tx<<48) t3 0 0 c] = [p8 0 0 p5 p4 p3 0 0 p0] */
|
||||
/* [d 0 t4+(tx<<48)+(u0<<52) t3 0 0 c] = [p8 0 0 p5 p4 p3 0 0 p0] */
|
||||
u0 = (u0 << 4) | tx;
|
||||
VERIFY_BITS(u0, 56);
|
||||
/* [d 0 t4+(u0<<48) t3 0 0 c] = [p8 0 0 p5 p4 p3 0 0 p0] */
|
||||
c += (uint128_t)u0 * (R >> 4);
|
||||
VERIFY_BITS(c, 115);
|
||||
/* [d 0 t4 t3 0 0 c] = [p8 0 0 p5 p4 p3 0 0 p0] */
|
||||
r[0] = c & M; c >>= 52;
|
||||
VERIFY_BITS(r[0], 52);
|
||||
VERIFY_BITS(c, 61);
|
||||
/* [d 0 t4 t3 0 c r0] = [p8 0 0 p5 p4 p3 0 0 p0] */
|
||||
|
||||
c += (uint128_t)a0 * b[1]
|
||||
+ (uint128_t)a1 * b[0];
|
||||
VERIFY_BITS(c, 114);
|
||||
/* [d 0 t4 t3 0 c r0] = [p8 0 0 p5 p4 p3 0 p1 p0] */
|
||||
d += (uint128_t)a2 * b[4]
|
||||
+ (uint128_t)a3 * b[3]
|
||||
+ (uint128_t)a4 * b[2];
|
||||
VERIFY_BITS(d, 114);
|
||||
/* [d 0 t4 t3 0 c r0] = [p8 0 p6 p5 p4 p3 0 p1 p0] */
|
||||
c += (d & M) * R; d >>= 52;
|
||||
VERIFY_BITS(c, 115);
|
||||
VERIFY_BITS(d, 62);
|
||||
/* [d 0 0 t4 t3 0 c r0] = [p8 0 p6 p5 p4 p3 0 p1 p0] */
|
||||
r[1] = c & M; c >>= 52;
|
||||
VERIFY_BITS(r[1], 52);
|
||||
VERIFY_BITS(c, 63);
|
||||
/* [d 0 0 t4 t3 c r1 r0] = [p8 0 p6 p5 p4 p3 0 p1 p0] */
|
||||
|
||||
c += (uint128_t)a0 * b[2]
|
||||
+ (uint128_t)a1 * b[1]
|
||||
+ (uint128_t)a2 * b[0];
|
||||
VERIFY_BITS(c, 114);
|
||||
/* [d 0 0 t4 t3 c r1 r0] = [p8 0 p6 p5 p4 p3 p2 p1 p0] */
|
||||
d += (uint128_t)a3 * b[4]
|
||||
+ (uint128_t)a4 * b[3];
|
||||
VERIFY_BITS(d, 114);
|
||||
/* [d 0 0 t4 t3 c t1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */
|
||||
c += (d & M) * R; d >>= 52;
|
||||
VERIFY_BITS(c, 115);
|
||||
VERIFY_BITS(d, 62);
|
||||
/* [d 0 0 0 t4 t3 c r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */
|
||||
|
||||
/* [d 0 0 0 t4 t3 c r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */
|
||||
r[2] = c & M; c >>= 52;
|
||||
VERIFY_BITS(r[2], 52);
|
||||
VERIFY_BITS(c, 63);
|
||||
/* [d 0 0 0 t4 t3+c r2 r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */
|
||||
c += d * R + t3;;
|
||||
VERIFY_BITS(c, 100);
|
||||
/* [t4 c r2 r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */
|
||||
r[3] = c & M; c >>= 52;
|
||||
VERIFY_BITS(r[3], 52);
|
||||
VERIFY_BITS(c, 48);
|
||||
/* [t4+c r3 r2 r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */
|
||||
c += t4;
|
||||
VERIFY_BITS(c, 49);
|
||||
/* [c r3 r2 r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */
|
||||
r[4] = c;
|
||||
VERIFY_BITS(r[4], 49);
|
||||
/* [r4 r3 r2 r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */
|
||||
}
|
||||
|
||||
SECP256K1_INLINE static void secp256k1_fe_sqr_inner(uint64_t *r, const uint64_t *a) {
|
||||
uint128_t c, d;
|
||||
uint64_t a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3], a4 = a[4];
|
||||
int64_t t3, t4, tx, u0;
|
||||
const uint64_t M = 0xFFFFFFFFFFFFFULL, R = 0x1000003D10ULL;
|
||||
|
||||
VERIFY_BITS(a[0], 56);
|
||||
VERIFY_BITS(a[1], 56);
|
||||
VERIFY_BITS(a[2], 56);
|
||||
VERIFY_BITS(a[3], 56);
|
||||
VERIFY_BITS(a[4], 52);
|
||||
|
||||
/** [... a b c] is a shorthand for ... + a<<104 + b<<52 + c<<0 mod n.
|
||||
* px is a shorthand for sum(a[i]*a[x-i], i=0..x).
|
||||
* Note that [x 0 0 0 0 0] = [x*R].
|
||||
*/
|
||||
|
||||
d = (uint128_t)(a0*2) * a3
|
||||
+ (uint128_t)(a1*2) * a2;
|
||||
VERIFY_BITS(d, 114);
|
||||
/* [d 0 0 0] = [p3 0 0 0] */
|
||||
c = (uint128_t)a4 * a4;
|
||||
VERIFY_BITS(c, 112);
|
||||
/* [c 0 0 0 0 d 0 0 0] = [p8 0 0 0 0 p3 0 0 0] */
|
||||
d += (c & M) * R; c >>= 52;
|
||||
VERIFY_BITS(d, 115);
|
||||
VERIFY_BITS(c, 60);
|
||||
/* [c 0 0 0 0 0 d 0 0 0] = [p8 0 0 0 0 p3 0 0 0] */
|
||||
t3 = d & M; d >>= 52;
|
||||
VERIFY_BITS(t3, 52);
|
||||
VERIFY_BITS(d, 63);
|
||||
/* [c 0 0 0 0 d t3 0 0 0] = [p8 0 0 0 0 p3 0 0 0] */
|
||||
|
||||
a4 *= 2;
|
||||
d += (uint128_t)a0 * a4
|
||||
+ (uint128_t)(a1*2) * a3
|
||||
+ (uint128_t)a2 * a2;
|
||||
VERIFY_BITS(d, 115);
|
||||
/* [c 0 0 0 0 d t3 0 0 0] = [p8 0 0 0 p4 p3 0 0 0] */
|
||||
d += c * R;
|
||||
VERIFY_BITS(d, 116);
|
||||
/* [d t3 0 0 0] = [p8 0 0 0 p4 p3 0 0 0] */
|
||||
t4 = d & M; d >>= 52;
|
||||
VERIFY_BITS(t4, 52);
|
||||
VERIFY_BITS(d, 64);
|
||||
/* [d t4 t3 0 0 0] = [p8 0 0 0 p4 p3 0 0 0] */
|
||||
tx = (t4 >> 48); t4 &= (M >> 4);
|
||||
VERIFY_BITS(tx, 4);
|
||||
VERIFY_BITS(t4, 48);
|
||||
/* [d t4+(tx<<48) t3 0 0 0] = [p8 0 0 0 p4 p3 0 0 0] */
|
||||
|
||||
c = (uint128_t)a0 * a0;
|
||||
VERIFY_BITS(c, 112);
|
||||
/* [d t4+(tx<<48) t3 0 0 c] = [p8 0 0 0 p4 p3 0 0 p0] */
|
||||
d += (uint128_t)a1 * a4
|
||||
+ (uint128_t)(a2*2) * a3;
|
||||
VERIFY_BITS(d, 114);
|
||||
/* [d t4+(tx<<48) t3 0 0 c] = [p8 0 0 p5 p4 p3 0 0 p0] */
|
||||
u0 = d & M; d >>= 52;
|
||||
VERIFY_BITS(u0, 52);
|
||||
VERIFY_BITS(d, 62);
|
||||
/* [d u0 t4+(tx<<48) t3 0 0 c] = [p8 0 0 p5 p4 p3 0 0 p0] */
|
||||
/* [d 0 t4+(tx<<48)+(u0<<52) t3 0 0 c] = [p8 0 0 p5 p4 p3 0 0 p0] */
|
||||
u0 = (u0 << 4) | tx;
|
||||
VERIFY_BITS(u0, 56);
|
||||
/* [d 0 t4+(u0<<48) t3 0 0 c] = [p8 0 0 p5 p4 p3 0 0 p0] */
|
||||
c += (uint128_t)u0 * (R >> 4);
|
||||
VERIFY_BITS(c, 113);
|
||||
/* [d 0 t4 t3 0 0 c] = [p8 0 0 p5 p4 p3 0 0 p0] */
|
||||
r[0] = c & M; c >>= 52;
|
||||
VERIFY_BITS(r[0], 52);
|
||||
VERIFY_BITS(c, 61);
|
||||
/* [d 0 t4 t3 0 c r0] = [p8 0 0 p5 p4 p3 0 0 p0] */
|
||||
|
||||
a0 *= 2;
|
||||
c += (uint128_t)a0 * a1;
|
||||
VERIFY_BITS(c, 114);
|
||||
/* [d 0 t4 t3 0 c r0] = [p8 0 0 p5 p4 p3 0 p1 p0] */
|
||||
d += (uint128_t)a2 * a4
|
||||
+ (uint128_t)a3 * a3;
|
||||
VERIFY_BITS(d, 114);
|
||||
/* [d 0 t4 t3 0 c r0] = [p8 0 p6 p5 p4 p3 0 p1 p0] */
|
||||
c += (d & M) * R; d >>= 52;
|
||||
VERIFY_BITS(c, 115);
|
||||
VERIFY_BITS(d, 62);
|
||||
/* [d 0 0 t4 t3 0 c r0] = [p8 0 p6 p5 p4 p3 0 p1 p0] */
|
||||
r[1] = c & M; c >>= 52;
|
||||
VERIFY_BITS(r[1], 52);
|
||||
VERIFY_BITS(c, 63);
|
||||
/* [d 0 0 t4 t3 c r1 r0] = [p8 0 p6 p5 p4 p3 0 p1 p0] */
|
||||
|
||||
c += (uint128_t)a0 * a2
|
||||
+ (uint128_t)a1 * a1;
|
||||
VERIFY_BITS(c, 114);
|
||||
/* [d 0 0 t4 t3 c r1 r0] = [p8 0 p6 p5 p4 p3 p2 p1 p0] */
|
||||
d += (uint128_t)a3 * a4;
|
||||
VERIFY_BITS(d, 114);
|
||||
/* [d 0 0 t4 t3 c r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */
|
||||
c += (d & M) * R; d >>= 52;
|
||||
VERIFY_BITS(c, 115);
|
||||
VERIFY_BITS(d, 62);
|
||||
/* [d 0 0 0 t4 t3 c r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */
|
||||
r[2] = c & M; c >>= 52;
|
||||
VERIFY_BITS(r[2], 52);
|
||||
VERIFY_BITS(c, 63);
|
||||
/* [d 0 0 0 t4 t3+c r2 r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */
|
||||
|
||||
c += d * R + t3;;
|
||||
VERIFY_BITS(c, 100);
|
||||
/* [t4 c r2 r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */
|
||||
r[3] = c & M; c >>= 52;
|
||||
VERIFY_BITS(r[3], 52);
|
||||
VERIFY_BITS(c, 48);
|
||||
/* [t4+c r3 r2 r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */
|
||||
c += t4;
|
||||
VERIFY_BITS(c, 49);
|
||||
/* [c r3 r2 r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */
|
||||
r[4] = c;
|
||||
VERIFY_BITS(r[4], 49);
|
||||
/* [r4 r3 r2 r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */
|
||||
}
|
||||
|
||||
#endif
|
||||
|
|
@ -1,19 +0,0 @@
|
|||
// Copyright (c) 2013 Pieter Wuille
|
||||
// Distributed under the MIT/X11 software license, see the accompanying
|
||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||
|
||||
#ifndef _SECP256K1_FIELD_REPR_
|
||||
#define _SECP256K1_FIELD_REPR_
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
typedef struct {
|
||||
// X = sum(i=0..4, elem[i]*2^64) mod n
|
||||
uint64_t n[5];
|
||||
#ifdef VERIFY
|
||||
int reduced; // n[4] == 0
|
||||
int normalized; // reduced and X < 2^256 - 0x100003D1
|
||||
#endif
|
||||
} secp256k1_fe_t;
|
||||
|
||||
#endif
|
||||
|
|
@ -1,332 +0,0 @@
|
|||
;; Added by Diederik Huys, March 2013
|
||||
;;
|
||||
;; Provided public procedures:
|
||||
;; secp256k1_fe_mul_inner
|
||||
;; secp256k1_fe_sqr_inner
|
||||
;;
|
||||
;; Needed tools: YASM (http://yasm.tortall.net)
|
||||
;;
|
||||
;;
|
||||
|
||||
BITS 64
|
||||
|
||||
COMP_LIMB EQU 000000001000003D1h
|
||||
|
||||
;; Procedure ExSetMult
|
||||
;; Register Layout:
|
||||
;; INPUT: rdi = a->n
|
||||
;; rsi = b->n
|
||||
;; rdx = r->a
|
||||
;;
|
||||
;; INTERNAL: rdx:rax = multiplication accumulator
|
||||
;; r8-r10 = c0-c2
|
||||
;; r11-r15 = b.n[0]-b.n[4] / r3 - r7
|
||||
;; rbx = r0
|
||||
;; rcx = r1
|
||||
;; rbp = r2
|
||||
;;
|
||||
GLOBAL secp256k1_fe_mul_inner
|
||||
ALIGN 32
|
||||
secp256k1_fe_mul_inner:
|
||||
push rbp
|
||||
push rbx
|
||||
push r12
|
||||
push r13
|
||||
push r14
|
||||
push r15
|
||||
push rdx
|
||||
|
||||
mov r11,[rsi+8*0] ; preload b.n[0]
|
||||
|
||||
;; step 1: mul_c2
|
||||
mov rax,[rdi+0*8] ; load a.n[0]
|
||||
mul r11 ; rdx:rax=a.n[0]*b.n[0]
|
||||
mov r12,[rsi+1*8] ; preload b.n[1]
|
||||
mov rbx,rax ; retire LO qword (r[0])
|
||||
mov r8,rdx ; save overflow
|
||||
xor r9,r9 ; overflow HO qwords
|
||||
xor r10,r10
|
||||
|
||||
;; c+=a.n[0] * b.n[1] + a.n[1] * b.n[0]
|
||||
mov rax,[rdi+0*8]
|
||||
mul r12
|
||||
mov r13,[rsi+2*8] ; preload b.n[2]
|
||||
add r8,rax ; still the same :-)
|
||||
adc r9,rdx ;
|
||||
adc r10,0 ; mmm...
|
||||
|
||||
mov rax,[rdi+1*8]
|
||||
mul r11
|
||||
add r8,rax
|
||||
adc r9,rdx
|
||||
adc r10,0
|
||||
mov rcx,r8 ; retire r[1]
|
||||
xor r8,r8
|
||||
|
||||
;; c+=a.n[0 1 2] * b.n[2 1 0]
|
||||
mov rax,[rdi+0*8]
|
||||
mul r13
|
||||
mov r14,[rsi+3*8] ; preload b.n[3]
|
||||
add r9,rax
|
||||
adc r10,rdx
|
||||
adc r8,0
|
||||
|
||||
mov rax,[rdi+1*8]
|
||||
mul r12
|
||||
add r9,rax
|
||||
adc r10,rdx
|
||||
adc r8,0
|
||||
|
||||
mov rax,[rdi+2*8]
|
||||
mul r11
|
||||
add r9,rax
|
||||
adc r10,rdx
|
||||
adc r8,0
|
||||
mov rbp,r9 ; retire r[2]
|
||||
xor r9,r9
|
||||
|
||||
;; c+=a.n[0 1 2 3] * b.n[3 2 1 0]
|
||||
mov rax,[rdi+0*8]
|
||||
mul r14
|
||||
add r10,rax
|
||||
adc r8,rdx
|
||||
adc r9,0
|
||||
|
||||
mov rax,[rdi+1*8]
|
||||
mul r13
|
||||
add r10,rax
|
||||
adc r8,rdx
|
||||
adc r9,0
|
||||
|
||||
mov rax,[rdi+2*8]
|
||||
mul r12
|
||||
add r10,rax
|
||||
adc r8,rdx
|
||||
adc r9,0
|
||||
|
||||
mov rax,[rdi+3*8]
|
||||
mul r11
|
||||
add r10,rax
|
||||
adc r8,rdx
|
||||
adc r9,0
|
||||
mov r11,r10 ; retire r[3]
|
||||
xor r10,r10
|
||||
|
||||
;; c+=a.n[1 2 3] * b.n[3 2 1]
|
||||
mov rax,[rdi+1*8]
|
||||
mul r14
|
||||
add r8,rax
|
||||
adc r9,rdx
|
||||
adc r10,0
|
||||
|
||||
mov rax,[rdi+2*8]
|
||||
mul r13
|
||||
add r8,rax
|
||||
adc r9,rdx
|
||||
adc r10,0
|
||||
|
||||
mov rax,[rdi+3*8]
|
||||
mul r12
|
||||
add r8,rax
|
||||
adc r9,rdx
|
||||
adc r10,0
|
||||
mov r12,r8 ; retire r[4]
|
||||
xor r8,r8
|
||||
|
||||
;; c+=a.n[2 3] * b.n[3 2]
|
||||
mov rax,[rdi+2*8]
|
||||
mul r14
|
||||
add r9,rax ; still the same :-)
|
||||
adc r10,rdx ;
|
||||
adc r8,0 ; mmm...
|
||||
|
||||
mov rax,[rdi+3*8]
|
||||
mul r13
|
||||
add r9,rax
|
||||
adc r10,rdx
|
||||
adc r8,0
|
||||
mov r13,r9 ; retire r[5]
|
||||
xor r9,r9
|
||||
|
||||
;; c+=a.n[3] * b.n[3]
|
||||
mov rax,[rdi+3*8]
|
||||
mul r14
|
||||
add r10,rax
|
||||
adc r8,rdx
|
||||
|
||||
mov r14,r10
|
||||
mov r15,r8
|
||||
|
||||
|
||||
;; *******************************************************
|
||||
common_exit_norm:
|
||||
mov rdi,COMP_LIMB
|
||||
mov rax,r12
|
||||
mul rdi
|
||||
add rax,rbx
|
||||
adc rcx,rdx
|
||||
pop rbx
|
||||
mov [rbx],rax
|
||||
|
||||
mov rax,r13 ; get r5
|
||||
mul rdi
|
||||
add rax,rcx ; +r1
|
||||
adc rbp,rdx
|
||||
mov [rbx+1*8],rax
|
||||
|
||||
mov rax,r14 ; get r6
|
||||
mul rdi
|
||||
add rax,rbp ; +r2
|
||||
adc r11,rdx
|
||||
mov [rbx+2*8],rax
|
||||
|
||||
mov rax,r15 ; get r7
|
||||
mul rdi
|
||||
add rax,r11 ; +r3
|
||||
adc rdx,0
|
||||
mov [rbx+3*8],rax
|
||||
mov [rbx+4*8],rdx
|
||||
|
||||
pop r15
|
||||
pop r14
|
||||
pop r13
|
||||
pop r12
|
||||
pop rbx
|
||||
pop rbp
|
||||
ret
|
||||
|
||||
|
||||
;; PROC ExSetSquare
|
||||
;; Register Layout:
|
||||
;; INPUT: rdi = a.n
|
||||
;; rsi = this.a
|
||||
;; INTERNAL: rdx:rax = multiplication accumulator
|
||||
;; r8-r10 = c
|
||||
;; r11-r15 = a.n[0]-a.n[4] / r3-r7
|
||||
;; rbx = r0
|
||||
;; rcx = r1
|
||||
;; rbp = r2
|
||||
GLOBAL secp256k1_fe_sqr_inner
|
||||
|
||||
ALIGN 32
|
||||
secp256k1_fe_sqr_inner:
|
||||
push rbp
|
||||
push rbx
|
||||
push r12
|
||||
push r13
|
||||
push r14
|
||||
push r15
|
||||
push rsi
|
||||
|
||||
mov r11,[rdi+8*0] ; preload a.n[0]
|
||||
|
||||
;; step 1: mul_c2
|
||||
mov rax,r11 ; load a.n[0]
|
||||
mul rax ; rdx:rax=a.n[0]²
|
||||
mov r12,[rdi+1*8] ; preload a.n[1]
|
||||
mov rbx,rax ; retire LO qword (r[0])
|
||||
mov r8,rdx ; save overflow
|
||||
xor r9,r9 ; overflow HO qwords
|
||||
xor r10,r10
|
||||
|
||||
;; c+=2*a.n[0] * a.n[1]
|
||||
mov rax,r11 ; load a.n[0]
|
||||
mul r12 ; rdx:rax=a.n[0] * a.n[1]
|
||||
mov r13,[rdi+2*8] ; preload a.n[2]
|
||||
add rax,rax ; rdx:rax*=2
|
||||
adc rdx,rdx
|
||||
adc r10,0
|
||||
add r8,rax ; still the same :-)
|
||||
adc r9,rdx
|
||||
adc r10,0 ; mmm...
|
||||
|
||||
mov rcx,r8 ; retire r[1]
|
||||
xor r8,r8
|
||||
|
||||
;; c+=2*a.n[0]*a.n[2]+a.n[1]*a.n[1]
|
||||
mov rax,r11 ; load a.n[0]
|
||||
mul r13 ; * a.n[2]
|
||||
mov r14,[rdi+3*8] ; preload a.n[3]
|
||||
add rax,rax ; rdx:rax*=2
|
||||
adc rdx,rdx
|
||||
adc r8,0
|
||||
add r9,rax
|
||||
adc r10,rdx
|
||||
adc r8,0
|
||||
|
||||
mov rax,r12
|
||||
mul rax
|
||||
add r9,rax
|
||||
adc r10,rdx
|
||||
adc r8,0
|
||||
|
||||
|
||||
mov rbp,r9
|
||||
xor r9,r9
|
||||
|
||||
;; c+=2*a.n[0]*a.n[3]+2*a.n[1]*a.n[2]
|
||||
mov rax,r11 ; load a.n[0]
|
||||
mul r14 ; * a.n[3]
|
||||
add rax,rax ; rdx:rax*=2
|
||||
adc rdx,rdx
|
||||
adc r9,0
|
||||
add r10,rax
|
||||
adc r8,rdx
|
||||
adc r9,0
|
||||
|
||||
mov rax,r12 ; load a.n[1]
|
||||
mul r13 ; * a.n[2]
|
||||
add rax,rax
|
||||
adc rdx,rdx
|
||||
adc r9,0
|
||||
add r10,rax
|
||||
adc r8,rdx
|
||||
adc r9,0
|
||||
|
||||
mov r11,r10
|
||||
xor r10,r10
|
||||
|
||||
;; c+=2*a.n[1]*a.n[3]+a.n[2]*a.n[2]
|
||||
mov rax,r12 ; load a.n[1]
|
||||
mul r14 ; * a.n[3]
|
||||
add rax,rax ; rdx:rax*=2
|
||||
adc rdx,rdx
|
||||
adc r10,0
|
||||
add r8,rax
|
||||
adc r9,rdx
|
||||
adc r10,0
|
||||
|
||||
mov rax,r13
|
||||
mul rax
|
||||
add r8,rax
|
||||
adc r9,rdx
|
||||
adc r10,0
|
||||
|
||||
mov r12,r8
|
||||
xor r8,r8
|
||||
;; c+=2*a.n[2]*a.n[3]
|
||||
mov rax,r13 ; load a.n[2]
|
||||
mul r14 ; * a.n[3]
|
||||
add rax,rax ; rdx:rax*=2
|
||||
adc rdx,rdx
|
||||
adc r8,0
|
||||
add r9,rax
|
||||
adc r10,rdx
|
||||
adc r8,0
|
||||
|
||||
mov r13,r9
|
||||
xor r9,r9
|
||||
|
||||
;; c+=a.n[3]²
|
||||
mov rax,r14
|
||||
mul rax
|
||||
add r10,rax
|
||||
adc r8,rdx
|
||||
|
||||
mov r14,r10
|
||||
mov r15,r8
|
||||
|
||||
jmp common_exit_norm
|
||||
end
|
||||
|
||||
|
||||
|
|
@ -1,16 +0,0 @@
|
|||
// Copyright (c) 2013 Pieter Wuille
|
||||
// Distributed under the MIT/X11 software license, see the accompanying
|
||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||
|
||||
#ifndef _SECP256K1_FIELD_REPR_
|
||||
#define _SECP256K1_FIELD_REPR_
|
||||
|
||||
#include <gmp.h>
|
||||
|
||||
#define FIELD_LIMBS ((256 + GMP_NUMB_BITS - 1) / GMP_NUMB_BITS)
|
||||
|
||||
typedef struct {
|
||||
mp_limb_t n[FIELD_LIMBS+1];
|
||||
} secp256k1_fe_t;
|
||||
|
||||
#endif
|
||||
263
crypto/secp256k1/secp256k1/src/field_impl.h
Normal file
263
crypto/secp256k1/secp256k1/src/field_impl.h
Normal file
|
|
@ -0,0 +1,263 @@
|
|||
/**********************************************************************
|
||||
* Copyright (c) 2013, 2014 Pieter Wuille *
|
||||
* Distributed under the MIT software license, see the accompanying *
|
||||
* file COPYING or http://www.opensource.org/licenses/mit-license.php.*
|
||||
**********************************************************************/
|
||||
|
||||
#ifndef _SECP256K1_FIELD_IMPL_H_
|
||||
#define _SECP256K1_FIELD_IMPL_H_
|
||||
|
||||
#if defined HAVE_CONFIG_H
|
||||
#include "libsecp256k1-config.h"
|
||||
#endif
|
||||
|
||||
#include "util.h"
|
||||
|
||||
#if defined(USE_FIELD_10X26)
|
||||
#include "field_10x26_impl.h"
|
||||
#elif defined(USE_FIELD_5X52)
|
||||
#include "field_5x52_impl.h"
|
||||
#else
|
||||
#error "Please select field implementation"
|
||||
#endif
|
||||
|
||||
SECP256K1_INLINE static int secp256k1_fe_equal_var(const secp256k1_fe_t *a, const secp256k1_fe_t *b) {
|
||||
secp256k1_fe_t na;
|
||||
secp256k1_fe_negate(&na, a, 1);
|
||||
secp256k1_fe_add(&na, b);
|
||||
return secp256k1_fe_normalizes_to_zero_var(&na);
|
||||
}
|
||||
|
||||
static int secp256k1_fe_sqrt_var(secp256k1_fe_t *r, const secp256k1_fe_t *a) {
|
||||
secp256k1_fe_t x2, x3, x6, x9, x11, x22, x44, x88, x176, x220, x223, t1;
|
||||
int j;
|
||||
|
||||
/** The binary representation of (p + 1)/4 has 3 blocks of 1s, with lengths in
|
||||
* { 2, 22, 223 }. Use an addition chain to calculate 2^n - 1 for each block:
|
||||
* 1, [2], 3, 6, 9, 11, [22], 44, 88, 176, 220, [223]
|
||||
*/
|
||||
|
||||
secp256k1_fe_sqr(&x2, a);
|
||||
secp256k1_fe_mul(&x2, &x2, a);
|
||||
|
||||
secp256k1_fe_sqr(&x3, &x2);
|
||||
secp256k1_fe_mul(&x3, &x3, a);
|
||||
|
||||
x6 = x3;
|
||||
for (j=0; j<3; j++) {
|
||||
secp256k1_fe_sqr(&x6, &x6);
|
||||
}
|
||||
secp256k1_fe_mul(&x6, &x6, &x3);
|
||||
|
||||
x9 = x6;
|
||||
for (j=0; j<3; j++) {
|
||||
secp256k1_fe_sqr(&x9, &x9);
|
||||
}
|
||||
secp256k1_fe_mul(&x9, &x9, &x3);
|
||||
|
||||
x11 = x9;
|
||||
for (j=0; j<2; j++) {
|
||||
secp256k1_fe_sqr(&x11, &x11);
|
||||
}
|
||||
secp256k1_fe_mul(&x11, &x11, &x2);
|
||||
|
||||
x22 = x11;
|
||||
for (j=0; j<11; j++) {
|
||||
secp256k1_fe_sqr(&x22, &x22);
|
||||
}
|
||||
secp256k1_fe_mul(&x22, &x22, &x11);
|
||||
|
||||
x44 = x22;
|
||||
for (j=0; j<22; j++) {
|
||||
secp256k1_fe_sqr(&x44, &x44);
|
||||
}
|
||||
secp256k1_fe_mul(&x44, &x44, &x22);
|
||||
|
||||
x88 = x44;
|
||||
for (j=0; j<44; j++) {
|
||||
secp256k1_fe_sqr(&x88, &x88);
|
||||
}
|
||||
secp256k1_fe_mul(&x88, &x88, &x44);
|
||||
|
||||
x176 = x88;
|
||||
for (j=0; j<88; j++) {
|
||||
secp256k1_fe_sqr(&x176, &x176);
|
||||
}
|
||||
secp256k1_fe_mul(&x176, &x176, &x88);
|
||||
|
||||
x220 = x176;
|
||||
for (j=0; j<44; j++) {
|
||||
secp256k1_fe_sqr(&x220, &x220);
|
||||
}
|
||||
secp256k1_fe_mul(&x220, &x220, &x44);
|
||||
|
||||
x223 = x220;
|
||||
for (j=0; j<3; j++) {
|
||||
secp256k1_fe_sqr(&x223, &x223);
|
||||
}
|
||||
secp256k1_fe_mul(&x223, &x223, &x3);
|
||||
|
||||
/* The final result is then assembled using a sliding window over the blocks. */
|
||||
|
||||
t1 = x223;
|
||||
for (j=0; j<23; j++) {
|
||||
secp256k1_fe_sqr(&t1, &t1);
|
||||
}
|
||||
secp256k1_fe_mul(&t1, &t1, &x22);
|
||||
for (j=0; j<6; j++) {
|
||||
secp256k1_fe_sqr(&t1, &t1);
|
||||
}
|
||||
secp256k1_fe_mul(&t1, &t1, &x2);
|
||||
secp256k1_fe_sqr(&t1, &t1);
|
||||
secp256k1_fe_sqr(r, &t1);
|
||||
|
||||
/* Check that a square root was actually calculated */
|
||||
|
||||
secp256k1_fe_sqr(&t1, r);
|
||||
return secp256k1_fe_equal_var(&t1, a);
|
||||
}
|
||||
|
||||
static void secp256k1_fe_inv(secp256k1_fe_t *r, const secp256k1_fe_t *a) {
|
||||
secp256k1_fe_t x2, x3, x6, x9, x11, x22, x44, x88, x176, x220, x223, t1;
|
||||
int j;
|
||||
|
||||
/** The binary representation of (p - 2) has 5 blocks of 1s, with lengths in
|
||||
* { 1, 2, 22, 223 }. Use an addition chain to calculate 2^n - 1 for each block:
|
||||
* [1], [2], 3, 6, 9, 11, [22], 44, 88, 176, 220, [223]
|
||||
*/
|
||||
|
||||
secp256k1_fe_sqr(&x2, a);
|
||||
secp256k1_fe_mul(&x2, &x2, a);
|
||||
|
||||
secp256k1_fe_sqr(&x3, &x2);
|
||||
secp256k1_fe_mul(&x3, &x3, a);
|
||||
|
||||
x6 = x3;
|
||||
for (j=0; j<3; j++) {
|
||||
secp256k1_fe_sqr(&x6, &x6);
|
||||
}
|
||||
secp256k1_fe_mul(&x6, &x6, &x3);
|
||||
|
||||
x9 = x6;
|
||||
for (j=0; j<3; j++) {
|
||||
secp256k1_fe_sqr(&x9, &x9);
|
||||
}
|
||||
secp256k1_fe_mul(&x9, &x9, &x3);
|
||||
|
||||
x11 = x9;
|
||||
for (j=0; j<2; j++) {
|
||||
secp256k1_fe_sqr(&x11, &x11);
|
||||
}
|
||||
secp256k1_fe_mul(&x11, &x11, &x2);
|
||||
|
||||
x22 = x11;
|
||||
for (j=0; j<11; j++) {
|
||||
secp256k1_fe_sqr(&x22, &x22);
|
||||
}
|
||||
secp256k1_fe_mul(&x22, &x22, &x11);
|
||||
|
||||
x44 = x22;
|
||||
for (j=0; j<22; j++) {
|
||||
secp256k1_fe_sqr(&x44, &x44);
|
||||
}
|
||||
secp256k1_fe_mul(&x44, &x44, &x22);
|
||||
|
||||
x88 = x44;
|
||||
for (j=0; j<44; j++) {
|
||||
secp256k1_fe_sqr(&x88, &x88);
|
||||
}
|
||||
secp256k1_fe_mul(&x88, &x88, &x44);
|
||||
|
||||
x176 = x88;
|
||||
for (j=0; j<88; j++) {
|
||||
secp256k1_fe_sqr(&x176, &x176);
|
||||
}
|
||||
secp256k1_fe_mul(&x176, &x176, &x88);
|
||||
|
||||
x220 = x176;
|
||||
for (j=0; j<44; j++) {
|
||||
secp256k1_fe_sqr(&x220, &x220);
|
||||
}
|
||||
secp256k1_fe_mul(&x220, &x220, &x44);
|
||||
|
||||
x223 = x220;
|
||||
for (j=0; j<3; j++) {
|
||||
secp256k1_fe_sqr(&x223, &x223);
|
||||
}
|
||||
secp256k1_fe_mul(&x223, &x223, &x3);
|
||||
|
||||
/* The final result is then assembled using a sliding window over the blocks. */
|
||||
|
||||
t1 = x223;
|
||||
for (j=0; j<23; j++) {
|
||||
secp256k1_fe_sqr(&t1, &t1);
|
||||
}
|
||||
secp256k1_fe_mul(&t1, &t1, &x22);
|
||||
for (j=0; j<5; j++) {
|
||||
secp256k1_fe_sqr(&t1, &t1);
|
||||
}
|
||||
secp256k1_fe_mul(&t1, &t1, a);
|
||||
for (j=0; j<3; j++) {
|
||||
secp256k1_fe_sqr(&t1, &t1);
|
||||
}
|
||||
secp256k1_fe_mul(&t1, &t1, &x2);
|
||||
for (j=0; j<2; j++) {
|
||||
secp256k1_fe_sqr(&t1, &t1);
|
||||
}
|
||||
secp256k1_fe_mul(r, a, &t1);
|
||||
}
|
||||
|
||||
static void secp256k1_fe_inv_var(secp256k1_fe_t *r, const secp256k1_fe_t *a) {
|
||||
#if defined(USE_FIELD_INV_BUILTIN)
|
||||
secp256k1_fe_inv(r, a);
|
||||
#elif defined(USE_FIELD_INV_NUM)
|
||||
secp256k1_num_t n, m;
|
||||
/* secp256k1 field prime, value p defined in "Standards for Efficient Cryptography" (SEC2) 2.7.1. */
|
||||
static const unsigned char prime[32] = {
|
||||
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
|
||||
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
|
||||
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
|
||||
0xFF,0xFF,0xFF,0xFE,0xFF,0xFF,0xFC,0x2F
|
||||
};
|
||||
unsigned char b[32];
|
||||
secp256k1_fe_t c = *a;
|
||||
secp256k1_fe_normalize_var(&c);
|
||||
secp256k1_fe_get_b32(b, &c);
|
||||
secp256k1_num_set_bin(&n, b, 32);
|
||||
secp256k1_num_set_bin(&m, prime, 32);
|
||||
secp256k1_num_mod_inverse(&n, &n, &m);
|
||||
secp256k1_num_get_bin(b, 32, &n);
|
||||
VERIFY_CHECK(secp256k1_fe_set_b32(r, b));
|
||||
#else
|
||||
#error "Please select field inverse implementation"
|
||||
#endif
|
||||
}
|
||||
|
||||
static void secp256k1_fe_inv_all_var(size_t len, secp256k1_fe_t *r, const secp256k1_fe_t *a) {
|
||||
secp256k1_fe_t u;
|
||||
size_t i;
|
||||
if (len < 1) {
|
||||
return;
|
||||
}
|
||||
|
||||
VERIFY_CHECK((r + len <= a) || (a + len <= r));
|
||||
|
||||
r[0] = a[0];
|
||||
|
||||
i = 0;
|
||||
while (++i < len) {
|
||||
secp256k1_fe_mul(&r[i], &r[i - 1], &a[i]);
|
||||
}
|
||||
|
||||
secp256k1_fe_inv_var(&u, &r[--i]);
|
||||
|
||||
while (i > 0) {
|
||||
int j = i--;
|
||||
secp256k1_fe_mul(&r[j], &r[i], &u);
|
||||
secp256k1_fe_mul(&u, &u, &a[j]);
|
||||
}
|
||||
|
||||
r[0] = u;
|
||||
}
|
||||
|
||||
#endif
|
||||
|
|
@ -1,6 +1,8 @@
|
|||
// Copyright (c) 2013 Pieter Wuille
|
||||
// Distributed under the MIT/X11 software license, see the accompanying
|
||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||
/**********************************************************************
|
||||
* Copyright (c) 2013, 2014 Pieter Wuille *
|
||||
* Distributed under the MIT software license, see the accompanying *
|
||||
* file COPYING or http://www.opensource.org/licenses/mit-license.php.*
|
||||
**********************************************************************/
|
||||
|
||||
#ifndef _SECP256K1_GROUP_
|
||||
#define _SECP256K1_GROUP_
|
||||
|
|
@ -12,97 +14,105 @@
|
|||
typedef struct {
|
||||
secp256k1_fe_t x;
|
||||
secp256k1_fe_t y;
|
||||
int infinity; // whether this represents the point at infinity
|
||||
int infinity; /* whether this represents the point at infinity */
|
||||
} secp256k1_ge_t;
|
||||
|
||||
#define SECP256K1_GE_CONST(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) {SECP256K1_FE_CONST((a),(b),(c),(d),(e),(f),(g),(h)), SECP256K1_FE_CONST((i),(j),(k),(l),(m),(n),(o),(p)), 0}
|
||||
#define SECP256K1_GE_CONST_INFINITY {SECP256K1_FE_CONST(0, 0, 0, 0, 0, 0, 0, 0), SECP256K1_FE_CONST(0, 0, 0, 0, 0, 0, 0, 0), 1}
|
||||
|
||||
/** A group element of the secp256k1 curve, in jacobian coordinates. */
|
||||
typedef struct {
|
||||
secp256k1_fe_t x; // actual X: x/z^2
|
||||
secp256k1_fe_t y; // actual Y: y/z^3
|
||||
secp256k1_fe_t x; /* actual X: x/z^2 */
|
||||
secp256k1_fe_t y; /* actual Y: y/z^3 */
|
||||
secp256k1_fe_t z;
|
||||
int infinity; // whether this represents the point at infinity
|
||||
int infinity; /* whether this represents the point at infinity */
|
||||
} secp256k1_gej_t;
|
||||
|
||||
/** Global constants related to the group */
|
||||
#define SECP256K1_GEJ_CONST(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) {SECP256K1_FE_CONST((a),(b),(c),(d),(e),(f),(g),(h)), SECP256K1_FE_CONST((i),(j),(k),(l),(m),(n),(o),(p)), SECP256K1_FE_CONST(0, 0, 0, 0, 0, 0, 0, 1), 0}
|
||||
#define SECP256K1_GEJ_CONST_INFINITY {SECP256K1_FE_CONST(0, 0, 0, 0, 0, 0, 0, 0), SECP256K1_FE_CONST(0, 0, 0, 0, 0, 0, 0, 0), SECP256K1_FE_CONST(0, 0, 0, 0, 0, 0, 0, 0), 1}
|
||||
|
||||
typedef struct {
|
||||
secp256k1_num_t order; // the order of the curve (= order of its generator)
|
||||
secp256k1_num_t half_order; // half the order of the curve (= order of its generator)
|
||||
secp256k1_ge_t g; // the generator point
|
||||
secp256k1_fe_storage_t x;
|
||||
secp256k1_fe_storage_t y;
|
||||
} secp256k1_ge_storage_t;
|
||||
|
||||
// constants related to secp256k1's efficiently computable endomorphism
|
||||
secp256k1_fe_t beta;
|
||||
secp256k1_num_t lambda, a1b2, b1, a2;
|
||||
} secp256k1_ge_consts_t;
|
||||
|
||||
static const secp256k1_ge_consts_t *secp256k1_ge_consts = NULL;
|
||||
|
||||
/** Initialize the group module. */
|
||||
void static secp256k1_ge_start(void);
|
||||
|
||||
/** De-initialize the group module. */
|
||||
void static secp256k1_ge_stop(void);
|
||||
#define SECP256K1_GE_STORAGE_CONST(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) {SECP256K1_FE_STORAGE_CONST((a),(b),(c),(d),(e),(f),(g),(h)), SECP256K1_FE_STORAGE_CONST((i),(j),(k),(l),(m),(n),(o),(p))}
|
||||
|
||||
/** Set a group element equal to the point at infinity */
|
||||
void static secp256k1_ge_set_infinity(secp256k1_ge_t *r);
|
||||
static void secp256k1_ge_set_infinity(secp256k1_ge_t *r);
|
||||
|
||||
/** Set a group element equal to the point with given X and Y coordinates */
|
||||
void static secp256k1_ge_set_xy(secp256k1_ge_t *r, const secp256k1_fe_t *x, const secp256k1_fe_t *y);
|
||||
static void secp256k1_ge_set_xy(secp256k1_ge_t *r, const secp256k1_fe_t *x, const secp256k1_fe_t *y);
|
||||
|
||||
/** Set a group element (jacobian) equal to the point with given X coordinate, and given oddness for Y.
|
||||
The result is not guaranteed to be valid. */
|
||||
void static secp256k1_ge_set_xo(secp256k1_ge_t *r, const secp256k1_fe_t *x, int odd);
|
||||
/** Set a group element (affine) equal to the point with the given X coordinate, and given oddness
|
||||
* for Y. Return value indicates whether the result is valid. */
|
||||
static int secp256k1_ge_set_xo_var(secp256k1_ge_t *r, const secp256k1_fe_t *x, int odd);
|
||||
|
||||
/** Check whether a group element is the point at infinity. */
|
||||
int static secp256k1_ge_is_infinity(const secp256k1_ge_t *a);
|
||||
static int secp256k1_ge_is_infinity(const secp256k1_ge_t *a);
|
||||
|
||||
/** Check whether a group element is valid (i.e., on the curve). */
|
||||
int static secp256k1_ge_is_valid(const secp256k1_ge_t *a);
|
||||
static int secp256k1_ge_is_valid_var(const secp256k1_ge_t *a);
|
||||
|
||||
void static secp256k1_ge_neg(secp256k1_ge_t *r, const secp256k1_ge_t *a);
|
||||
|
||||
/** Get a hex representation of a point. *rlen will be overwritten with the real length. */
|
||||
void static secp256k1_ge_get_hex(char *r, int *rlen, const secp256k1_ge_t *a);
|
||||
static void secp256k1_ge_neg(secp256k1_ge_t *r, const secp256k1_ge_t *a);
|
||||
|
||||
/** Set a group element equal to another which is given in jacobian coordinates */
|
||||
void static secp256k1_ge_set_gej(secp256k1_ge_t *r, secp256k1_gej_t *a);
|
||||
static void secp256k1_ge_set_gej(secp256k1_ge_t *r, secp256k1_gej_t *a);
|
||||
|
||||
/** Set a batch of group elements equal to the inputs given in jacobian coordinates */
|
||||
static void secp256k1_ge_set_all_gej_var(size_t len, secp256k1_ge_t *r, const secp256k1_gej_t *a);
|
||||
|
||||
|
||||
/** Set a group element (jacobian) equal to the point at infinity. */
|
||||
void static secp256k1_gej_set_infinity(secp256k1_gej_t *r);
|
||||
static void secp256k1_gej_set_infinity(secp256k1_gej_t *r);
|
||||
|
||||
/** Set a group element (jacobian) equal to the point with given X and Y coordinates. */
|
||||
void static secp256k1_gej_set_xy(secp256k1_gej_t *r, const secp256k1_fe_t *x, const secp256k1_fe_t *y);
|
||||
static void secp256k1_gej_set_xy(secp256k1_gej_t *r, const secp256k1_fe_t *x, const secp256k1_fe_t *y);
|
||||
|
||||
/** Set a group element (jacobian) equal to another which is given in affine coordinates. */
|
||||
void static secp256k1_gej_set_ge(secp256k1_gej_t *r, const secp256k1_ge_t *a);
|
||||
static void secp256k1_gej_set_ge(secp256k1_gej_t *r, const secp256k1_ge_t *a);
|
||||
|
||||
/** Get the X coordinate of a group element (jacobian). */
|
||||
void static secp256k1_gej_get_x(secp256k1_fe_t *r, const secp256k1_gej_t *a);
|
||||
/** Compare the X coordinate of a group element (jacobian). */
|
||||
static int secp256k1_gej_eq_x_var(const secp256k1_fe_t *x, const secp256k1_gej_t *a);
|
||||
|
||||
/** Set r equal to the inverse of a (i.e., mirrored around the X axis) */
|
||||
void static secp256k1_gej_neg(secp256k1_gej_t *r, const secp256k1_gej_t *a);
|
||||
static void secp256k1_gej_neg(secp256k1_gej_t *r, const secp256k1_gej_t *a);
|
||||
|
||||
/** Check whether a group element is the point at infinity. */
|
||||
int static secp256k1_gej_is_infinity(const secp256k1_gej_t *a);
|
||||
static int secp256k1_gej_is_infinity(const secp256k1_gej_t *a);
|
||||
|
||||
/** Set r equal to the double of a. */
|
||||
void static secp256k1_gej_double(secp256k1_gej_t *r, const secp256k1_gej_t *a);
|
||||
static void secp256k1_gej_double_var(secp256k1_gej_t *r, const secp256k1_gej_t *a);
|
||||
|
||||
/** Set r equal to the sum of a and b. */
|
||||
void static secp256k1_gej_add(secp256k1_gej_t *r, const secp256k1_gej_t *a, const secp256k1_gej_t *b);
|
||||
static void secp256k1_gej_add_var(secp256k1_gej_t *r, const secp256k1_gej_t *a, const secp256k1_gej_t *b);
|
||||
|
||||
/** Set r equal to the sum of a and b (with b given in jacobian coordinates). This is more efficient
|
||||
than secp256k1_gej_add. */
|
||||
void static secp256k1_gej_add_ge(secp256k1_gej_t *r, const secp256k1_gej_t *a, const secp256k1_ge_t *b);
|
||||
/** Set r equal to the sum of a and b (with b given in affine coordinates, and not infinity). */
|
||||
static void secp256k1_gej_add_ge(secp256k1_gej_t *r, const secp256k1_gej_t *a, const secp256k1_ge_t *b);
|
||||
|
||||
/** Get a hex representation of a point. *rlen will be overwritten with the real length. */
|
||||
void static secp256k1_gej_get_hex(char *r, int *rlen, const secp256k1_gej_t *a);
|
||||
/** Set r equal to the sum of a and b (with b given in affine coordinates). This is more efficient
|
||||
than secp256k1_gej_add_var. It is identical to secp256k1_gej_add_ge but without constant-time
|
||||
guarantee, and b is allowed to be infinity. */
|
||||
static void secp256k1_gej_add_ge_var(secp256k1_gej_t *r, const secp256k1_gej_t *a, const secp256k1_ge_t *b);
|
||||
|
||||
#ifdef USE_ENDOMORPHISM
|
||||
/** Set r to be equal to lambda times a, where lambda is chosen in a way such that this is very fast. */
|
||||
void static secp256k1_gej_mul_lambda(secp256k1_gej_t *r, const secp256k1_gej_t *a);
|
||||
static void secp256k1_gej_mul_lambda(secp256k1_gej_t *r, const secp256k1_gej_t *a);
|
||||
#endif
|
||||
|
||||
/** Find r1 and r2 such that r1+r2*lambda = a, and r1 and r2 are maximum 128 bits long (given that a is
|
||||
not more than 256 bits). */
|
||||
void static secp256k1_gej_split_exp(secp256k1_num_t *r1, secp256k1_num_t *r2, const secp256k1_num_t *a);
|
||||
/** Clear a secp256k1_gej_t to prevent leaking sensitive information. */
|
||||
static void secp256k1_gej_clear(secp256k1_gej_t *r);
|
||||
|
||||
/** Clear a secp256k1_ge_t to prevent leaking sensitive information. */
|
||||
static void secp256k1_ge_clear(secp256k1_ge_t *r);
|
||||
|
||||
/** Convert a group element to the storage type. */
|
||||
static void secp256k1_ge_to_storage(secp256k1_ge_storage_t *r, const secp256k1_ge_t*);
|
||||
|
||||
/** Convert a group element back from the storage type. */
|
||||
static void secp256k1_ge_from_storage(secp256k1_ge_t *r, const secp256k1_ge_storage_t*);
|
||||
|
||||
/** If flag is true, set *r equal to *a; otherwise leave it. Constant-time. */
|
||||
static void secp256k1_ge_storage_cmov(secp256k1_ge_storage_t *r, const secp256k1_ge_storage_t *a, int flag);
|
||||
|
||||
#endif
|
||||
|
|
|
|||
434
crypto/secp256k1/secp256k1/src/group_impl.h
Normal file
434
crypto/secp256k1/secp256k1/src/group_impl.h
Normal file
|
|
@ -0,0 +1,434 @@
|
|||
/**********************************************************************
|
||||
* Copyright (c) 2013, 2014 Pieter Wuille *
|
||||
* Distributed under the MIT software license, see the accompanying *
|
||||
* file COPYING or http://www.opensource.org/licenses/mit-license.php.*
|
||||
**********************************************************************/
|
||||
|
||||
#ifndef _SECP256K1_GROUP_IMPL_H_
|
||||
#define _SECP256K1_GROUP_IMPL_H_
|
||||
|
||||
#include <string.h>
|
||||
|
||||
#include "num.h"
|
||||
#include "field.h"
|
||||
#include "group.h"
|
||||
|
||||
/** Generator for secp256k1, value 'g' defined in
|
||||
* "Standards for Efficient Cryptography" (SEC2) 2.7.1.
|
||||
*/
|
||||
static const secp256k1_ge_t secp256k1_ge_const_g = SECP256K1_GE_CONST(
|
||||
0x79BE667EUL, 0xF9DCBBACUL, 0x55A06295UL, 0xCE870B07UL,
|
||||
0x029BFCDBUL, 0x2DCE28D9UL, 0x59F2815BUL, 0x16F81798UL,
|
||||
0x483ADA77UL, 0x26A3C465UL, 0x5DA4FBFCUL, 0x0E1108A8UL,
|
||||
0xFD17B448UL, 0xA6855419UL, 0x9C47D08FUL, 0xFB10D4B8UL
|
||||
);
|
||||
|
||||
static void secp256k1_ge_set_infinity(secp256k1_ge_t *r) {
|
||||
r->infinity = 1;
|
||||
}
|
||||
|
||||
static void secp256k1_ge_set_xy(secp256k1_ge_t *r, const secp256k1_fe_t *x, const secp256k1_fe_t *y) {
|
||||
r->infinity = 0;
|
||||
r->x = *x;
|
||||
r->y = *y;
|
||||
}
|
||||
|
||||
static int secp256k1_ge_is_infinity(const secp256k1_ge_t *a) {
|
||||
return a->infinity;
|
||||
}
|
||||
|
||||
static void secp256k1_ge_neg(secp256k1_ge_t *r, const secp256k1_ge_t *a) {
|
||||
*r = *a;
|
||||
secp256k1_fe_normalize_weak(&r->y);
|
||||
secp256k1_fe_negate(&r->y, &r->y, 1);
|
||||
}
|
||||
|
||||
static void secp256k1_ge_set_gej(secp256k1_ge_t *r, secp256k1_gej_t *a) {
|
||||
secp256k1_fe_t z2, z3;
|
||||
r->infinity = a->infinity;
|
||||
secp256k1_fe_inv(&a->z, &a->z);
|
||||
secp256k1_fe_sqr(&z2, &a->z);
|
||||
secp256k1_fe_mul(&z3, &a->z, &z2);
|
||||
secp256k1_fe_mul(&a->x, &a->x, &z2);
|
||||
secp256k1_fe_mul(&a->y, &a->y, &z3);
|
||||
secp256k1_fe_set_int(&a->z, 1);
|
||||
r->x = a->x;
|
||||
r->y = a->y;
|
||||
}
|
||||
|
||||
static void secp256k1_ge_set_gej_var(secp256k1_ge_t *r, secp256k1_gej_t *a) {
|
||||
secp256k1_fe_t z2, z3;
|
||||
r->infinity = a->infinity;
|
||||
if (a->infinity) {
|
||||
return;
|
||||
}
|
||||
secp256k1_fe_inv_var(&a->z, &a->z);
|
||||
secp256k1_fe_sqr(&z2, &a->z);
|
||||
secp256k1_fe_mul(&z3, &a->z, &z2);
|
||||
secp256k1_fe_mul(&a->x, &a->x, &z2);
|
||||
secp256k1_fe_mul(&a->y, &a->y, &z3);
|
||||
secp256k1_fe_set_int(&a->z, 1);
|
||||
r->x = a->x;
|
||||
r->y = a->y;
|
||||
}
|
||||
|
||||
static void secp256k1_ge_set_all_gej_var(size_t len, secp256k1_ge_t *r, const secp256k1_gej_t *a) {
|
||||
secp256k1_fe_t *az;
|
||||
secp256k1_fe_t *azi;
|
||||
size_t i;
|
||||
size_t count = 0;
|
||||
az = (secp256k1_fe_t *)checked_malloc(sizeof(secp256k1_fe_t) * len);
|
||||
for (i = 0; i < len; i++) {
|
||||
if (!a[i].infinity) {
|
||||
az[count++] = a[i].z;
|
||||
}
|
||||
}
|
||||
|
||||
azi = (secp256k1_fe_t *)checked_malloc(sizeof(secp256k1_fe_t) * count);
|
||||
secp256k1_fe_inv_all_var(count, azi, az);
|
||||
free(az);
|
||||
|
||||
count = 0;
|
||||
for (i = 0; i < len; i++) {
|
||||
r[i].infinity = a[i].infinity;
|
||||
if (!a[i].infinity) {
|
||||
secp256k1_fe_t zi2, zi3;
|
||||
secp256k1_fe_t *zi = &azi[count++];
|
||||
secp256k1_fe_sqr(&zi2, zi);
|
||||
secp256k1_fe_mul(&zi3, &zi2, zi);
|
||||
secp256k1_fe_mul(&r[i].x, &a[i].x, &zi2);
|
||||
secp256k1_fe_mul(&r[i].y, &a[i].y, &zi3);
|
||||
}
|
||||
}
|
||||
free(azi);
|
||||
}
|
||||
|
||||
static void secp256k1_gej_set_infinity(secp256k1_gej_t *r) {
|
||||
r->infinity = 1;
|
||||
secp256k1_fe_set_int(&r->x, 0);
|
||||
secp256k1_fe_set_int(&r->y, 0);
|
||||
secp256k1_fe_set_int(&r->z, 0);
|
||||
}
|
||||
|
||||
static void secp256k1_gej_set_xy(secp256k1_gej_t *r, const secp256k1_fe_t *x, const secp256k1_fe_t *y) {
|
||||
r->infinity = 0;
|
||||
r->x = *x;
|
||||
r->y = *y;
|
||||
secp256k1_fe_set_int(&r->z, 1);
|
||||
}
|
||||
|
||||
static void secp256k1_gej_clear(secp256k1_gej_t *r) {
|
||||
r->infinity = 0;
|
||||
secp256k1_fe_clear(&r->x);
|
||||
secp256k1_fe_clear(&r->y);
|
||||
secp256k1_fe_clear(&r->z);
|
||||
}
|
||||
|
||||
static void secp256k1_ge_clear(secp256k1_ge_t *r) {
|
||||
r->infinity = 0;
|
||||
secp256k1_fe_clear(&r->x);
|
||||
secp256k1_fe_clear(&r->y);
|
||||
}
|
||||
|
||||
static int secp256k1_ge_set_xo_var(secp256k1_ge_t *r, const secp256k1_fe_t *x, int odd) {
|
||||
secp256k1_fe_t x2, x3, c;
|
||||
r->x = *x;
|
||||
secp256k1_fe_sqr(&x2, x);
|
||||
secp256k1_fe_mul(&x3, x, &x2);
|
||||
r->infinity = 0;
|
||||
secp256k1_fe_set_int(&c, 7);
|
||||
secp256k1_fe_add(&c, &x3);
|
||||
if (!secp256k1_fe_sqrt_var(&r->y, &c)) {
|
||||
return 0;
|
||||
}
|
||||
secp256k1_fe_normalize_var(&r->y);
|
||||
if (secp256k1_fe_is_odd(&r->y) != odd) {
|
||||
secp256k1_fe_negate(&r->y, &r->y, 1);
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
static void secp256k1_gej_set_ge(secp256k1_gej_t *r, const secp256k1_ge_t *a) {
|
||||
r->infinity = a->infinity;
|
||||
r->x = a->x;
|
||||
r->y = a->y;
|
||||
secp256k1_fe_set_int(&r->z, 1);
|
||||
}
|
||||
|
||||
static int secp256k1_gej_eq_x_var(const secp256k1_fe_t *x, const secp256k1_gej_t *a) {
|
||||
secp256k1_fe_t r, r2;
|
||||
VERIFY_CHECK(!a->infinity);
|
||||
secp256k1_fe_sqr(&r, &a->z); secp256k1_fe_mul(&r, &r, x);
|
||||
r2 = a->x; secp256k1_fe_normalize_weak(&r2);
|
||||
return secp256k1_fe_equal_var(&r, &r2);
|
||||
}
|
||||
|
||||
static void secp256k1_gej_neg(secp256k1_gej_t *r, const secp256k1_gej_t *a) {
|
||||
r->infinity = a->infinity;
|
||||
r->x = a->x;
|
||||
r->y = a->y;
|
||||
r->z = a->z;
|
||||
secp256k1_fe_normalize_weak(&r->y);
|
||||
secp256k1_fe_negate(&r->y, &r->y, 1);
|
||||
}
|
||||
|
||||
static int secp256k1_gej_is_infinity(const secp256k1_gej_t *a) {
|
||||
return a->infinity;
|
||||
}
|
||||
|
||||
static int secp256k1_gej_is_valid_var(const secp256k1_gej_t *a) {
|
||||
secp256k1_fe_t y2, x3, z2, z6;
|
||||
if (a->infinity) {
|
||||
return 0;
|
||||
}
|
||||
/** y^2 = x^3 + 7
|
||||
* (Y/Z^3)^2 = (X/Z^2)^3 + 7
|
||||
* Y^2 / Z^6 = X^3 / Z^6 + 7
|
||||
* Y^2 = X^3 + 7*Z^6
|
||||
*/
|
||||
secp256k1_fe_sqr(&y2, &a->y);
|
||||
secp256k1_fe_sqr(&x3, &a->x); secp256k1_fe_mul(&x3, &x3, &a->x);
|
||||
secp256k1_fe_sqr(&z2, &a->z);
|
||||
secp256k1_fe_sqr(&z6, &z2); secp256k1_fe_mul(&z6, &z6, &z2);
|
||||
secp256k1_fe_mul_int(&z6, 7);
|
||||
secp256k1_fe_add(&x3, &z6);
|
||||
secp256k1_fe_normalize_weak(&x3);
|
||||
return secp256k1_fe_equal_var(&y2, &x3);
|
||||
}
|
||||
|
||||
static int secp256k1_ge_is_valid_var(const secp256k1_ge_t *a) {
|
||||
secp256k1_fe_t y2, x3, c;
|
||||
if (a->infinity) {
|
||||
return 0;
|
||||
}
|
||||
/* y^2 = x^3 + 7 */
|
||||
secp256k1_fe_sqr(&y2, &a->y);
|
||||
secp256k1_fe_sqr(&x3, &a->x); secp256k1_fe_mul(&x3, &x3, &a->x);
|
||||
secp256k1_fe_set_int(&c, 7);
|
||||
secp256k1_fe_add(&x3, &c);
|
||||
secp256k1_fe_normalize_weak(&x3);
|
||||
return secp256k1_fe_equal_var(&y2, &x3);
|
||||
}
|
||||
|
||||
static void secp256k1_gej_double_var(secp256k1_gej_t *r, const secp256k1_gej_t *a) {
|
||||
/* Operations: 3 mul, 4 sqr, 0 normalize, 12 mul_int/add/negate */
|
||||
secp256k1_fe_t t1,t2,t3,t4;
|
||||
/** For secp256k1, 2Q is infinity if and only if Q is infinity. This is because if 2Q = infinity,
|
||||
* Q must equal -Q, or that Q.y == -(Q.y), or Q.y is 0. For a point on y^2 = x^3 + 7 to have
|
||||
* y=0, x^3 must be -7 mod p. However, -7 has no cube root mod p.
|
||||
*/
|
||||
r->infinity = a->infinity;
|
||||
if (r->infinity) {
|
||||
return;
|
||||
}
|
||||
|
||||
secp256k1_fe_mul(&r->z, &a->z, &a->y);
|
||||
secp256k1_fe_mul_int(&r->z, 2); /* Z' = 2*Y*Z (2) */
|
||||
secp256k1_fe_sqr(&t1, &a->x);
|
||||
secp256k1_fe_mul_int(&t1, 3); /* T1 = 3*X^2 (3) */
|
||||
secp256k1_fe_sqr(&t2, &t1); /* T2 = 9*X^4 (1) */
|
||||
secp256k1_fe_sqr(&t3, &a->y);
|
||||
secp256k1_fe_mul_int(&t3, 2); /* T3 = 2*Y^2 (2) */
|
||||
secp256k1_fe_sqr(&t4, &t3);
|
||||
secp256k1_fe_mul_int(&t4, 2); /* T4 = 8*Y^4 (2) */
|
||||
secp256k1_fe_mul(&t3, &t3, &a->x); /* T3 = 2*X*Y^2 (1) */
|
||||
r->x = t3;
|
||||
secp256k1_fe_mul_int(&r->x, 4); /* X' = 8*X*Y^2 (4) */
|
||||
secp256k1_fe_negate(&r->x, &r->x, 4); /* X' = -8*X*Y^2 (5) */
|
||||
secp256k1_fe_add(&r->x, &t2); /* X' = 9*X^4 - 8*X*Y^2 (6) */
|
||||
secp256k1_fe_negate(&t2, &t2, 1); /* T2 = -9*X^4 (2) */
|
||||
secp256k1_fe_mul_int(&t3, 6); /* T3 = 12*X*Y^2 (6) */
|
||||
secp256k1_fe_add(&t3, &t2); /* T3 = 12*X*Y^2 - 9*X^4 (8) */
|
||||
secp256k1_fe_mul(&r->y, &t1, &t3); /* Y' = 36*X^3*Y^2 - 27*X^6 (1) */
|
||||
secp256k1_fe_negate(&t2, &t4, 2); /* T2 = -8*Y^4 (3) */
|
||||
secp256k1_fe_add(&r->y, &t2); /* Y' = 36*X^3*Y^2 - 27*X^6 - 8*Y^4 (4) */
|
||||
}
|
||||
|
||||
static void secp256k1_gej_add_var(secp256k1_gej_t *r, const secp256k1_gej_t *a, const secp256k1_gej_t *b) {
|
||||
/* Operations: 12 mul, 4 sqr, 2 normalize, 12 mul_int/add/negate */
|
||||
secp256k1_fe_t z22, z12, u1, u2, s1, s2, h, i, i2, h2, h3, t;
|
||||
if (a->infinity) {
|
||||
*r = *b;
|
||||
return;
|
||||
}
|
||||
if (b->infinity) {
|
||||
*r = *a;
|
||||
return;
|
||||
}
|
||||
r->infinity = 0;
|
||||
secp256k1_fe_sqr(&z22, &b->z);
|
||||
secp256k1_fe_sqr(&z12, &a->z);
|
||||
secp256k1_fe_mul(&u1, &a->x, &z22);
|
||||
secp256k1_fe_mul(&u2, &b->x, &z12);
|
||||
secp256k1_fe_mul(&s1, &a->y, &z22); secp256k1_fe_mul(&s1, &s1, &b->z);
|
||||
secp256k1_fe_mul(&s2, &b->y, &z12); secp256k1_fe_mul(&s2, &s2, &a->z);
|
||||
secp256k1_fe_negate(&h, &u1, 1); secp256k1_fe_add(&h, &u2);
|
||||
secp256k1_fe_negate(&i, &s1, 1); secp256k1_fe_add(&i, &s2);
|
||||
if (secp256k1_fe_normalizes_to_zero_var(&h)) {
|
||||
if (secp256k1_fe_normalizes_to_zero_var(&i)) {
|
||||
secp256k1_gej_double_var(r, a);
|
||||
} else {
|
||||
r->infinity = 1;
|
||||
}
|
||||
return;
|
||||
}
|
||||
secp256k1_fe_sqr(&i2, &i);
|
||||
secp256k1_fe_sqr(&h2, &h);
|
||||
secp256k1_fe_mul(&h3, &h, &h2);
|
||||
secp256k1_fe_mul(&r->z, &a->z, &b->z); secp256k1_fe_mul(&r->z, &r->z, &h);
|
||||
secp256k1_fe_mul(&t, &u1, &h2);
|
||||
r->x = t; secp256k1_fe_mul_int(&r->x, 2); secp256k1_fe_add(&r->x, &h3); secp256k1_fe_negate(&r->x, &r->x, 3); secp256k1_fe_add(&r->x, &i2);
|
||||
secp256k1_fe_negate(&r->y, &r->x, 5); secp256k1_fe_add(&r->y, &t); secp256k1_fe_mul(&r->y, &r->y, &i);
|
||||
secp256k1_fe_mul(&h3, &h3, &s1); secp256k1_fe_negate(&h3, &h3, 1);
|
||||
secp256k1_fe_add(&r->y, &h3);
|
||||
}
|
||||
|
||||
static void secp256k1_gej_add_ge_var(secp256k1_gej_t *r, const secp256k1_gej_t *a, const secp256k1_ge_t *b) {
|
||||
/* 8 mul, 3 sqr, 4 normalize, 12 mul_int/add/negate */
|
||||
secp256k1_fe_t z12, u1, u2, s1, s2, h, i, i2, h2, h3, t;
|
||||
if (a->infinity) {
|
||||
r->infinity = b->infinity;
|
||||
r->x = b->x;
|
||||
r->y = b->y;
|
||||
secp256k1_fe_set_int(&r->z, 1);
|
||||
return;
|
||||
}
|
||||
if (b->infinity) {
|
||||
*r = *a;
|
||||
return;
|
||||
}
|
||||
r->infinity = 0;
|
||||
secp256k1_fe_sqr(&z12, &a->z);
|
||||
u1 = a->x; secp256k1_fe_normalize_weak(&u1);
|
||||
secp256k1_fe_mul(&u2, &b->x, &z12);
|
||||
s1 = a->y; secp256k1_fe_normalize_weak(&s1);
|
||||
secp256k1_fe_mul(&s2, &b->y, &z12); secp256k1_fe_mul(&s2, &s2, &a->z);
|
||||
secp256k1_fe_negate(&h, &u1, 1); secp256k1_fe_add(&h, &u2);
|
||||
secp256k1_fe_negate(&i, &s1, 1); secp256k1_fe_add(&i, &s2);
|
||||
if (secp256k1_fe_normalizes_to_zero_var(&h)) {
|
||||
if (secp256k1_fe_normalizes_to_zero_var(&i)) {
|
||||
secp256k1_gej_double_var(r, a);
|
||||
} else {
|
||||
r->infinity = 1;
|
||||
}
|
||||
return;
|
||||
}
|
||||
secp256k1_fe_sqr(&i2, &i);
|
||||
secp256k1_fe_sqr(&h2, &h);
|
||||
secp256k1_fe_mul(&h3, &h, &h2);
|
||||
r->z = a->z; secp256k1_fe_mul(&r->z, &r->z, &h);
|
||||
secp256k1_fe_mul(&t, &u1, &h2);
|
||||
r->x = t; secp256k1_fe_mul_int(&r->x, 2); secp256k1_fe_add(&r->x, &h3); secp256k1_fe_negate(&r->x, &r->x, 3); secp256k1_fe_add(&r->x, &i2);
|
||||
secp256k1_fe_negate(&r->y, &r->x, 5); secp256k1_fe_add(&r->y, &t); secp256k1_fe_mul(&r->y, &r->y, &i);
|
||||
secp256k1_fe_mul(&h3, &h3, &s1); secp256k1_fe_negate(&h3, &h3, 1);
|
||||
secp256k1_fe_add(&r->y, &h3);
|
||||
}
|
||||
|
||||
static void secp256k1_gej_add_ge(secp256k1_gej_t *r, const secp256k1_gej_t *a, const secp256k1_ge_t *b) {
|
||||
/* Operations: 7 mul, 5 sqr, 5 normalize, 19 mul_int/add/negate */
|
||||
secp256k1_fe_t zz, u1, u2, s1, s2, z, t, m, n, q, rr;
|
||||
int infinity;
|
||||
VERIFY_CHECK(!b->infinity);
|
||||
VERIFY_CHECK(a->infinity == 0 || a->infinity == 1);
|
||||
|
||||
/** In:
|
||||
* Eric Brier and Marc Joye, Weierstrass Elliptic Curves and Side-Channel Attacks.
|
||||
* In D. Naccache and P. Paillier, Eds., Public Key Cryptography, vol. 2274 of Lecture Notes in Computer Science, pages 335-345. Springer-Verlag, 2002.
|
||||
* we find as solution for a unified addition/doubling formula:
|
||||
* lambda = ((x1 + x2)^2 - x1 * x2 + a) / (y1 + y2), with a = 0 for secp256k1's curve equation.
|
||||
* x3 = lambda^2 - (x1 + x2)
|
||||
* 2*y3 = lambda * (x1 + x2 - 2 * x3) - (y1 + y2).
|
||||
*
|
||||
* Substituting x_i = Xi / Zi^2 and yi = Yi / Zi^3, for i=1,2,3, gives:
|
||||
* U1 = X1*Z2^2, U2 = X2*Z1^2
|
||||
* S1 = Y1*Z2^3, S2 = Y2*Z1^3
|
||||
* Z = Z1*Z2
|
||||
* T = U1+U2
|
||||
* M = S1+S2
|
||||
* Q = T*M^2
|
||||
* R = T^2-U1*U2
|
||||
* X3 = 4*(R^2-Q)
|
||||
* Y3 = 4*(R*(3*Q-2*R^2)-M^4)
|
||||
* Z3 = 2*M*Z
|
||||
* (Note that the paper uses xi = Xi / Zi and yi = Yi / Zi instead.)
|
||||
*/
|
||||
|
||||
secp256k1_fe_sqr(&zz, &a->z); /* z = Z1^2 */
|
||||
u1 = a->x; secp256k1_fe_normalize_weak(&u1); /* u1 = U1 = X1*Z2^2 (1) */
|
||||
secp256k1_fe_mul(&u2, &b->x, &zz); /* u2 = U2 = X2*Z1^2 (1) */
|
||||
s1 = a->y; secp256k1_fe_normalize_weak(&s1); /* s1 = S1 = Y1*Z2^3 (1) */
|
||||
secp256k1_fe_mul(&s2, &b->y, &zz); /* s2 = Y2*Z2^2 (1) */
|
||||
secp256k1_fe_mul(&s2, &s2, &a->z); /* s2 = S2 = Y2*Z1^3 (1) */
|
||||
z = a->z; /* z = Z = Z1*Z2 (8) */
|
||||
t = u1; secp256k1_fe_add(&t, &u2); /* t = T = U1+U2 (2) */
|
||||
m = s1; secp256k1_fe_add(&m, &s2); /* m = M = S1+S2 (2) */
|
||||
secp256k1_fe_sqr(&n, &m); /* n = M^2 (1) */
|
||||
secp256k1_fe_mul(&q, &n, &t); /* q = Q = T*M^2 (1) */
|
||||
secp256k1_fe_sqr(&n, &n); /* n = M^4 (1) */
|
||||
secp256k1_fe_sqr(&rr, &t); /* rr = T^2 (1) */
|
||||
secp256k1_fe_mul(&t, &u1, &u2); secp256k1_fe_negate(&t, &t, 1); /* t = -U1*U2 (2) */
|
||||
secp256k1_fe_add(&rr, &t); /* rr = R = T^2-U1*U2 (3) */
|
||||
secp256k1_fe_sqr(&t, &rr); /* t = R^2 (1) */
|
||||
secp256k1_fe_mul(&r->z, &m, &z); /* r->z = M*Z (1) */
|
||||
infinity = secp256k1_fe_normalizes_to_zero(&r->z) * (1 - a->infinity);
|
||||
secp256k1_fe_mul_int(&r->z, 2 * (1 - a->infinity)); /* r->z = Z3 = 2*M*Z (2) */
|
||||
r->x = t; /* r->x = R^2 (1) */
|
||||
secp256k1_fe_negate(&q, &q, 1); /* q = -Q (2) */
|
||||
secp256k1_fe_add(&r->x, &q); /* r->x = R^2-Q (3) */
|
||||
secp256k1_fe_normalize(&r->x);
|
||||
secp256k1_fe_mul_int(&q, 3); /* q = -3*Q (6) */
|
||||
secp256k1_fe_mul_int(&t, 2); /* t = 2*R^2 (2) */
|
||||
secp256k1_fe_add(&t, &q); /* t = 2*R^2-3*Q (8) */
|
||||
secp256k1_fe_mul(&t, &t, &rr); /* t = R*(2*R^2-3*Q) (1) */
|
||||
secp256k1_fe_add(&t, &n); /* t = R*(2*R^2-3*Q)+M^4 (2) */
|
||||
secp256k1_fe_negate(&r->y, &t, 2); /* r->y = R*(3*Q-2*R^2)-M^4 (3) */
|
||||
secp256k1_fe_normalize_weak(&r->y);
|
||||
secp256k1_fe_mul_int(&r->x, 4 * (1 - a->infinity)); /* r->x = X3 = 4*(R^2-Q) */
|
||||
secp256k1_fe_mul_int(&r->y, 4 * (1 - a->infinity)); /* r->y = Y3 = 4*R*(3*Q-2*R^2)-4*M^4 (4) */
|
||||
|
||||
/** In case a->infinity == 1, the above code results in r->x, r->y, and r->z all equal to 0.
|
||||
* Add b->x to x, b->y to y, and 1 to z in that case.
|
||||
*/
|
||||
t = b->x; secp256k1_fe_mul_int(&t, a->infinity);
|
||||
secp256k1_fe_add(&r->x, &t);
|
||||
t = b->y; secp256k1_fe_mul_int(&t, a->infinity);
|
||||
secp256k1_fe_add(&r->y, &t);
|
||||
secp256k1_fe_set_int(&t, a->infinity);
|
||||
secp256k1_fe_add(&r->z, &t);
|
||||
r->infinity = infinity;
|
||||
}
|
||||
|
||||
static void secp256k1_ge_to_storage(secp256k1_ge_storage_t *r, const secp256k1_ge_t *a) {
|
||||
secp256k1_fe_t x, y;
|
||||
VERIFY_CHECK(!a->infinity);
|
||||
x = a->x;
|
||||
secp256k1_fe_normalize(&x);
|
||||
y = a->y;
|
||||
secp256k1_fe_normalize(&y);
|
||||
secp256k1_fe_to_storage(&r->x, &x);
|
||||
secp256k1_fe_to_storage(&r->y, &y);
|
||||
}
|
||||
|
||||
static void secp256k1_ge_from_storage(secp256k1_ge_t *r, const secp256k1_ge_storage_t *a) {
|
||||
secp256k1_fe_from_storage(&r->x, &a->x);
|
||||
secp256k1_fe_from_storage(&r->y, &a->y);
|
||||
r->infinity = 0;
|
||||
}
|
||||
|
||||
static SECP256K1_INLINE void secp256k1_ge_storage_cmov(secp256k1_ge_storage_t *r, const secp256k1_ge_storage_t *a, int flag) {
|
||||
secp256k1_fe_storage_cmov(&r->x, &a->x, flag);
|
||||
secp256k1_fe_storage_cmov(&r->y, &a->y, flag);
|
||||
}
|
||||
|
||||
#ifdef USE_ENDOMORPHISM
|
||||
static void secp256k1_gej_mul_lambda(secp256k1_gej_t *r, const secp256k1_gej_t *a) {
|
||||
static const secp256k1_fe_t beta = SECP256K1_FE_CONST(
|
||||
0x7ae96a2bul, 0x657c0710ul, 0x6e64479eul, 0xac3434e9ul,
|
||||
0x9cf04975ul, 0x12f58995ul, 0xc1396c28ul, 0x719501eeul
|
||||
);
|
||||
*r = *a;
|
||||
secp256k1_fe_mul(&r->x, &r->x, &beta);
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
41
crypto/secp256k1/secp256k1/src/hash.h
Normal file
41
crypto/secp256k1/secp256k1/src/hash.h
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
/**********************************************************************
|
||||
* Copyright (c) 2014 Pieter Wuille *
|
||||
* Distributed under the MIT software license, see the accompanying *
|
||||
* file COPYING or http://www.opensource.org/licenses/mit-license.php.*
|
||||
**********************************************************************/
|
||||
|
||||
#ifndef _SECP256K1_HASH_
|
||||
#define _SECP256K1_HASH_
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <stdint.h>
|
||||
|
||||
typedef struct {
|
||||
uint32_t s[32];
|
||||
uint32_t buf[16]; /* In big endian */
|
||||
size_t bytes;
|
||||
} secp256k1_sha256_t;
|
||||
|
||||
static void secp256k1_sha256_initialize(secp256k1_sha256_t *hash);
|
||||
static void secp256k1_sha256_write(secp256k1_sha256_t *hash, const unsigned char *data, size_t size);
|
||||
static void secp256k1_sha256_finalize(secp256k1_sha256_t *hash, unsigned char *out32);
|
||||
|
||||
typedef struct {
|
||||
secp256k1_sha256_t inner, outer;
|
||||
} secp256k1_hmac_sha256_t;
|
||||
|
||||
static void secp256k1_hmac_sha256_initialize(secp256k1_hmac_sha256_t *hash, const unsigned char *key, size_t size);
|
||||
static void secp256k1_hmac_sha256_write(secp256k1_hmac_sha256_t *hash, const unsigned char *data, size_t size);
|
||||
static void secp256k1_hmac_sha256_finalize(secp256k1_hmac_sha256_t *hash, unsigned char *out32);
|
||||
|
||||
typedef struct {
|
||||
unsigned char v[32];
|
||||
unsigned char k[32];
|
||||
int retry;
|
||||
} secp256k1_rfc6979_hmac_sha256_t;
|
||||
|
||||
static void secp256k1_rfc6979_hmac_sha256_initialize(secp256k1_rfc6979_hmac_sha256_t *rng, const unsigned char *key, size_t keylen, const unsigned char *msg, size_t msglen, const unsigned char *rnd, size_t rndlen);
|
||||
static void secp256k1_rfc6979_hmac_sha256_generate(secp256k1_rfc6979_hmac_sha256_t *rng, unsigned char *out, size_t outlen);
|
||||
static void secp256k1_rfc6979_hmac_sha256_finalize(secp256k1_rfc6979_hmac_sha256_t *rng);
|
||||
|
||||
#endif
|
||||
293
crypto/secp256k1/secp256k1/src/hash_impl.h
Normal file
293
crypto/secp256k1/secp256k1/src/hash_impl.h
Normal file
|
|
@ -0,0 +1,293 @@
|
|||
/**********************************************************************
|
||||
* Copyright (c) 2014 Pieter Wuille *
|
||||
* Distributed under the MIT software license, see the accompanying *
|
||||
* file COPYING or http://www.opensource.org/licenses/mit-license.php.*
|
||||
**********************************************************************/
|
||||
|
||||
#ifndef _SECP256K1_HASH_IMPL_H_
|
||||
#define _SECP256K1_HASH_IMPL_H_
|
||||
|
||||
#include "hash.h"
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
|
||||
#define Ch(x,y,z) ((z) ^ ((x) & ((y) ^ (z))))
|
||||
#define Maj(x,y,z) (((x) & (y)) | ((z) & ((x) | (y))))
|
||||
#define Sigma0(x) (((x) >> 2 | (x) << 30) ^ ((x) >> 13 | (x) << 19) ^ ((x) >> 22 | (x) << 10))
|
||||
#define Sigma1(x) (((x) >> 6 | (x) << 26) ^ ((x) >> 11 | (x) << 21) ^ ((x) >> 25 | (x) << 7))
|
||||
#define sigma0(x) (((x) >> 7 | (x) << 25) ^ ((x) >> 18 | (x) << 14) ^ ((x) >> 3))
|
||||
#define sigma1(x) (((x) >> 17 | (x) << 15) ^ ((x) >> 19 | (x) << 13) ^ ((x) >> 10))
|
||||
|
||||
#define Round(a,b,c,d,e,f,g,h,k,w) do { \
|
||||
uint32_t t1 = (h) + Sigma1(e) + Ch((e), (f), (g)) + (k) + (w); \
|
||||
uint32_t t2 = Sigma0(a) + Maj((a), (b), (c)); \
|
||||
(d) += t1; \
|
||||
(h) = t1 + t2; \
|
||||
} while(0)
|
||||
|
||||
#ifdef WORDS_BIGENDIAN
|
||||
#define BE32(x) (x)
|
||||
#else
|
||||
#define BE32(p) ((((p) & 0xFF) << 24) | (((p) & 0xFF00) << 8) | (((p) & 0xFF0000) >> 8) | (((p) & 0xFF000000) >> 24))
|
||||
#endif
|
||||
|
||||
static void secp256k1_sha256_initialize(secp256k1_sha256_t *hash) {
|
||||
hash->s[0] = 0x6a09e667ul;
|
||||
hash->s[1] = 0xbb67ae85ul;
|
||||
hash->s[2] = 0x3c6ef372ul;
|
||||
hash->s[3] = 0xa54ff53aul;
|
||||
hash->s[4] = 0x510e527ful;
|
||||
hash->s[5] = 0x9b05688cul;
|
||||
hash->s[6] = 0x1f83d9abul;
|
||||
hash->s[7] = 0x5be0cd19ul;
|
||||
hash->bytes = 0;
|
||||
}
|
||||
|
||||
/** Perform one SHA-256 transformation, processing 16 big endian 32-bit words. */
|
||||
static void secp256k1_sha256_transform(uint32_t* s, const uint32_t* chunk) {
|
||||
uint32_t a = s[0], b = s[1], c = s[2], d = s[3], e = s[4], f = s[5], g = s[6], h = s[7];
|
||||
uint32_t w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15;
|
||||
|
||||
Round(a, b, c, d, e, f, g, h, 0x428a2f98, w0 = BE32(chunk[0]));
|
||||
Round(h, a, b, c, d, e, f, g, 0x71374491, w1 = BE32(chunk[1]));
|
||||
Round(g, h, a, b, c, d, e, f, 0xb5c0fbcf, w2 = BE32(chunk[2]));
|
||||
Round(f, g, h, a, b, c, d, e, 0xe9b5dba5, w3 = BE32(chunk[3]));
|
||||
Round(e, f, g, h, a, b, c, d, 0x3956c25b, w4 = BE32(chunk[4]));
|
||||
Round(d, e, f, g, h, a, b, c, 0x59f111f1, w5 = BE32(chunk[5]));
|
||||
Round(c, d, e, f, g, h, a, b, 0x923f82a4, w6 = BE32(chunk[6]));
|
||||
Round(b, c, d, e, f, g, h, a, 0xab1c5ed5, w7 = BE32(chunk[7]));
|
||||
Round(a, b, c, d, e, f, g, h, 0xd807aa98, w8 = BE32(chunk[8]));
|
||||
Round(h, a, b, c, d, e, f, g, 0x12835b01, w9 = BE32(chunk[9]));
|
||||
Round(g, h, a, b, c, d, e, f, 0x243185be, w10 = BE32(chunk[10]));
|
||||
Round(f, g, h, a, b, c, d, e, 0x550c7dc3, w11 = BE32(chunk[11]));
|
||||
Round(e, f, g, h, a, b, c, d, 0x72be5d74, w12 = BE32(chunk[12]));
|
||||
Round(d, e, f, g, h, a, b, c, 0x80deb1fe, w13 = BE32(chunk[13]));
|
||||
Round(c, d, e, f, g, h, a, b, 0x9bdc06a7, w14 = BE32(chunk[14]));
|
||||
Round(b, c, d, e, f, g, h, a, 0xc19bf174, w15 = BE32(chunk[15]));
|
||||
|
||||
Round(a, b, c, d, e, f, g, h, 0xe49b69c1, w0 += sigma1(w14) + w9 + sigma0(w1));
|
||||
Round(h, a, b, c, d, e, f, g, 0xefbe4786, w1 += sigma1(w15) + w10 + sigma0(w2));
|
||||
Round(g, h, a, b, c, d, e, f, 0x0fc19dc6, w2 += sigma1(w0) + w11 + sigma0(w3));
|
||||
Round(f, g, h, a, b, c, d, e, 0x240ca1cc, w3 += sigma1(w1) + w12 + sigma0(w4));
|
||||
Round(e, f, g, h, a, b, c, d, 0x2de92c6f, w4 += sigma1(w2) + w13 + sigma0(w5));
|
||||
Round(d, e, f, g, h, a, b, c, 0x4a7484aa, w5 += sigma1(w3) + w14 + sigma0(w6));
|
||||
Round(c, d, e, f, g, h, a, b, 0x5cb0a9dc, w6 += sigma1(w4) + w15 + sigma0(w7));
|
||||
Round(b, c, d, e, f, g, h, a, 0x76f988da, w7 += sigma1(w5) + w0 + sigma0(w8));
|
||||
Round(a, b, c, d, e, f, g, h, 0x983e5152, w8 += sigma1(w6) + w1 + sigma0(w9));
|
||||
Round(h, a, b, c, d, e, f, g, 0xa831c66d, w9 += sigma1(w7) + w2 + sigma0(w10));
|
||||
Round(g, h, a, b, c, d, e, f, 0xb00327c8, w10 += sigma1(w8) + w3 + sigma0(w11));
|
||||
Round(f, g, h, a, b, c, d, e, 0xbf597fc7, w11 += sigma1(w9) + w4 + sigma0(w12));
|
||||
Round(e, f, g, h, a, b, c, d, 0xc6e00bf3, w12 += sigma1(w10) + w5 + sigma0(w13));
|
||||
Round(d, e, f, g, h, a, b, c, 0xd5a79147, w13 += sigma1(w11) + w6 + sigma0(w14));
|
||||
Round(c, d, e, f, g, h, a, b, 0x06ca6351, w14 += sigma1(w12) + w7 + sigma0(w15));
|
||||
Round(b, c, d, e, f, g, h, a, 0x14292967, w15 += sigma1(w13) + w8 + sigma0(w0));
|
||||
|
||||
Round(a, b, c, d, e, f, g, h, 0x27b70a85, w0 += sigma1(w14) + w9 + sigma0(w1));
|
||||
Round(h, a, b, c, d, e, f, g, 0x2e1b2138, w1 += sigma1(w15) + w10 + sigma0(w2));
|
||||
Round(g, h, a, b, c, d, e, f, 0x4d2c6dfc, w2 += sigma1(w0) + w11 + sigma0(w3));
|
||||
Round(f, g, h, a, b, c, d, e, 0x53380d13, w3 += sigma1(w1) + w12 + sigma0(w4));
|
||||
Round(e, f, g, h, a, b, c, d, 0x650a7354, w4 += sigma1(w2) + w13 + sigma0(w5));
|
||||
Round(d, e, f, g, h, a, b, c, 0x766a0abb, w5 += sigma1(w3) + w14 + sigma0(w6));
|
||||
Round(c, d, e, f, g, h, a, b, 0x81c2c92e, w6 += sigma1(w4) + w15 + sigma0(w7));
|
||||
Round(b, c, d, e, f, g, h, a, 0x92722c85, w7 += sigma1(w5) + w0 + sigma0(w8));
|
||||
Round(a, b, c, d, e, f, g, h, 0xa2bfe8a1, w8 += sigma1(w6) + w1 + sigma0(w9));
|
||||
Round(h, a, b, c, d, e, f, g, 0xa81a664b, w9 += sigma1(w7) + w2 + sigma0(w10));
|
||||
Round(g, h, a, b, c, d, e, f, 0xc24b8b70, w10 += sigma1(w8) + w3 + sigma0(w11));
|
||||
Round(f, g, h, a, b, c, d, e, 0xc76c51a3, w11 += sigma1(w9) + w4 + sigma0(w12));
|
||||
Round(e, f, g, h, a, b, c, d, 0xd192e819, w12 += sigma1(w10) + w5 + sigma0(w13));
|
||||
Round(d, e, f, g, h, a, b, c, 0xd6990624, w13 += sigma1(w11) + w6 + sigma0(w14));
|
||||
Round(c, d, e, f, g, h, a, b, 0xf40e3585, w14 += sigma1(w12) + w7 + sigma0(w15));
|
||||
Round(b, c, d, e, f, g, h, a, 0x106aa070, w15 += sigma1(w13) + w8 + sigma0(w0));
|
||||
|
||||
Round(a, b, c, d, e, f, g, h, 0x19a4c116, w0 += sigma1(w14) + w9 + sigma0(w1));
|
||||
Round(h, a, b, c, d, e, f, g, 0x1e376c08, w1 += sigma1(w15) + w10 + sigma0(w2));
|
||||
Round(g, h, a, b, c, d, e, f, 0x2748774c, w2 += sigma1(w0) + w11 + sigma0(w3));
|
||||
Round(f, g, h, a, b, c, d, e, 0x34b0bcb5, w3 += sigma1(w1) + w12 + sigma0(w4));
|
||||
Round(e, f, g, h, a, b, c, d, 0x391c0cb3, w4 += sigma1(w2) + w13 + sigma0(w5));
|
||||
Round(d, e, f, g, h, a, b, c, 0x4ed8aa4a, w5 += sigma1(w3) + w14 + sigma0(w6));
|
||||
Round(c, d, e, f, g, h, a, b, 0x5b9cca4f, w6 += sigma1(w4) + w15 + sigma0(w7));
|
||||
Round(b, c, d, e, f, g, h, a, 0x682e6ff3, w7 += sigma1(w5) + w0 + sigma0(w8));
|
||||
Round(a, b, c, d, e, f, g, h, 0x748f82ee, w8 += sigma1(w6) + w1 + sigma0(w9));
|
||||
Round(h, a, b, c, d, e, f, g, 0x78a5636f, w9 += sigma1(w7) + w2 + sigma0(w10));
|
||||
Round(g, h, a, b, c, d, e, f, 0x84c87814, w10 += sigma1(w8) + w3 + sigma0(w11));
|
||||
Round(f, g, h, a, b, c, d, e, 0x8cc70208, w11 += sigma1(w9) + w4 + sigma0(w12));
|
||||
Round(e, f, g, h, a, b, c, d, 0x90befffa, w12 += sigma1(w10) + w5 + sigma0(w13));
|
||||
Round(d, e, f, g, h, a, b, c, 0xa4506ceb, w13 += sigma1(w11) + w6 + sigma0(w14));
|
||||
Round(c, d, e, f, g, h, a, b, 0xbef9a3f7, w14 + sigma1(w12) + w7 + sigma0(w15));
|
||||
Round(b, c, d, e, f, g, h, a, 0xc67178f2, w15 + sigma1(w13) + w8 + sigma0(w0));
|
||||
|
||||
s[0] += a;
|
||||
s[1] += b;
|
||||
s[2] += c;
|
||||
s[3] += d;
|
||||
s[4] += e;
|
||||
s[5] += f;
|
||||
s[6] += g;
|
||||
s[7] += h;
|
||||
}
|
||||
|
||||
static void secp256k1_sha256_write(secp256k1_sha256_t *hash, const unsigned char *data, size_t len) {
|
||||
size_t bufsize = hash->bytes & 0x3F;
|
||||
hash->bytes += len;
|
||||
while (bufsize + len >= 64) {
|
||||
/* Fill the buffer, and process it. */
|
||||
memcpy(((unsigned char*)hash->buf) + bufsize, data, 64 - bufsize);
|
||||
data += 64 - bufsize;
|
||||
len -= 64 - bufsize;
|
||||
secp256k1_sha256_transform(hash->s, hash->buf);
|
||||
bufsize = 0;
|
||||
}
|
||||
if (len) {
|
||||
/* Fill the buffer with what remains. */
|
||||
memcpy(((unsigned char*)hash->buf) + bufsize, data, len);
|
||||
}
|
||||
}
|
||||
|
||||
static void secp256k1_sha256_finalize(secp256k1_sha256_t *hash, unsigned char *out32) {
|
||||
static const unsigned char pad[64] = {0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
|
||||
uint32_t sizedesc[2];
|
||||
uint32_t out[8];
|
||||
int i = 0;
|
||||
sizedesc[0] = BE32(hash->bytes >> 29);
|
||||
sizedesc[1] = BE32(hash->bytes << 3);
|
||||
secp256k1_sha256_write(hash, pad, 1 + ((119 - (hash->bytes % 64)) % 64));
|
||||
secp256k1_sha256_write(hash, (const unsigned char*)sizedesc, 8);
|
||||
for (i = 0; i < 8; i++) {
|
||||
out[i] = BE32(hash->s[i]);
|
||||
hash->s[i] = 0;
|
||||
}
|
||||
memcpy(out32, (const unsigned char*)out, 32);
|
||||
}
|
||||
|
||||
static void secp256k1_hmac_sha256_initialize(secp256k1_hmac_sha256_t *hash, const unsigned char *key, size_t keylen) {
|
||||
int n;
|
||||
unsigned char rkey[64];
|
||||
if (keylen <= 64) {
|
||||
memcpy(rkey, key, keylen);
|
||||
memset(rkey + keylen, 0, 64 - keylen);
|
||||
} else {
|
||||
secp256k1_sha256_t sha256;
|
||||
secp256k1_sha256_initialize(&sha256);
|
||||
secp256k1_sha256_write(&sha256, key, keylen);
|
||||
secp256k1_sha256_finalize(&sha256, rkey);
|
||||
memset(rkey + 32, 0, 32);
|
||||
}
|
||||
|
||||
secp256k1_sha256_initialize(&hash->outer);
|
||||
for (n = 0; n < 64; n++) {
|
||||
rkey[n] ^= 0x5c;
|
||||
}
|
||||
secp256k1_sha256_write(&hash->outer, rkey, 64);
|
||||
|
||||
secp256k1_sha256_initialize(&hash->inner);
|
||||
for (n = 0; n < 64; n++) {
|
||||
rkey[n] ^= 0x5c ^ 0x36;
|
||||
}
|
||||
secp256k1_sha256_write(&hash->inner, rkey, 64);
|
||||
memset(rkey, 0, 64);
|
||||
}
|
||||
|
||||
static void secp256k1_hmac_sha256_write(secp256k1_hmac_sha256_t *hash, const unsigned char *data, size_t size) {
|
||||
secp256k1_sha256_write(&hash->inner, data, size);
|
||||
}
|
||||
|
||||
static void secp256k1_hmac_sha256_finalize(secp256k1_hmac_sha256_t *hash, unsigned char *out32) {
|
||||
unsigned char temp[32];
|
||||
secp256k1_sha256_finalize(&hash->inner, temp);
|
||||
secp256k1_sha256_write(&hash->outer, temp, 32);
|
||||
memset(temp, 0, 32);
|
||||
secp256k1_sha256_finalize(&hash->outer, out32);
|
||||
}
|
||||
|
||||
|
||||
static void secp256k1_rfc6979_hmac_sha256_initialize(secp256k1_rfc6979_hmac_sha256_t *rng, const unsigned char *key, size_t keylen, const unsigned char *msg, size_t msglen, const unsigned char *rnd, size_t rndlen) {
|
||||
secp256k1_hmac_sha256_t hmac;
|
||||
static const unsigned char zero[1] = {0x00};
|
||||
static const unsigned char one[1] = {0x01};
|
||||
|
||||
memset(rng->v, 0x01, 32); /* RFC6979 3.2.b. */
|
||||
memset(rng->k, 0x00, 32); /* RFC6979 3.2.c. */
|
||||
|
||||
/* RFC6979 3.2.d. */
|
||||
secp256k1_hmac_sha256_initialize(&hmac, rng->k, 32);
|
||||
secp256k1_hmac_sha256_write(&hmac, rng->v, 32);
|
||||
secp256k1_hmac_sha256_write(&hmac, zero, 1);
|
||||
secp256k1_hmac_sha256_write(&hmac, key, keylen);
|
||||
secp256k1_hmac_sha256_write(&hmac, msg, msglen);
|
||||
if (rnd && rndlen) {
|
||||
/* RFC6979 3.6 "Additional data". */
|
||||
secp256k1_hmac_sha256_write(&hmac, rnd, rndlen);
|
||||
}
|
||||
secp256k1_hmac_sha256_finalize(&hmac, rng->k);
|
||||
secp256k1_hmac_sha256_initialize(&hmac, rng->k, 32);
|
||||
secp256k1_hmac_sha256_write(&hmac, rng->v, 32);
|
||||
secp256k1_hmac_sha256_finalize(&hmac, rng->v);
|
||||
|
||||
/* RFC6979 3.2.f. */
|
||||
secp256k1_hmac_sha256_initialize(&hmac, rng->k, 32);
|
||||
secp256k1_hmac_sha256_write(&hmac, rng->v, 32);
|
||||
secp256k1_hmac_sha256_write(&hmac, one, 1);
|
||||
secp256k1_hmac_sha256_write(&hmac, key, keylen);
|
||||
secp256k1_hmac_sha256_write(&hmac, msg, msglen);
|
||||
if (rnd && rndlen) {
|
||||
/* RFC6979 3.6 "Additional data". */
|
||||
secp256k1_hmac_sha256_write(&hmac, rnd, rndlen);
|
||||
}
|
||||
secp256k1_hmac_sha256_finalize(&hmac, rng->k);
|
||||
secp256k1_hmac_sha256_initialize(&hmac, rng->k, 32);
|
||||
secp256k1_hmac_sha256_write(&hmac, rng->v, 32);
|
||||
secp256k1_hmac_sha256_finalize(&hmac, rng->v);
|
||||
rng->retry = 0;
|
||||
}
|
||||
|
||||
static void secp256k1_rfc6979_hmac_sha256_generate(secp256k1_rfc6979_hmac_sha256_t *rng, unsigned char *out, size_t outlen) {
|
||||
/* RFC6979 3.2.h. */
|
||||
static const unsigned char zero[1] = {0x00};
|
||||
if (rng->retry) {
|
||||
secp256k1_hmac_sha256_t hmac;
|
||||
secp256k1_hmac_sha256_initialize(&hmac, rng->k, 32);
|
||||
secp256k1_hmac_sha256_write(&hmac, rng->v, 32);
|
||||
secp256k1_hmac_sha256_write(&hmac, zero, 1);
|
||||
secp256k1_hmac_sha256_finalize(&hmac, rng->k);
|
||||
secp256k1_hmac_sha256_initialize(&hmac, rng->k, 32);
|
||||
secp256k1_hmac_sha256_write(&hmac, rng->v, 32);
|
||||
secp256k1_hmac_sha256_finalize(&hmac, rng->v);
|
||||
}
|
||||
|
||||
while (outlen > 0) {
|
||||
secp256k1_hmac_sha256_t hmac;
|
||||
int now = outlen;
|
||||
secp256k1_hmac_sha256_initialize(&hmac, rng->k, 32);
|
||||
secp256k1_hmac_sha256_write(&hmac, rng->v, 32);
|
||||
secp256k1_hmac_sha256_finalize(&hmac, rng->v);
|
||||
if (now > 32) {
|
||||
now = 32;
|
||||
}
|
||||
memcpy(out, rng->v, now);
|
||||
out += now;
|
||||
outlen -= now;
|
||||
}
|
||||
|
||||
rng->retry = 1;
|
||||
}
|
||||
|
||||
static void secp256k1_rfc6979_hmac_sha256_finalize(secp256k1_rfc6979_hmac_sha256_t *rng) {
|
||||
memset(rng->k, 0, 32);
|
||||
memset(rng->v, 0, 32);
|
||||
rng->retry = 0;
|
||||
}
|
||||
|
||||
|
||||
#undef Round
|
||||
#undef sigma0
|
||||
#undef sigma1
|
||||
#undef Sigma0
|
||||
#undef Sigma1
|
||||
#undef Ch
|
||||
#undef Maj
|
||||
#undef ReadBE32
|
||||
#undef WriteBE32
|
||||
|
||||
#endif
|
||||
|
|
@ -1,309 +0,0 @@
|
|||
// Copyright (c) 2013 Pieter Wuille
|
||||
// Distributed under the MIT/X11 software license, see the accompanying
|
||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||
|
||||
#ifndef _SECP256K1_ECDSA_IMPL_H_
|
||||
#define _SECP256K1_ECDSA_IMPL_H_
|
||||
|
||||
#include "../num.h"
|
||||
#include "../field.h"
|
||||
#include "../group.h"
|
||||
#include "../ecmult.h"
|
||||
#include "../ecdsa.h"
|
||||
|
||||
void static secp256k1_ecdsa_sig_init(secp256k1_ecdsa_sig_t *r) {
|
||||
secp256k1_num_init(&r->r);
|
||||
secp256k1_num_init(&r->s);
|
||||
}
|
||||
|
||||
void static secp256k1_ecdsa_sig_free(secp256k1_ecdsa_sig_t *r) {
|
||||
secp256k1_num_free(&r->r);
|
||||
secp256k1_num_free(&r->s);
|
||||
}
|
||||
|
||||
int static secp256k1_ecdsa_pubkey_parse(secp256k1_ge_t *elem, const unsigned char *pub, int size) {
|
||||
if (size == 33 && (pub[0] == 0x02 || pub[0] == 0x03)) {
|
||||
secp256k1_fe_t x;
|
||||
secp256k1_fe_set_b32(&x, pub+1);
|
||||
secp256k1_ge_set_xo(elem, &x, pub[0] == 0x03);
|
||||
} else if (size == 65 && (pub[0] == 0x04 || pub[0] == 0x06 || pub[0] == 0x07)) {
|
||||
secp256k1_fe_t x, y;
|
||||
secp256k1_fe_set_b32(&x, pub+1);
|
||||
secp256k1_fe_set_b32(&y, pub+33);
|
||||
secp256k1_ge_set_xy(elem, &x, &y);
|
||||
if ((pub[0] == 0x06 || pub[0] == 0x07) && secp256k1_fe_is_odd(&y) != (pub[0] == 0x07))
|
||||
return 0;
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
return secp256k1_ge_is_valid(elem);
|
||||
}
|
||||
|
||||
int static secp256k1_ecdsa_sig_parse(secp256k1_ecdsa_sig_t *r, const unsigned char *sig, int size) {
|
||||
if (sig[0] != 0x30) return 0;
|
||||
int lenr = sig[3];
|
||||
if (5+lenr >= size) return 0;
|
||||
int lens = sig[lenr+5];
|
||||
if (sig[1] != lenr+lens+4) return 0;
|
||||
if (lenr+lens+6 > size) return 0;
|
||||
if (sig[2] != 0x02) return 0;
|
||||
if (lenr == 0) return 0;
|
||||
if (sig[lenr+4] != 0x02) return 0;
|
||||
if (lens == 0) return 0;
|
||||
secp256k1_num_set_bin(&r->r, sig+4, lenr);
|
||||
secp256k1_num_set_bin(&r->s, sig+6+lenr, lens);
|
||||
return 1;
|
||||
}
|
||||
|
||||
int static secp256k1_ecdsa_sig_serialize(unsigned char *sig, int *size, const secp256k1_ecdsa_sig_t *a) {
|
||||
int lenR = (secp256k1_num_bits(&a->r) + 7)/8;
|
||||
if (lenR == 0 || secp256k1_num_get_bit(&a->r, lenR*8-1))
|
||||
lenR++;
|
||||
int lenS = (secp256k1_num_bits(&a->s) + 7)/8;
|
||||
if (lenS == 0 || secp256k1_num_get_bit(&a->s, lenS*8-1))
|
||||
lenS++;
|
||||
if (*size < 6+lenS+lenR)
|
||||
return 0;
|
||||
*size = 6 + lenS + lenR;
|
||||
sig[0] = 0x30;
|
||||
sig[1] = 4 + lenS + lenR;
|
||||
sig[2] = 0x02;
|
||||
sig[3] = lenR;
|
||||
secp256k1_num_get_bin(sig+4, lenR, &a->r);
|
||||
sig[4+lenR] = 0x02;
|
||||
sig[5+lenR] = lenS;
|
||||
secp256k1_num_get_bin(sig+lenR+6, lenS, &a->s);
|
||||
return 1;
|
||||
}
|
||||
|
||||
int static secp256k1_ecdsa_sig_recompute(secp256k1_num_t *r2, const secp256k1_ecdsa_sig_t *sig, const secp256k1_ge_t *pubkey, const secp256k1_num_t *message) {
|
||||
const secp256k1_ge_consts_t *c = secp256k1_ge_consts;
|
||||
|
||||
if (secp256k1_num_is_neg(&sig->r) || secp256k1_num_is_neg(&sig->s))
|
||||
return 0;
|
||||
if (secp256k1_num_is_zero(&sig->r) || secp256k1_num_is_zero(&sig->s))
|
||||
return 0;
|
||||
if (secp256k1_num_cmp(&sig->r, &c->order) >= 0 || secp256k1_num_cmp(&sig->s, &c->order) >= 0)
|
||||
return 0;
|
||||
|
||||
int ret = 0;
|
||||
secp256k1_num_t sn, u1, u2;
|
||||
secp256k1_num_init(&sn);
|
||||
secp256k1_num_init(&u1);
|
||||
secp256k1_num_init(&u2);
|
||||
secp256k1_num_mod_inverse(&sn, &sig->s, &c->order);
|
||||
secp256k1_num_mod_mul(&u1, &sn, message, &c->order);
|
||||
secp256k1_num_mod_mul(&u2, &sn, &sig->r, &c->order);
|
||||
secp256k1_gej_t pubkeyj; secp256k1_gej_set_ge(&pubkeyj, pubkey);
|
||||
secp256k1_gej_t pr; secp256k1_ecmult(&pr, &pubkeyj, &u2, &u1);
|
||||
if (!secp256k1_gej_is_infinity(&pr)) {
|
||||
secp256k1_fe_t xr; secp256k1_gej_get_x(&xr, &pr);
|
||||
secp256k1_fe_normalize(&xr);
|
||||
unsigned char xrb[32]; secp256k1_fe_get_b32(xrb, &xr);
|
||||
secp256k1_num_set_bin(r2, xrb, 32);
|
||||
secp256k1_num_mod(r2, &c->order);
|
||||
ret = 1;
|
||||
}
|
||||
secp256k1_num_free(&sn);
|
||||
secp256k1_num_free(&u1);
|
||||
secp256k1_num_free(&u2);
|
||||
return ret;
|
||||
}
|
||||
|
||||
int static secp256k1_ecdsa_sig_recover(const secp256k1_ecdsa_sig_t *sig, secp256k1_ge_t *pubkey, const secp256k1_num_t *message, int recid) {
|
||||
const secp256k1_ge_consts_t *c = secp256k1_ge_consts;
|
||||
|
||||
if (secp256k1_num_is_neg(&sig->r) || secp256k1_num_is_neg(&sig->s))
|
||||
return 0;
|
||||
if (secp256k1_num_is_zero(&sig->r) || secp256k1_num_is_zero(&sig->s))
|
||||
return 0;
|
||||
if (secp256k1_num_cmp(&sig->r, &c->order) >= 0 || secp256k1_num_cmp(&sig->s, &c->order) >= 0)
|
||||
return 0;
|
||||
|
||||
secp256k1_num_t rx;
|
||||
secp256k1_num_init(&rx);
|
||||
secp256k1_num_copy(&rx, &sig->r);
|
||||
if (recid & 2) {
|
||||
secp256k1_num_add(&rx, &rx, &c->order);
|
||||
if (secp256k1_num_cmp(&rx, &secp256k1_fe_consts->p) >= 0)
|
||||
return 0;
|
||||
}
|
||||
unsigned char brx[32];
|
||||
secp256k1_num_get_bin(brx, 32, &rx);
|
||||
secp256k1_num_free(&rx);
|
||||
secp256k1_fe_t fx;
|
||||
secp256k1_fe_set_b32(&fx, brx);
|
||||
secp256k1_ge_t x;
|
||||
secp256k1_ge_set_xo(&x, &fx, recid & 1);
|
||||
if (!secp256k1_ge_is_valid(&x))
|
||||
return 0;
|
||||
secp256k1_gej_t xj;
|
||||
secp256k1_gej_set_ge(&xj, &x);
|
||||
secp256k1_num_t rn, u1, u2;
|
||||
secp256k1_num_init(&rn);
|
||||
secp256k1_num_init(&u1);
|
||||
secp256k1_num_init(&u2);
|
||||
secp256k1_num_mod_inverse(&rn, &sig->r, &c->order);
|
||||
secp256k1_num_mod_mul(&u1, &rn, message, &c->order);
|
||||
secp256k1_num_sub(&u1, &c->order, &u1);
|
||||
secp256k1_num_mod_mul(&u2, &rn, &sig->s, &c->order);
|
||||
secp256k1_gej_t qj;
|
||||
secp256k1_ecmult(&qj, &xj, &u2, &u1);
|
||||
if (secp256k1_gej_is_infinity(&qj))
|
||||
return 0;
|
||||
secp256k1_ge_set_gej(pubkey, &qj);
|
||||
secp256k1_num_free(&rn);
|
||||
secp256k1_num_free(&u1);
|
||||
secp256k1_num_free(&u2);
|
||||
return 1;
|
||||
}
|
||||
|
||||
int static secp256k1_ecdsa_sig_verify(const secp256k1_ecdsa_sig_t *sig, const secp256k1_ge_t *pubkey, const secp256k1_num_t *message) {
|
||||
secp256k1_num_t r2;
|
||||
secp256k1_num_init(&r2);
|
||||
int ret = 0;
|
||||
ret = secp256k1_ecdsa_sig_recompute(&r2, sig, pubkey, message) && secp256k1_num_cmp(&sig->r, &r2) == 0;
|
||||
secp256k1_num_free(&r2);
|
||||
return ret;
|
||||
}
|
||||
|
||||
int static secp256k1_ecdsa_sig_sign(secp256k1_ecdsa_sig_t *sig, const secp256k1_num_t *seckey, const secp256k1_num_t *message, const secp256k1_num_t *nonce, int *recid) {
|
||||
const secp256k1_ge_consts_t *c = secp256k1_ge_consts;
|
||||
|
||||
secp256k1_gej_t rp;
|
||||
secp256k1_ecmult_gen(&rp, nonce);
|
||||
secp256k1_ge_t r;
|
||||
secp256k1_ge_set_gej(&r, &rp);
|
||||
unsigned char b[32];
|
||||
secp256k1_fe_normalize(&r.x);
|
||||
secp256k1_fe_normalize(&r.y);
|
||||
secp256k1_fe_get_b32(b, &r.x);
|
||||
secp256k1_num_set_bin(&sig->r, b, 32);
|
||||
if (recid)
|
||||
*recid = (secp256k1_num_cmp(&sig->r, &c->order) >= 0 ? 2 : 0) | (secp256k1_fe_is_odd(&r.y) ? 1 : 0);
|
||||
secp256k1_num_mod(&sig->r, &c->order);
|
||||
secp256k1_num_t n;
|
||||
secp256k1_num_init(&n);
|
||||
secp256k1_num_mod_mul(&n, &sig->r, seckey, &c->order);
|
||||
secp256k1_num_add(&n, &n, message);
|
||||
secp256k1_num_mod(&n, &c->order);
|
||||
secp256k1_num_mod_inverse(&sig->s, nonce, &c->order);
|
||||
secp256k1_num_mod_mul(&sig->s, &sig->s, &n, &c->order);
|
||||
secp256k1_num_free(&n);
|
||||
if (secp256k1_num_is_zero(&sig->s))
|
||||
return 0;
|
||||
if (secp256k1_num_cmp(&sig->s, &c->half_order) > 0) {
|
||||
secp256k1_num_sub(&sig->s, &c->order, &sig->s);
|
||||
if (recid)
|
||||
*recid ^= 1;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
void static secp256k1_ecdsa_sig_set_rs(secp256k1_ecdsa_sig_t *sig, const secp256k1_num_t *r, const secp256k1_num_t *s) {
|
||||
secp256k1_num_copy(&sig->r, r);
|
||||
secp256k1_num_copy(&sig->s, s);
|
||||
}
|
||||
|
||||
void static secp256k1_ecdsa_pubkey_serialize(secp256k1_ge_t *elem, unsigned char *pub, int *size, int compressed) {
|
||||
secp256k1_fe_normalize(&elem->x);
|
||||
secp256k1_fe_normalize(&elem->y);
|
||||
secp256k1_fe_get_b32(&pub[1], &elem->x);
|
||||
if (compressed) {
|
||||
*size = 33;
|
||||
pub[0] = 0x02 | (secp256k1_fe_is_odd(&elem->y) ? 0x01 : 0x00);
|
||||
} else {
|
||||
*size = 65;
|
||||
pub[0] = 0x04;
|
||||
secp256k1_fe_get_b32(&pub[33], &elem->y);
|
||||
}
|
||||
}
|
||||
|
||||
int static secp256k1_ecdsa_privkey_parse(secp256k1_num_t *key, const unsigned char *privkey, int privkeylen) {
|
||||
const unsigned char *end = privkey + privkeylen;
|
||||
// sequence header
|
||||
if (end < privkey+1 || *privkey != 0x30)
|
||||
return 0;
|
||||
privkey++;
|
||||
// sequence length constructor
|
||||
int lenb = 0;
|
||||
if (end < privkey+1 || !(*privkey & 0x80))
|
||||
return 0;
|
||||
lenb = *privkey & ~0x80; privkey++;
|
||||
if (lenb < 1 || lenb > 2)
|
||||
return 0;
|
||||
if (end < privkey+lenb)
|
||||
return 0;
|
||||
// sequence length
|
||||
int len = 0;
|
||||
len = privkey[lenb-1] | (lenb > 1 ? privkey[lenb-2] << 8 : 0);
|
||||
privkey += lenb;
|
||||
if (end < privkey+len)
|
||||
return 0;
|
||||
// sequence element 0: version number (=1)
|
||||
if (end < privkey+3 || privkey[0] != 0x02 || privkey[1] != 0x01 || privkey[2] != 0x01)
|
||||
return 0;
|
||||
privkey += 3;
|
||||
// sequence element 1: octet string, up to 32 bytes
|
||||
if (end < privkey+2 || privkey[0] != 0x04 || privkey[1] > 0x20 || end < privkey+2+privkey[1])
|
||||
return 0;
|
||||
secp256k1_num_set_bin(key, privkey+2, privkey[1]);
|
||||
return 1;
|
||||
}
|
||||
|
||||
int static secp256k1_ecdsa_privkey_serialize(unsigned char *privkey, int *privkeylen, const secp256k1_num_t *key, int compressed) {
|
||||
secp256k1_gej_t rp;
|
||||
secp256k1_ecmult_gen(&rp, key);
|
||||
secp256k1_ge_t r;
|
||||
secp256k1_ge_set_gej(&r, &rp);
|
||||
if (compressed) {
|
||||
static const unsigned char begin[] = {
|
||||
0x30,0x81,0xD3,0x02,0x01,0x01,0x04,0x20
|
||||
};
|
||||
static const unsigned char middle[] = {
|
||||
0xA0,0x81,0x85,0x30,0x81,0x82,0x02,0x01,0x01,0x30,0x2C,0x06,0x07,0x2A,0x86,0x48,
|
||||
0xCE,0x3D,0x01,0x01,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
|
||||
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
|
||||
0xFF,0xFF,0xFE,0xFF,0xFF,0xFC,0x2F,0x30,0x06,0x04,0x01,0x00,0x04,0x01,0x07,0x04,
|
||||
0x21,0x02,0x79,0xBE,0x66,0x7E,0xF9,0xDC,0xBB,0xAC,0x55,0xA0,0x62,0x95,0xCE,0x87,
|
||||
0x0B,0x07,0x02,0x9B,0xFC,0xDB,0x2D,0xCE,0x28,0xD9,0x59,0xF2,0x81,0x5B,0x16,0xF8,
|
||||
0x17,0x98,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
|
||||
0xFF,0xFF,0xFF,0xFF,0xFE,0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B,0xBF,0xD2,0x5E,
|
||||
0x8C,0xD0,0x36,0x41,0x41,0x02,0x01,0x01,0xA1,0x24,0x03,0x22,0x00
|
||||
};
|
||||
unsigned char *ptr = privkey;
|
||||
memcpy(ptr, begin, sizeof(begin)); ptr += sizeof(begin);
|
||||
secp256k1_num_get_bin(ptr, 32, key); ptr += 32;
|
||||
memcpy(ptr, middle, sizeof(middle)); ptr += sizeof(middle);
|
||||
int pubkeylen = 0;
|
||||
secp256k1_ecdsa_pubkey_serialize(&r, ptr, &pubkeylen, 1); ptr += pubkeylen;
|
||||
*privkeylen = ptr - privkey;
|
||||
} else {
|
||||
static const unsigned char begin[] = {
|
||||
0x30,0x82,0x01,0x13,0x02,0x01,0x01,0x04,0x20
|
||||
};
|
||||
static const unsigned char middle[] = {
|
||||
0xA0,0x81,0xA5,0x30,0x81,0xA2,0x02,0x01,0x01,0x30,0x2C,0x06,0x07,0x2A,0x86,0x48,
|
||||
0xCE,0x3D,0x01,0x01,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
|
||||
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
|
||||
0xFF,0xFF,0xFE,0xFF,0xFF,0xFC,0x2F,0x30,0x06,0x04,0x01,0x00,0x04,0x01,0x07,0x04,
|
||||
0x41,0x04,0x79,0xBE,0x66,0x7E,0xF9,0xDC,0xBB,0xAC,0x55,0xA0,0x62,0x95,0xCE,0x87,
|
||||
0x0B,0x07,0x02,0x9B,0xFC,0xDB,0x2D,0xCE,0x28,0xD9,0x59,0xF2,0x81,0x5B,0x16,0xF8,
|
||||
0x17,0x98,0x48,0x3A,0xDA,0x77,0x26,0xA3,0xC4,0x65,0x5D,0xA4,0xFB,0xFC,0x0E,0x11,
|
||||
0x08,0xA8,0xFD,0x17,0xB4,0x48,0xA6,0x85,0x54,0x19,0x9C,0x47,0xD0,0x8F,0xFB,0x10,
|
||||
0xD4,0xB8,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
|
||||
0xFF,0xFF,0xFF,0xFF,0xFE,0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B,0xBF,0xD2,0x5E,
|
||||
0x8C,0xD0,0x36,0x41,0x41,0x02,0x01,0x01,0xA1,0x44,0x03,0x42,0x00
|
||||
};
|
||||
unsigned char *ptr = privkey;
|
||||
memcpy(ptr, begin, sizeof(begin)); ptr += sizeof(begin);
|
||||
secp256k1_num_get_bin(ptr, 32, key); ptr += 32;
|
||||
memcpy(ptr, middle, sizeof(middle)); ptr += sizeof(middle);
|
||||
int pubkeylen = 0;
|
||||
secp256k1_ecdsa_pubkey_serialize(&r, ptr, &pubkeylen, 0); ptr += pubkeylen;
|
||||
*privkeylen = ptr - privkey;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
#endif
|
||||
|
|
@ -1,238 +0,0 @@
|
|||
// Copyright (c) 2013 Pieter Wuille
|
||||
// Distributed under the MIT/X11 software license, see the accompanying
|
||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||
|
||||
#ifndef _SECP256K1_ECMULT_IMPL_H_
|
||||
#define _SECP256K1_ECMULT_IMPL_H_
|
||||
|
||||
#include "../num.h"
|
||||
#include "../group.h"
|
||||
#include "../ecmult.h"
|
||||
|
||||
// optimal for 128-bit and 256-bit exponents.
|
||||
#define WINDOW_A 5
|
||||
|
||||
// larger numbers may result in slightly better performance, at the cost of
|
||||
// exponentially larger precomputed tables. WINDOW_G == 14 results in 640 KiB.
|
||||
#define WINDOW_G 14
|
||||
|
||||
/** Fill a table 'pre' with precomputed odd multiples of a. W determines the size of the table.
|
||||
* pre will contains the values [1*a,3*a,5*a,...,(2^(w-1)-1)*a], so it needs place for
|
||||
* 2^(w-2) entries.
|
||||
*
|
||||
* There are two versions of this function:
|
||||
* - secp256k1_ecmult_precomp_wnaf_gej, which operates on group elements in jacobian notation,
|
||||
* fast to precompute, but slower to use in later additions.
|
||||
* - secp256k1_ecmult_precomp_wnaf_ge, which operates on group elements in affine notations,
|
||||
* (much) slower to precompute, but a bit faster to use in later additions.
|
||||
* To compute a*P + b*G, we use the jacobian version for P, and the affine version for G, as
|
||||
* G is constant, so it only needs to be done once in advance.
|
||||
*/
|
||||
void static secp256k1_ecmult_table_precomp_gej(secp256k1_gej_t *pre, const secp256k1_gej_t *a, int w) {
|
||||
pre[0] = *a;
|
||||
secp256k1_gej_t d; secp256k1_gej_double(&d, &pre[0]);
|
||||
for (int i=1; i<(1 << (w-2)); i++)
|
||||
secp256k1_gej_add(&pre[i], &d, &pre[i-1]);
|
||||
}
|
||||
|
||||
void static secp256k1_ecmult_table_precomp_ge(secp256k1_ge_t *pre, const secp256k1_ge_t *a, int w) {
|
||||
pre[0] = *a;
|
||||
secp256k1_gej_t x; secp256k1_gej_set_ge(&x, a);
|
||||
secp256k1_gej_t d; secp256k1_gej_double(&d, &x);
|
||||
for (int i=1; i<(1 << (w-2)); i++) {
|
||||
secp256k1_gej_add_ge(&x, &d, &pre[i-1]);
|
||||
secp256k1_ge_set_gej(&pre[i], &x);
|
||||
}
|
||||
}
|
||||
|
||||
/** The number of entries a table with precomputed multiples needs to have. */
|
||||
#define ECMULT_TABLE_SIZE(w) (1 << ((w)-2))
|
||||
|
||||
/** The following two macro retrieves a particular odd multiple from a table
|
||||
* of precomputed multiples. */
|
||||
#define ECMULT_TABLE_GET(r,pre,n,w,neg) do { \
|
||||
assert(((n) & 1) == 1); \
|
||||
assert((n) >= -((1 << ((w)-1)) - 1)); \
|
||||
assert((n) <= ((1 << ((w)-1)) - 1)); \
|
||||
if ((n) > 0) \
|
||||
*(r) = (pre)[((n)-1)/2]; \
|
||||
else \
|
||||
(neg)((r), &(pre)[(-(n)-1)/2]); \
|
||||
} while(0)
|
||||
|
||||
#define ECMULT_TABLE_GET_GEJ(r,pre,n,w) ECMULT_TABLE_GET((r),(pre),(n),(w),secp256k1_gej_neg)
|
||||
#define ECMULT_TABLE_GET_GE(r,pre,n,w) ECMULT_TABLE_GET((r),(pre),(n),(w),secp256k1_ge_neg)
|
||||
|
||||
typedef struct {
|
||||
secp256k1_ge_t pre_g[ECMULT_TABLE_SIZE(WINDOW_G)]; // odd multiples of the generator
|
||||
secp256k1_ge_t pre_g_128[ECMULT_TABLE_SIZE(WINDOW_G)]; // odd multiples of 2^128*generator
|
||||
secp256k1_ge_t prec[64][16]; // prec[j][i] = 16^j * (i+1) * G
|
||||
secp256k1_ge_t fin; // -(sum(prec[j][0], j=0..63))
|
||||
} secp256k1_ecmult_consts_t;
|
||||
|
||||
static const secp256k1_ecmult_consts_t *secp256k1_ecmult_consts = NULL;
|
||||
|
||||
static void secp256k1_ecmult_start(void) {
|
||||
if (secp256k1_ecmult_consts != NULL)
|
||||
return;
|
||||
|
||||
secp256k1_ecmult_consts_t *ret = (secp256k1_ecmult_consts_t*)malloc(sizeof(secp256k1_ecmult_consts_t));
|
||||
secp256k1_ecmult_consts = ret;
|
||||
|
||||
// get the generator
|
||||
const secp256k1_ge_t *g = &secp256k1_ge_consts->g;
|
||||
|
||||
// calculate 2^128*generator
|
||||
secp256k1_gej_t g_128j; secp256k1_gej_set_ge(&g_128j, g);
|
||||
for (int i=0; i<128; i++)
|
||||
secp256k1_gej_double(&g_128j, &g_128j);
|
||||
secp256k1_ge_t g_128; secp256k1_ge_set_gej(&g_128, &g_128j);
|
||||
|
||||
// precompute the tables with odd multiples
|
||||
secp256k1_ecmult_table_precomp_ge(ret->pre_g, g, WINDOW_G);
|
||||
secp256k1_ecmult_table_precomp_ge(ret->pre_g_128, &g_128, WINDOW_G);
|
||||
|
||||
// compute prec and fin
|
||||
secp256k1_gej_t gg; secp256k1_gej_set_ge(&gg, g);
|
||||
secp256k1_ge_t ad = *g;
|
||||
secp256k1_gej_t fn; secp256k1_gej_set_infinity(&fn);
|
||||
for (int j=0; j<64; j++) {
|
||||
secp256k1_ge_set_gej(&ret->prec[j][0], &gg);
|
||||
secp256k1_gej_add(&fn, &fn, &gg);
|
||||
for (int i=1; i<16; i++) {
|
||||
secp256k1_gej_add_ge(&gg, &gg, &ad);
|
||||
secp256k1_ge_set_gej(&ret->prec[j][i], &gg);
|
||||
}
|
||||
ad = ret->prec[j][15];
|
||||
}
|
||||
secp256k1_ge_set_gej(&ret->fin, &fn);
|
||||
secp256k1_ge_neg(&ret->fin, &ret->fin);
|
||||
}
|
||||
|
||||
static void secp256k1_ecmult_stop(void) {
|
||||
if (secp256k1_ecmult_consts == NULL)
|
||||
return;
|
||||
|
||||
secp256k1_ecmult_consts_t *c = (secp256k1_ecmult_consts_t*)secp256k1_ecmult_consts;
|
||||
free(c);
|
||||
secp256k1_ecmult_consts = NULL;
|
||||
}
|
||||
|
||||
/** Convert a number to WNAF notation. The number becomes represented by sum(2^i * wnaf[i], i=0..bits),
|
||||
* with the following guarantees:
|
||||
* - each wnaf[i] is either 0, or an odd integer between -(1<<(w-1) - 1) and (1<<(w-1) - 1)
|
||||
* - two non-zero entries in wnaf are separated by at least w-1 zeroes.
|
||||
* - the index of the highest non-zero entry in wnaf (=return value-1) is at most bits, where
|
||||
* bits is the number of bits necessary to represent the absolute value of the input.
|
||||
*/
|
||||
static int secp256k1_ecmult_wnaf(int *wnaf, const secp256k1_num_t *a, int w) {
|
||||
int ret = 0;
|
||||
int zeroes = 0;
|
||||
secp256k1_num_t x;
|
||||
secp256k1_num_init(&x);
|
||||
secp256k1_num_copy(&x, a);
|
||||
int sign = 1;
|
||||
if (secp256k1_num_is_neg(&x)) {
|
||||
sign = -1;
|
||||
secp256k1_num_negate(&x);
|
||||
}
|
||||
while (!secp256k1_num_is_zero(&x)) {
|
||||
while (!secp256k1_num_is_odd(&x)) {
|
||||
zeroes++;
|
||||
secp256k1_num_shift(&x, 1);
|
||||
}
|
||||
int word = secp256k1_num_shift(&x, w);
|
||||
while (zeroes) {
|
||||
wnaf[ret++] = 0;
|
||||
zeroes--;
|
||||
}
|
||||
if (word & (1 << (w-1))) {
|
||||
secp256k1_num_inc(&x);
|
||||
wnaf[ret++] = sign * (word - (1 << w));
|
||||
} else {
|
||||
wnaf[ret++] = sign * word;
|
||||
}
|
||||
zeroes = w-1;
|
||||
}
|
||||
secp256k1_num_free(&x);
|
||||
return ret;
|
||||
}
|
||||
|
||||
void static secp256k1_ecmult_gen(secp256k1_gej_t *r, const secp256k1_num_t *gn) {
|
||||
secp256k1_num_t n;
|
||||
secp256k1_num_init(&n);
|
||||
secp256k1_num_copy(&n, gn);
|
||||
const secp256k1_ecmult_consts_t *c = secp256k1_ecmult_consts;
|
||||
secp256k1_gej_set_ge(r, &c->prec[0][secp256k1_num_shift(&n, 4)]);
|
||||
for (int j=1; j<64; j++)
|
||||
secp256k1_gej_add_ge(r, r, &c->prec[j][secp256k1_num_shift(&n, 4)]);
|
||||
secp256k1_num_free(&n);
|
||||
secp256k1_gej_add_ge(r, r, &c->fin);
|
||||
}
|
||||
|
||||
void static secp256k1_ecmult(secp256k1_gej_t *r, const secp256k1_gej_t *a, const secp256k1_num_t *na, const secp256k1_num_t *ng) {
|
||||
const secp256k1_ecmult_consts_t *c = secp256k1_ecmult_consts;
|
||||
|
||||
secp256k1_num_t na_1, na_lam;
|
||||
secp256k1_num_t ng_1, ng_128;
|
||||
secp256k1_num_init(&na_1);
|
||||
secp256k1_num_init(&na_lam);
|
||||
secp256k1_num_init(&ng_1);
|
||||
secp256k1_num_init(&ng_128);
|
||||
|
||||
// split na into na_1 and na_lam (where na = na_1 + na_lam*lambda, and na_1 and na_lam are ~128 bit)
|
||||
secp256k1_gej_split_exp(&na_1, &na_lam, na);
|
||||
// split ng into ng_1 and ng_128 (where gn = gn_1 + gn_128*2^128, and gn_1 and gn_128 are ~128 bit)
|
||||
secp256k1_num_split(&ng_1, &ng_128, ng, 128);
|
||||
|
||||
// build wnaf representation for na_1, na_lam, ng_1, ng_128
|
||||
int wnaf_na_1[129]; int bits_na_1 = secp256k1_ecmult_wnaf(wnaf_na_1, &na_1, WINDOW_A);
|
||||
int wnaf_na_lam[129]; int bits_na_lam = secp256k1_ecmult_wnaf(wnaf_na_lam, &na_lam, WINDOW_A);
|
||||
int wnaf_ng_1[129]; int bits_ng_1 = secp256k1_ecmult_wnaf(wnaf_ng_1, &ng_1, WINDOW_G);
|
||||
int wnaf_ng_128[129]; int bits_ng_128 = secp256k1_ecmult_wnaf(wnaf_ng_128, &ng_128, WINDOW_G);
|
||||
|
||||
// calculate a_lam = a*lambda
|
||||
secp256k1_gej_t a_lam; secp256k1_gej_mul_lambda(&a_lam, a);
|
||||
|
||||
// calculate odd multiples of a and a_lam
|
||||
secp256k1_gej_t pre_a_1[ECMULT_TABLE_SIZE(WINDOW_A)], pre_a_lam[ECMULT_TABLE_SIZE(WINDOW_A)];
|
||||
secp256k1_ecmult_table_precomp_gej(pre_a_1, a, WINDOW_A);
|
||||
secp256k1_ecmult_table_precomp_gej(pre_a_lam, &a_lam, WINDOW_A);
|
||||
|
||||
int bits = bits_na_1;
|
||||
if (bits_na_lam > bits) bits = bits_na_lam;
|
||||
if (bits_ng_1 > bits) bits = bits_ng_1;
|
||||
if (bits_ng_128 > bits) bits = bits_ng_128;
|
||||
|
||||
secp256k1_gej_set_infinity(r);
|
||||
secp256k1_gej_t tmpj;
|
||||
secp256k1_ge_t tmpa;
|
||||
|
||||
for (int i=bits-1; i>=0; i--) {
|
||||
secp256k1_gej_double(r, r);
|
||||
int n;
|
||||
if (i < bits_na_1 && (n = wnaf_na_1[i])) {
|
||||
ECMULT_TABLE_GET_GEJ(&tmpj, pre_a_1, n, WINDOW_A);
|
||||
secp256k1_gej_add(r, r, &tmpj);
|
||||
}
|
||||
if (i < bits_na_lam && (n = wnaf_na_lam[i])) {
|
||||
ECMULT_TABLE_GET_GEJ(&tmpj, pre_a_lam, n, WINDOW_A);
|
||||
secp256k1_gej_add(r, r, &tmpj);
|
||||
}
|
||||
if (i < bits_ng_1 && (n = wnaf_ng_1[i])) {
|
||||
ECMULT_TABLE_GET_GE(&tmpa, c->pre_g, n, WINDOW_G);
|
||||
secp256k1_gej_add_ge(r, r, &tmpa);
|
||||
}
|
||||
if (i < bits_ng_128 && (n = wnaf_ng_128[i])) {
|
||||
ECMULT_TABLE_GET_GE(&tmpa, c->pre_g_128, n, WINDOW_G);
|
||||
secp256k1_gej_add_ge(r, r, &tmpa);
|
||||
}
|
||||
}
|
||||
|
||||
secp256k1_num_free(&na_1);
|
||||
secp256k1_num_free(&na_lam);
|
||||
secp256k1_num_free(&ng_1);
|
||||
secp256k1_num_free(&ng_128);
|
||||
}
|
||||
|
||||
#endif
|
||||
|
|
@ -1,175 +0,0 @@
|
|||
// Copyright (c) 2013 Pieter Wuille
|
||||
// Distributed under the MIT/X11 software license, see the accompanying
|
||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||
|
||||
#ifndef _SECP256K1_FIELD_IMPL_H_
|
||||
#define _SECP256K1_FIELD_IMPL_H_
|
||||
|
||||
#if defined(USE_FIELD_GMP)
|
||||
#include "field_gmp.h"
|
||||
#elif defined(USE_FIELD_10X26)
|
||||
#include "field_10x26.h"
|
||||
#elif defined(USE_FIELD_5X52)
|
||||
#include "field_5x52.h"
|
||||
#elif defined(USE_FIELD_5X64)
|
||||
#include "field_5x64.h"
|
||||
#else
|
||||
#error "Please select field implementation"
|
||||
#endif
|
||||
|
||||
void static secp256k1_fe_get_hex(char *r, int *rlen, const secp256k1_fe_t *a) {
|
||||
if (*rlen < 65) {
|
||||
*rlen = 65;
|
||||
return;
|
||||
}
|
||||
*rlen = 65;
|
||||
unsigned char tmp[32];
|
||||
secp256k1_fe_t b = *a;
|
||||
secp256k1_fe_normalize(&b);
|
||||
secp256k1_fe_get_b32(tmp, &b);
|
||||
for (int i=0; i<32; i++) {
|
||||
static const char *c = "0123456789ABCDEF";
|
||||
r[2*i] = c[(tmp[i] >> 4) & 0xF];
|
||||
r[2*i+1] = c[(tmp[i]) & 0xF];
|
||||
}
|
||||
r[64] = 0x00;
|
||||
}
|
||||
|
||||
void static secp256k1_fe_set_hex(secp256k1_fe_t *r, const char *a, int alen) {
|
||||
unsigned char tmp[32] = {};
|
||||
static const int cvt[256] = {0, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0,
|
||||
0, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0,
|
||||
0, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0,
|
||||
0, 1, 2, 3, 4, 5, 6,7,8,9,0,0,0,0,0,0,
|
||||
0,10,11,12,13,14,15,0,0,0,0,0,0,0,0,0,
|
||||
0, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0,
|
||||
0,10,11,12,13,14,15,0,0,0,0,0,0,0,0,0,
|
||||
0, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0,
|
||||
0, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0,
|
||||
0, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0,
|
||||
0, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0,
|
||||
0, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0,
|
||||
0, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0,
|
||||
0, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0,
|
||||
0, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0,
|
||||
0, 0, 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0};
|
||||
for (int i=0; i<32; i++) {
|
||||
if (alen > i*2)
|
||||
tmp[32 - alen/2 + i] = (cvt[(unsigned char)a[2*i]] << 4) + cvt[(unsigned char)a[2*i+1]];
|
||||
}
|
||||
secp256k1_fe_set_b32(r, tmp);
|
||||
}
|
||||
|
||||
void static secp256k1_fe_sqrt(secp256k1_fe_t *r, const secp256k1_fe_t *a) {
|
||||
// calculate a^p, with p={15,780,1022,1023}
|
||||
secp256k1_fe_t a2; secp256k1_fe_sqr(&a2, a);
|
||||
secp256k1_fe_t a3; secp256k1_fe_mul(&a3, &a2, a);
|
||||
secp256k1_fe_t a6; secp256k1_fe_sqr(&a6, &a3);
|
||||
secp256k1_fe_t a12; secp256k1_fe_sqr(&a12, &a6);
|
||||
secp256k1_fe_t a15; secp256k1_fe_mul(&a15, &a12, &a3);
|
||||
secp256k1_fe_t a30; secp256k1_fe_sqr(&a30, &a15);
|
||||
secp256k1_fe_t a60; secp256k1_fe_sqr(&a60, &a30);
|
||||
secp256k1_fe_t a120; secp256k1_fe_sqr(&a120, &a60);
|
||||
secp256k1_fe_t a240; secp256k1_fe_sqr(&a240, &a120);
|
||||
secp256k1_fe_t a255; secp256k1_fe_mul(&a255, &a240, &a15);
|
||||
secp256k1_fe_t a510; secp256k1_fe_sqr(&a510, &a255);
|
||||
secp256k1_fe_t a750; secp256k1_fe_mul(&a750, &a510, &a240);
|
||||
secp256k1_fe_t a780; secp256k1_fe_mul(&a780, &a750, &a30);
|
||||
secp256k1_fe_t a1020; secp256k1_fe_sqr(&a1020, &a510);
|
||||
secp256k1_fe_t a1022; secp256k1_fe_mul(&a1022, &a1020, &a2);
|
||||
secp256k1_fe_t a1023; secp256k1_fe_mul(&a1023, &a1022, a);
|
||||
secp256k1_fe_t x = a15;
|
||||
for (int i=0; i<21; i++) {
|
||||
for (int j=0; j<10; j++) secp256k1_fe_sqr(&x, &x);
|
||||
secp256k1_fe_mul(&x, &x, &a1023);
|
||||
}
|
||||
for (int j=0; j<10; j++) secp256k1_fe_sqr(&x, &x);
|
||||
secp256k1_fe_mul(&x, &x, &a1022);
|
||||
for (int i=0; i<2; i++) {
|
||||
for (int j=0; j<10; j++) secp256k1_fe_sqr(&x, &x);
|
||||
secp256k1_fe_mul(&x, &x, &a1023);
|
||||
}
|
||||
for (int j=0; j<10; j++) secp256k1_fe_sqr(&x, &x);
|
||||
secp256k1_fe_mul(r, &x, &a780);
|
||||
}
|
||||
|
||||
void static secp256k1_fe_inv(secp256k1_fe_t *r, const secp256k1_fe_t *a) {
|
||||
// calculate a^p, with p={45,63,1019,1023}
|
||||
secp256k1_fe_t a2; secp256k1_fe_sqr(&a2, a);
|
||||
secp256k1_fe_t a3; secp256k1_fe_mul(&a3, &a2, a);
|
||||
secp256k1_fe_t a4; secp256k1_fe_sqr(&a4, &a2);
|
||||
secp256k1_fe_t a5; secp256k1_fe_mul(&a5, &a4, a);
|
||||
secp256k1_fe_t a10; secp256k1_fe_sqr(&a10, &a5);
|
||||
secp256k1_fe_t a11; secp256k1_fe_mul(&a11, &a10, a);
|
||||
secp256k1_fe_t a21; secp256k1_fe_mul(&a21, &a11, &a10);
|
||||
secp256k1_fe_t a42; secp256k1_fe_sqr(&a42, &a21);
|
||||
secp256k1_fe_t a45; secp256k1_fe_mul(&a45, &a42, &a3);
|
||||
secp256k1_fe_t a63; secp256k1_fe_mul(&a63, &a42, &a21);
|
||||
secp256k1_fe_t a126; secp256k1_fe_sqr(&a126, &a63);
|
||||
secp256k1_fe_t a252; secp256k1_fe_sqr(&a252, &a126);
|
||||
secp256k1_fe_t a504; secp256k1_fe_sqr(&a504, &a252);
|
||||
secp256k1_fe_t a1008; secp256k1_fe_sqr(&a1008, &a504);
|
||||
secp256k1_fe_t a1019; secp256k1_fe_mul(&a1019, &a1008, &a11);
|
||||
secp256k1_fe_t a1023; secp256k1_fe_mul(&a1023, &a1019, &a4);
|
||||
secp256k1_fe_t x = a63;
|
||||
for (int i=0; i<21; i++) {
|
||||
for (int j=0; j<10; j++) secp256k1_fe_sqr(&x, &x);
|
||||
secp256k1_fe_mul(&x, &x, &a1023);
|
||||
}
|
||||
for (int j=0; j<10; j++) secp256k1_fe_sqr(&x, &x);
|
||||
secp256k1_fe_mul(&x, &x, &a1019);
|
||||
for (int i=0; i<2; i++) {
|
||||
for (int j=0; j<10; j++) secp256k1_fe_sqr(&x, &x);
|
||||
secp256k1_fe_mul(&x, &x, &a1023);
|
||||
}
|
||||
for (int j=0; j<10; j++) secp256k1_fe_sqr(&x, &x);
|
||||
secp256k1_fe_mul(r, &x, &a45);
|
||||
}
|
||||
|
||||
void static secp256k1_fe_inv_var(secp256k1_fe_t *r, const secp256k1_fe_t *a) {
|
||||
#if defined(USE_FIELD_INV_BUILTIN)
|
||||
secp256k1_fe_inv(r, a);
|
||||
#elif defined(USE_FIELD_INV_NUM)
|
||||
unsigned char b[32];
|
||||
secp256k1_fe_t c = *a;
|
||||
secp256k1_fe_normalize(&c);
|
||||
secp256k1_fe_get_b32(b, &c);
|
||||
secp256k1_num_t n;
|
||||
secp256k1_num_init(&n);
|
||||
secp256k1_num_set_bin(&n, b, 32);
|
||||
secp256k1_num_mod_inverse(&n, &n, &secp256k1_fe_consts->p);
|
||||
secp256k1_num_get_bin(b, 32, &n);
|
||||
secp256k1_num_free(&n);
|
||||
secp256k1_fe_set_b32(r, b);
|
||||
#else
|
||||
#error "Please select field inverse implementation"
|
||||
#endif
|
||||
}
|
||||
|
||||
void static secp256k1_fe_start(void) {
|
||||
static const unsigned char secp256k1_fe_consts_p[] = {
|
||||
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
|
||||
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
|
||||
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
|
||||
0xFF,0xFF,0xFF,0xFE,0xFF,0xFF,0xFC,0x2F
|
||||
};
|
||||
if (secp256k1_fe_consts == NULL) {
|
||||
secp256k1_fe_inner_start();
|
||||
secp256k1_fe_consts_t *ret = (secp256k1_fe_consts_t*)malloc(sizeof(secp256k1_fe_consts_t));
|
||||
secp256k1_num_init(&ret->p);
|
||||
secp256k1_num_set_bin(&ret->p, secp256k1_fe_consts_p, sizeof(secp256k1_fe_consts_p));
|
||||
secp256k1_fe_consts = ret;
|
||||
}
|
||||
}
|
||||
|
||||
void static secp256k1_fe_stop(void) {
|
||||
if (secp256k1_fe_consts != NULL) {
|
||||
secp256k1_fe_consts_t *c = (secp256k1_fe_consts_t*)secp256k1_fe_consts;
|
||||
secp256k1_num_free(&c->p);
|
||||
free((void*)c);
|
||||
secp256k1_fe_consts = NULL;
|
||||
secp256k1_fe_inner_stop();
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
|
|
@ -1,487 +0,0 @@
|
|||
// Copyright (c) 2013 Pieter Wuille
|
||||
// Distributed under the MIT/X11 software license, see the accompanying
|
||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||
|
||||
#ifndef _SECP256K1_FIELD_REPR_IMPL_H_
|
||||
#define _SECP256K1_FIELD_REPR_IMPL_H_
|
||||
|
||||
#include <stdio.h>
|
||||
#include <assert.h>
|
||||
#include <string.h>
|
||||
#include "../num.h"
|
||||
#include "../field.h"
|
||||
|
||||
void static secp256k1_fe_inner_start(void) {}
|
||||
void static secp256k1_fe_inner_stop(void) {}
|
||||
|
||||
void static secp256k1_fe_normalize(secp256k1_fe_t *r) {
|
||||
// fog("normalize in: ", r);
|
||||
uint32_t c;
|
||||
c = r->n[0];
|
||||
uint32_t t0 = c & 0x3FFFFFFUL;
|
||||
c = (c >> 26) + r->n[1];
|
||||
uint32_t t1 = c & 0x3FFFFFFUL;
|
||||
c = (c >> 26) + r->n[2];
|
||||
uint32_t t2 = c & 0x3FFFFFFUL;
|
||||
c = (c >> 26) + r->n[3];
|
||||
uint32_t t3 = c & 0x3FFFFFFUL;
|
||||
c = (c >> 26) + r->n[4];
|
||||
uint32_t t4 = c & 0x3FFFFFFUL;
|
||||
c = (c >> 26) + r->n[5];
|
||||
uint32_t t5 = c & 0x3FFFFFFUL;
|
||||
c = (c >> 26) + r->n[6];
|
||||
uint32_t t6 = c & 0x3FFFFFFUL;
|
||||
c = (c >> 26) + r->n[7];
|
||||
uint32_t t7 = c & 0x3FFFFFFUL;
|
||||
c = (c >> 26) + r->n[8];
|
||||
uint32_t t8 = c & 0x3FFFFFFUL;
|
||||
c = (c >> 26) + r->n[9];
|
||||
uint32_t t9 = c & 0x03FFFFFUL;
|
||||
c >>= 22;
|
||||
/* r->n[0] = t0; r->n[1] = t1; r->n[2] = t2; r->n[3] = t3; r->n[4] = t4;
|
||||
r->n[5] = t5; r->n[6] = t6; r->n[7] = t7; r->n[8] = t8; r->n[9] = t9;
|
||||
fog(" tm1: ", r);
|
||||
fprintf(stderr, "out c= %08lx\n", (unsigned long)c);*/
|
||||
|
||||
// The following code will not modify the t's if c is initially 0.
|
||||
uint32_t d = c * 0x3D1UL + t0;
|
||||
t0 = d & 0x3FFFFFFULL;
|
||||
d = (d >> 26) + t1 + c*0x40;
|
||||
t1 = d & 0x3FFFFFFULL;
|
||||
d = (d >> 26) + t2;
|
||||
t2 = d & 0x3FFFFFFULL;
|
||||
d = (d >> 26) + t3;
|
||||
t3 = d & 0x3FFFFFFULL;
|
||||
d = (d >> 26) + t4;
|
||||
t4 = d & 0x3FFFFFFULL;
|
||||
d = (d >> 26) + t5;
|
||||
t5 = d & 0x3FFFFFFULL;
|
||||
d = (d >> 26) + t6;
|
||||
t6 = d & 0x3FFFFFFULL;
|
||||
d = (d >> 26) + t7;
|
||||
t7 = d & 0x3FFFFFFULL;
|
||||
d = (d >> 26) + t8;
|
||||
t8 = d & 0x3FFFFFFULL;
|
||||
d = (d >> 26) + t9;
|
||||
t9 = d & 0x03FFFFFULL;
|
||||
assert((d >> 22) == 0);
|
||||
/* r->n[0] = t0; r->n[1] = t1; r->n[2] = t2; r->n[3] = t3; r->n[4] = t4;
|
||||
r->n[5] = t5; r->n[6] = t6; r->n[7] = t7; r->n[8] = t8; r->n[9] = t9;
|
||||
fog(" tm2: ", r); */
|
||||
|
||||
// Subtract p if result >= p
|
||||
uint64_t low = ((uint64_t)t1 << 26) | t0;
|
||||
uint64_t mask = -(int64_t)((t9 < 0x03FFFFFUL) | (t8 < 0x3FFFFFFUL) | (t7 < 0x3FFFFFFUL) | (t6 < 0x3FFFFFFUL) | (t5 < 0x3FFFFFFUL) | (t4 < 0x3FFFFFFUL) | (t3 < 0x3FFFFFFUL) | (t2 < 0x3FFFFFFUL) | (low < 0xFFFFEFFFFFC2FULL));
|
||||
t9 &= mask;
|
||||
t8 &= mask;
|
||||
t7 &= mask;
|
||||
t6 &= mask;
|
||||
t5 &= mask;
|
||||
t4 &= mask;
|
||||
t3 &= mask;
|
||||
t2 &= mask;
|
||||
low -= (~mask & 0xFFFFEFFFFFC2FULL);
|
||||
|
||||
// push internal variables back
|
||||
r->n[0] = low & 0x3FFFFFFUL; r->n[1] = (low >> 26) & 0x3FFFFFFUL; r->n[2] = t2; r->n[3] = t3; r->n[4] = t4;
|
||||
r->n[5] = t5; r->n[6] = t6; r->n[7] = t7; r->n[8] = t8; r->n[9] = t9;
|
||||
/* fog(" out: ", r);*/
|
||||
|
||||
#ifdef VERIFY
|
||||
r->magnitude = 1;
|
||||
r->normalized = 1;
|
||||
#endif
|
||||
}
|
||||
|
||||
void static inline secp256k1_fe_set_int(secp256k1_fe_t *r, int a) {
|
||||
r->n[0] = a;
|
||||
r->n[1] = r->n[2] = r->n[3] = r->n[4] = r->n[5] = r->n[6] = r->n[7] = r->n[8] = r->n[9] = 0;
|
||||
#ifdef VERIFY
|
||||
r->magnitude = 1;
|
||||
r->normalized = 1;
|
||||
#endif
|
||||
}
|
||||
|
||||
// TODO: not constant time!
|
||||
int static inline secp256k1_fe_is_zero(const secp256k1_fe_t *a) {
|
||||
#ifdef VERIFY
|
||||
assert(a->normalized);
|
||||
#endif
|
||||
return (a->n[0] == 0 && a->n[1] == 0 && a->n[2] == 0 && a->n[3] == 0 && a->n[4] == 0 && a->n[5] == 0 && a->n[6] == 0 && a->n[7] == 0 && a->n[8] == 0 && a->n[9] == 0);
|
||||
}
|
||||
|
||||
int static inline secp256k1_fe_is_odd(const secp256k1_fe_t *a) {
|
||||
#ifdef VERIFY
|
||||
assert(a->normalized);
|
||||
#endif
|
||||
return a->n[0] & 1;
|
||||
}
|
||||
|
||||
// TODO: not constant time!
|
||||
int static inline secp256k1_fe_equal(const secp256k1_fe_t *a, const secp256k1_fe_t *b) {
|
||||
#ifdef VERIFY
|
||||
assert(a->normalized);
|
||||
assert(b->normalized);
|
||||
#endif
|
||||
return (a->n[0] == b->n[0] && a->n[1] == b->n[1] && a->n[2] == b->n[2] && a->n[3] == b->n[3] && a->n[4] == b->n[4] &&
|
||||
a->n[5] == b->n[5] && a->n[6] == b->n[6] && a->n[7] == b->n[7] && a->n[8] == b->n[8] && a->n[9] == b->n[9]);
|
||||
}
|
||||
|
||||
void static secp256k1_fe_set_b32(secp256k1_fe_t *r, const unsigned char *a) {
|
||||
r->n[0] = r->n[1] = r->n[2] = r->n[3] = r->n[4] = 0;
|
||||
r->n[5] = r->n[6] = r->n[7] = r->n[8] = r->n[9] = 0;
|
||||
for (int i=0; i<32; i++) {
|
||||
for (int j=0; j<4; j++) {
|
||||
int limb = (8*i+2*j)/26;
|
||||
int shift = (8*i+2*j)%26;
|
||||
r->n[limb] |= (uint32_t)((a[31-i] >> (2*j)) & 0x3) << shift;
|
||||
}
|
||||
}
|
||||
#ifdef VERIFY
|
||||
r->magnitude = 1;
|
||||
r->normalized = 1;
|
||||
#endif
|
||||
}
|
||||
|
||||
/** Convert a field element to a 32-byte big endian value. Requires the input to be normalized */
|
||||
void static secp256k1_fe_get_b32(unsigned char *r, const secp256k1_fe_t *a) {
|
||||
#ifdef VERIFY
|
||||
assert(a->normalized);
|
||||
#endif
|
||||
for (int i=0; i<32; i++) {
|
||||
int c = 0;
|
||||
for (int j=0; j<4; j++) {
|
||||
int limb = (8*i+2*j)/26;
|
||||
int shift = (8*i+2*j)%26;
|
||||
c |= ((a->n[limb] >> shift) & 0x3) << (2 * j);
|
||||
}
|
||||
r[31-i] = c;
|
||||
}
|
||||
}
|
||||
|
||||
void static inline secp256k1_fe_negate(secp256k1_fe_t *r, const secp256k1_fe_t *a, int m) {
|
||||
#ifdef VERIFY
|
||||
assert(a->magnitude <= m);
|
||||
r->magnitude = m + 1;
|
||||
r->normalized = 0;
|
||||
#endif
|
||||
r->n[0] = 0x3FFFC2FUL * (m + 1) - a->n[0];
|
||||
r->n[1] = 0x3FFFFBFUL * (m + 1) - a->n[1];
|
||||
r->n[2] = 0x3FFFFFFUL * (m + 1) - a->n[2];
|
||||
r->n[3] = 0x3FFFFFFUL * (m + 1) - a->n[3];
|
||||
r->n[4] = 0x3FFFFFFUL * (m + 1) - a->n[4];
|
||||
r->n[5] = 0x3FFFFFFUL * (m + 1) - a->n[5];
|
||||
r->n[6] = 0x3FFFFFFUL * (m + 1) - a->n[6];
|
||||
r->n[7] = 0x3FFFFFFUL * (m + 1) - a->n[7];
|
||||
r->n[8] = 0x3FFFFFFUL * (m + 1) - a->n[8];
|
||||
r->n[9] = 0x03FFFFFUL * (m + 1) - a->n[9];
|
||||
}
|
||||
|
||||
void static inline secp256k1_fe_mul_int(secp256k1_fe_t *r, int a) {
|
||||
#ifdef VERIFY
|
||||
r->magnitude *= a;
|
||||
r->normalized = 0;
|
||||
#endif
|
||||
r->n[0] *= a;
|
||||
r->n[1] *= a;
|
||||
r->n[2] *= a;
|
||||
r->n[3] *= a;
|
||||
r->n[4] *= a;
|
||||
r->n[5] *= a;
|
||||
r->n[6] *= a;
|
||||
r->n[7] *= a;
|
||||
r->n[8] *= a;
|
||||
r->n[9] *= a;
|
||||
}
|
||||
|
||||
void static inline secp256k1_fe_add(secp256k1_fe_t *r, const secp256k1_fe_t *a) {
|
||||
#ifdef VERIFY
|
||||
r->magnitude += a->magnitude;
|
||||
r->normalized = 0;
|
||||
#endif
|
||||
r->n[0] += a->n[0];
|
||||
r->n[1] += a->n[1];
|
||||
r->n[2] += a->n[2];
|
||||
r->n[3] += a->n[3];
|
||||
r->n[4] += a->n[4];
|
||||
r->n[5] += a->n[5];
|
||||
r->n[6] += a->n[6];
|
||||
r->n[7] += a->n[7];
|
||||
r->n[8] += a->n[8];
|
||||
r->n[9] += a->n[9];
|
||||
}
|
||||
|
||||
void static inline secp256k1_fe_mul_inner(const uint32_t *a, const uint32_t *b, uint32_t *r) {
|
||||
uint64_t c = (uint64_t)a[0] * b[0];
|
||||
uint32_t t0 = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + (uint64_t)a[0] * b[1] +
|
||||
(uint64_t)a[1] * b[0];
|
||||
uint32_t t1 = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + (uint64_t)a[0] * b[2] +
|
||||
(uint64_t)a[1] * b[1] +
|
||||
(uint64_t)a[2] * b[0];
|
||||
uint32_t t2 = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + (uint64_t)a[0] * b[3] +
|
||||
(uint64_t)a[1] * b[2] +
|
||||
(uint64_t)a[2] * b[1] +
|
||||
(uint64_t)a[3] * b[0];
|
||||
uint32_t t3 = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + (uint64_t)a[0] * b[4] +
|
||||
(uint64_t)a[1] * b[3] +
|
||||
(uint64_t)a[2] * b[2] +
|
||||
(uint64_t)a[3] * b[1] +
|
||||
(uint64_t)a[4] * b[0];
|
||||
uint32_t t4 = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + (uint64_t)a[0] * b[5] +
|
||||
(uint64_t)a[1] * b[4] +
|
||||
(uint64_t)a[2] * b[3] +
|
||||
(uint64_t)a[3] * b[2] +
|
||||
(uint64_t)a[4] * b[1] +
|
||||
(uint64_t)a[5] * b[0];
|
||||
uint32_t t5 = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + (uint64_t)a[0] * b[6] +
|
||||
(uint64_t)a[1] * b[5] +
|
||||
(uint64_t)a[2] * b[4] +
|
||||
(uint64_t)a[3] * b[3] +
|
||||
(uint64_t)a[4] * b[2] +
|
||||
(uint64_t)a[5] * b[1] +
|
||||
(uint64_t)a[6] * b[0];
|
||||
uint32_t t6 = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + (uint64_t)a[0] * b[7] +
|
||||
(uint64_t)a[1] * b[6] +
|
||||
(uint64_t)a[2] * b[5] +
|
||||
(uint64_t)a[3] * b[4] +
|
||||
(uint64_t)a[4] * b[3] +
|
||||
(uint64_t)a[5] * b[2] +
|
||||
(uint64_t)a[6] * b[1] +
|
||||
(uint64_t)a[7] * b[0];
|
||||
uint32_t t7 = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + (uint64_t)a[0] * b[8] +
|
||||
(uint64_t)a[1] * b[7] +
|
||||
(uint64_t)a[2] * b[6] +
|
||||
(uint64_t)a[3] * b[5] +
|
||||
(uint64_t)a[4] * b[4] +
|
||||
(uint64_t)a[5] * b[3] +
|
||||
(uint64_t)a[6] * b[2] +
|
||||
(uint64_t)a[7] * b[1] +
|
||||
(uint64_t)a[8] * b[0];
|
||||
uint32_t t8 = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + (uint64_t)a[0] * b[9] +
|
||||
(uint64_t)a[1] * b[8] +
|
||||
(uint64_t)a[2] * b[7] +
|
||||
(uint64_t)a[3] * b[6] +
|
||||
(uint64_t)a[4] * b[5] +
|
||||
(uint64_t)a[5] * b[4] +
|
||||
(uint64_t)a[6] * b[3] +
|
||||
(uint64_t)a[7] * b[2] +
|
||||
(uint64_t)a[8] * b[1] +
|
||||
(uint64_t)a[9] * b[0];
|
||||
uint32_t t9 = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + (uint64_t)a[1] * b[9] +
|
||||
(uint64_t)a[2] * b[8] +
|
||||
(uint64_t)a[3] * b[7] +
|
||||
(uint64_t)a[4] * b[6] +
|
||||
(uint64_t)a[5] * b[5] +
|
||||
(uint64_t)a[6] * b[4] +
|
||||
(uint64_t)a[7] * b[3] +
|
||||
(uint64_t)a[8] * b[2] +
|
||||
(uint64_t)a[9] * b[1];
|
||||
uint32_t t10 = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + (uint64_t)a[2] * b[9] +
|
||||
(uint64_t)a[3] * b[8] +
|
||||
(uint64_t)a[4] * b[7] +
|
||||
(uint64_t)a[5] * b[6] +
|
||||
(uint64_t)a[6] * b[5] +
|
||||
(uint64_t)a[7] * b[4] +
|
||||
(uint64_t)a[8] * b[3] +
|
||||
(uint64_t)a[9] * b[2];
|
||||
uint32_t t11 = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + (uint64_t)a[3] * b[9] +
|
||||
(uint64_t)a[4] * b[8] +
|
||||
(uint64_t)a[5] * b[7] +
|
||||
(uint64_t)a[6] * b[6] +
|
||||
(uint64_t)a[7] * b[5] +
|
||||
(uint64_t)a[8] * b[4] +
|
||||
(uint64_t)a[9] * b[3];
|
||||
uint32_t t12 = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + (uint64_t)a[4] * b[9] +
|
||||
(uint64_t)a[5] * b[8] +
|
||||
(uint64_t)a[6] * b[7] +
|
||||
(uint64_t)a[7] * b[6] +
|
||||
(uint64_t)a[8] * b[5] +
|
||||
(uint64_t)a[9] * b[4];
|
||||
uint32_t t13 = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + (uint64_t)a[5] * b[9] +
|
||||
(uint64_t)a[6] * b[8] +
|
||||
(uint64_t)a[7] * b[7] +
|
||||
(uint64_t)a[8] * b[6] +
|
||||
(uint64_t)a[9] * b[5];
|
||||
uint32_t t14 = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + (uint64_t)a[6] * b[9] +
|
||||
(uint64_t)a[7] * b[8] +
|
||||
(uint64_t)a[8] * b[7] +
|
||||
(uint64_t)a[9] * b[6];
|
||||
uint32_t t15 = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + (uint64_t)a[7] * b[9] +
|
||||
(uint64_t)a[8] * b[8] +
|
||||
(uint64_t)a[9] * b[7];
|
||||
uint32_t t16 = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + (uint64_t)a[8] * b[9] +
|
||||
(uint64_t)a[9] * b[8];
|
||||
uint32_t t17 = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + (uint64_t)a[9] * b[9];
|
||||
uint32_t t18 = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
uint32_t t19 = c;
|
||||
|
||||
c = t0 + (uint64_t)t10 * 0x3D10UL;
|
||||
t0 = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + t1 + (uint64_t)t10*0x400UL + (uint64_t)t11 * 0x3D10UL;
|
||||
t1 = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + t2 + (uint64_t)t11*0x400UL + (uint64_t)t12 * 0x3D10UL;
|
||||
t2 = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + t3 + (uint64_t)t12*0x400UL + (uint64_t)t13 * 0x3D10UL;
|
||||
r[3] = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + t4 + (uint64_t)t13*0x400UL + (uint64_t)t14 * 0x3D10UL;
|
||||
r[4] = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + t5 + (uint64_t)t14*0x400UL + (uint64_t)t15 * 0x3D10UL;
|
||||
r[5] = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + t6 + (uint64_t)t15*0x400UL + (uint64_t)t16 * 0x3D10UL;
|
||||
r[6] = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + t7 + (uint64_t)t16*0x400UL + (uint64_t)t17 * 0x3D10UL;
|
||||
r[7] = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + t8 + (uint64_t)t17*0x400UL + (uint64_t)t18 * 0x3D10UL;
|
||||
r[8] = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + t9 + (uint64_t)t18*0x400UL + (uint64_t)t19 * 0x1000003D10ULL;
|
||||
r[9] = c & 0x03FFFFFUL; c = c >> 22;
|
||||
uint64_t d = t0 + c * 0x3D1UL;
|
||||
r[0] = d & 0x3FFFFFFUL; d = d >> 26;
|
||||
d = d + t1 + c*0x40;
|
||||
r[1] = d & 0x3FFFFFFUL; d = d >> 26;
|
||||
r[2] = t2 + d;
|
||||
}
|
||||
|
||||
void static inline secp256k1_fe_sqr_inner(const uint32_t *a, uint32_t *r) {
|
||||
uint64_t c = (uint64_t)a[0] * a[0];
|
||||
uint32_t t0 = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + (uint64_t)(a[0]*2) * a[1];
|
||||
uint32_t t1 = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + (uint64_t)(a[0]*2) * a[2] +
|
||||
(uint64_t)a[1] * a[1];
|
||||
uint32_t t2 = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + (uint64_t)(a[0]*2) * a[3] +
|
||||
(uint64_t)(a[1]*2) * a[2];
|
||||
uint32_t t3 = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + (uint64_t)(a[0]*2) * a[4] +
|
||||
(uint64_t)(a[1]*2) * a[3] +
|
||||
(uint64_t)a[2] * a[2];
|
||||
uint32_t t4 = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + (uint64_t)(a[0]*2) * a[5] +
|
||||
(uint64_t)(a[1]*2) * a[4] +
|
||||
(uint64_t)(a[2]*2) * a[3];
|
||||
uint32_t t5 = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + (uint64_t)(a[0]*2) * a[6] +
|
||||
(uint64_t)(a[1]*2) * a[5] +
|
||||
(uint64_t)(a[2]*2) * a[4] +
|
||||
(uint64_t)a[3] * a[3];
|
||||
uint32_t t6 = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + (uint64_t)(a[0]*2) * a[7] +
|
||||
(uint64_t)(a[1]*2) * a[6] +
|
||||
(uint64_t)(a[2]*2) * a[5] +
|
||||
(uint64_t)(a[3]*2) * a[4];
|
||||
uint32_t t7 = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + (uint64_t)(a[0]*2) * a[8] +
|
||||
(uint64_t)(a[1]*2) * a[7] +
|
||||
(uint64_t)(a[2]*2) * a[6] +
|
||||
(uint64_t)(a[3]*2) * a[5] +
|
||||
(uint64_t)a[4] * a[4];
|
||||
uint32_t t8 = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + (uint64_t)(a[0]*2) * a[9] +
|
||||
(uint64_t)(a[1]*2) * a[8] +
|
||||
(uint64_t)(a[2]*2) * a[7] +
|
||||
(uint64_t)(a[3]*2) * a[6] +
|
||||
(uint64_t)(a[4]*2) * a[5];
|
||||
uint32_t t9 = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + (uint64_t)(a[1]*2) * a[9] +
|
||||
(uint64_t)(a[2]*2) * a[8] +
|
||||
(uint64_t)(a[3]*2) * a[7] +
|
||||
(uint64_t)(a[4]*2) * a[6] +
|
||||
(uint64_t)a[5] * a[5];
|
||||
uint32_t t10 = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + (uint64_t)(a[2]*2) * a[9] +
|
||||
(uint64_t)(a[3]*2) * a[8] +
|
||||
(uint64_t)(a[4]*2) * a[7] +
|
||||
(uint64_t)(a[5]*2) * a[6];
|
||||
uint32_t t11 = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + (uint64_t)(a[3]*2) * a[9] +
|
||||
(uint64_t)(a[4]*2) * a[8] +
|
||||
(uint64_t)(a[5]*2) * a[7] +
|
||||
(uint64_t)a[6] * a[6];
|
||||
uint32_t t12 = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + (uint64_t)(a[4]*2) * a[9] +
|
||||
(uint64_t)(a[5]*2) * a[8] +
|
||||
(uint64_t)(a[6]*2) * a[7];
|
||||
uint32_t t13 = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + (uint64_t)(a[5]*2) * a[9] +
|
||||
(uint64_t)(a[6]*2) * a[8] +
|
||||
(uint64_t)a[7] * a[7];
|
||||
uint32_t t14 = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + (uint64_t)(a[6]*2) * a[9] +
|
||||
(uint64_t)(a[7]*2) * a[8];
|
||||
uint32_t t15 = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + (uint64_t)(a[7]*2) * a[9] +
|
||||
(uint64_t)a[8] * a[8];
|
||||
uint32_t t16 = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + (uint64_t)(a[8]*2) * a[9];
|
||||
uint32_t t17 = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + (uint64_t)a[9] * a[9];
|
||||
uint32_t t18 = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
uint32_t t19 = c;
|
||||
|
||||
c = t0 + (uint64_t)t10 * 0x3D10UL;
|
||||
t0 = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + t1 + (uint64_t)t10*0x400UL + (uint64_t)t11 * 0x3D10UL;
|
||||
t1 = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + t2 + (uint64_t)t11*0x400UL + (uint64_t)t12 * 0x3D10UL;
|
||||
t2 = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + t3 + (uint64_t)t12*0x400UL + (uint64_t)t13 * 0x3D10UL;
|
||||
r[3] = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + t4 + (uint64_t)t13*0x400UL + (uint64_t)t14 * 0x3D10UL;
|
||||
r[4] = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + t5 + (uint64_t)t14*0x400UL + (uint64_t)t15 * 0x3D10UL;
|
||||
r[5] = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + t6 + (uint64_t)t15*0x400UL + (uint64_t)t16 * 0x3D10UL;
|
||||
r[6] = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + t7 + (uint64_t)t16*0x400UL + (uint64_t)t17 * 0x3D10UL;
|
||||
r[7] = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + t8 + (uint64_t)t17*0x400UL + (uint64_t)t18 * 0x3D10UL;
|
||||
r[8] = c & 0x3FFFFFFUL; c = c >> 26;
|
||||
c = c + t9 + (uint64_t)t18*0x400UL + (uint64_t)t19 * 0x1000003D10ULL;
|
||||
r[9] = c & 0x03FFFFFUL; c = c >> 22;
|
||||
uint64_t d = t0 + c * 0x3D1UL;
|
||||
r[0] = d & 0x3FFFFFFUL; d = d >> 26;
|
||||
d = d + t1 + c*0x40;
|
||||
r[1] = d & 0x3FFFFFFUL; d = d >> 26;
|
||||
r[2] = t2 + d;
|
||||
}
|
||||
|
||||
|
||||
void static secp256k1_fe_mul(secp256k1_fe_t *r, const secp256k1_fe_t *a, const secp256k1_fe_t *b) {
|
||||
#ifdef VERIFY
|
||||
assert(a->magnitude <= 8);
|
||||
assert(b->magnitude <= 8);
|
||||
r->magnitude = 1;
|
||||
r->normalized = 0;
|
||||
#endif
|
||||
secp256k1_fe_mul_inner(a->n, b->n, r->n);
|
||||
}
|
||||
|
||||
void static secp256k1_fe_sqr(secp256k1_fe_t *r, const secp256k1_fe_t *a) {
|
||||
#ifdef VERIFY
|
||||
assert(a->magnitude <= 8);
|
||||
r->magnitude = 1;
|
||||
r->normalized = 0;
|
||||
#endif
|
||||
secp256k1_fe_sqr_inner(a->n, r->n);
|
||||
}
|
||||
|
||||
#endif
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue