diff --git a/.project b/.project index 72e4b9760eb09bf1c1d2a57c35da9b7101061e42..bb2fb71390c0d0a76bd480c24ecdc133f4bc878d 100644 --- a/.project +++ b/.project @@ -7,6 +7,7 @@ <buildSpec> <buildCommand> <name>com.googlecode.goclipse.goBuilder</name> + <triggers>clean,full,incremental,</triggers> <arguments> </arguments> </buildCommand> diff --git a/DOCKER/Dockerfile b/DOCKER/Dockerfile index 1d4d05f27139085c8fc83d6ab6a45dbc85b155cf..192e214d11d702aaea263d58c2ef87cbf242778b 100644 --- a/DOCKER/Dockerfile +++ b/DOCKER/Dockerfile @@ -1,5 +1,5 @@ # Pull base image. -FROM eris/base +FROM quay.io/eris/base MAINTAINER Eris Industries <support@erisindustries.com> #----------------------------------------------------------------------------- @@ -13,12 +13,14 @@ RUN apt-get update && \ # install tendermint # set the repo and install tendermint -- should track vendored commit -ENV REPO github.com/tendermint/tendermint -ENV COMMIT 4ee387d0770ed379e2d524f7077938517b38cd7c +ENV REPO_ALIAS github.com/tendermint/tendermint +ENV REPO github.com/eris-ltd/tendermint +#ENV COMMIT 4ee387d0770ed379e2d524f7077938517b38cd7c +ENV COMMIT working # note, we want to lock in the same commit number # as eris-db has vendored. RUN mkdir --parents $GOPATH/src/$REPO -WORKDIR $GOPATH/src/$REPO +WORKDIR $GOPATH/src/$REPO_ALIAS RUN git clone --quiet https://$REPO . && \ git checkout --quiet $COMMIT && \ go build -o /usr/local/bin/tendermint ./cmd/tendermint @@ -38,7 +40,7 @@ RUN cd ./cmd/erisdb && go build -o /usr/local/bin/erisdb && \ # set the repo and install mint-client ENV REPO github.com/eris-ltd/mint-client -ENV BRANCH master +ENV BRANCH develop RUN mkdir --parents $GOPATH/src/$REPO WORKDIR $GOPATH/src/$REPO RUN git clone --quiet https://$REPO . && \ @@ -69,6 +71,10 @@ RUN mkdir -p $ECM_PATH COPY DOCKER/chain_* $ECM_PATH/ COPY DOCKER/config.toml $ECM_PATH/ COPY DOCKER/version.sh $ECM_PATH/ + +#----------------------------------------------------------------------------- +# permission the directories +RUN chown -R eris /usr/local/bin RUN chown -R eris $ECM_PATH #----------------------------------------------------------------------------- @@ -86,4 +92,4 @@ ENV TMROOT /home/$USER/.eris/blockchains/tendermint EXPOSE 1337 EXPOSE 46656 EXPOSE 46657 -ENTRYPOINT ["erisdb-wrapper"] +CMD "erisdb-wrapper" diff --git a/DOCKER/build.sh b/DOCKER/build.sh index f23e6c1d8c62837eb9bcb1a7bcb29644f191622b..2a810588b2fe8ebaea700224e7dac440d5f72d5b 100755 --- a/DOCKER/build.sh +++ b/DOCKER/build.sh @@ -1,26 +1,28 @@ #!/bin/sh -release_maj="0.10" -release_min="0.10.1" +if [ "$CIRCLE_BRANCH" ] +then + repo=`pwd` +else + base=github.com/eris-ltd/eris-db + repo=$GOPATH/src/$base +fi +branch=${CIRCLE_BRANCH:=master} + +release_min=$(cat $repo/version/version.go | tail -n 1 | cut -d \ -f 4 | tr -d '"') +release_maj=$(echo $release_min | cut -d . -f 1-2) start=`pwd` -branch=${ERISDB_BUILD_BRANCH:=master} -base=github.com/eris-ltd/eris-db -repo=$GOPATH/src/$base +image_base=quay.io/eris/erisdb cd $repo -# if [ "$DEV" != "true" ]; then -# git checkout $branch -# git pull origin -# fi - -if [ "$ERISDB_BUILD_BRANCH" = "master" ]; then - docker build -t eris/erisdb:latest -f DOCKER/Dockerfile . - docker tag -f eris/erisdb:latest eris/erisdb:$release_maj - docker tag -f eris/erisdb:latest eris/erisdb:$release_min +if [ "$branch" = "master" ]; then + docker build -t $image_base:latest -f DOCKER/Dockerfile . + docker tag -f $image_base:latest $image_base:$release_maj + docker tag -f $image_base:latest $image_base:$release_min else - docker build -t eris/erisdb:$branch -f DOCKER/Dockerfile . + docker build -t $image_base:$branch -f DOCKER/Dockerfile . fi -cd $start +cd $start \ No newline at end of file diff --git a/DOCKER/chain_api.sh b/DOCKER/chain_api.sh new file mode 100755 index 0000000000000000000000000000000000000000..8fecb978619334a8394d279d28d00e45e2ff48d1 --- /dev/null +++ b/DOCKER/chain_api.sh @@ -0,0 +1,4 @@ +#! /bin/bash + +echo "Running chain $CHAIN_ID (via ErisDB API)" +erisdb $TMROOT diff --git a/DOCKER/chain_install.sh b/DOCKER/chain_install.sh index e8d2279010a23d683afb9f97e7a683341e327c03..55aaabba22f39692a21bd9f5ddc0bef485b2fb7b 100755 --- a/DOCKER/chain_install.sh +++ b/DOCKER/chain_install.sh @@ -3,10 +3,12 @@ #----------------------------------------------------------------------- # get genesis, seed, copy config +export MINTX_NODE_ADDR=$NODE_ADDR + # get genesis if not already if [ ! -e "${CHAIN_DIR}/genesis.json" ]; then # etcb chain (given by $NODE_ADDR) - REFS_CHAIN_ID=$(mintinfo --node-addr $NODE_ADDR genesis chain_id) + REFS_CHAIN_ID=$(mintinfo genesis chain_id) ifExit "Error fetching default chain id from $NODE_ADDR" REFS_CHAIN_ID=$(echo "$REFS_CHAIN_ID" | tr -d '"') # remove surrounding quotes @@ -16,16 +18,16 @@ if [ ! -e "${CHAIN_DIR}/genesis.json" ]; then # for a different chain, use etcb (ie namereg on the ref chain) if [ "$CHAIN_ID" = "$REFS_CHAIN_ID" ] ; then # grab genesis.json - mintinfo --node-addr $NODE_ADDR genesis > "${CHAIN_DIR}/genesis.json" + mintinfo genesis > "${CHAIN_DIR}/genesis.json" ifExit "Error fetching genesis.json from $NODE_ADDR" else # fetch genesis from etcb - GENESIS=$(mintinfo --node-addr $NODE_ADDR names "${CHAIN_ID}_genesis.json" data) + GENESIS=$(mintinfo names "${CHAIN_ID}/genesis" data) ifExit "Error fetching genesis.json for $CHAIN_ID: $GENESIS" echo $GENESIS > "${CHAIN_DIR}/genesis.json" - SEED_NODE=$(mintinfo --node-addr $NODE_ADDR names "${CHAIN_ID}_seed" data) + SEED_NODE=$(mintinfo names "${CHAIN_ID}/seeds" data) ifExit "Error grabbing seed node from $NODE_ADDR for $CHAIN_ID" fi fi @@ -33,11 +35,11 @@ fi # copy in config if not already if [ ! -e "${CHAIN_DIR}/config.toml" ]; then echo "laying default config..." - cp $ECM_PATH/config.toml "${CHAIN_DIR}/config.toml" - ifExit "Error copying config file from $ECM_PATH to $CHAIN_DIR" + mintconfig > $CHAIN_DIR/config.toml + ifExit "Error creating config" if [ "$SEED_NODE" = "" ]; then - SEED_NODE=$NODE_HOST + SEED_NODE=$P2P_ADDR fi if [ "$HOST_NAME" = "" ]; then @@ -48,8 +50,8 @@ fi # set seed node and host name if [ "$SEED_NODE" != "" ]; then echo "Seed node: $SEED_NODE" - # NOTE the NODE_HOST must not have any slashes (no http://) - sed -i "s/^\(seeds\s*=\s*\).*\$/\1\"$NODE_HOST\"/" "${CHAIN_DIR}/config.toml" + # NOTE the NODE_ADDR must not have any slashes (no http://) + sed -i "s/^\(seeds\s*=\s*\).*\$/\1\"$SEED_NODE\"/" "${CHAIN_DIR}/config.toml" ifExit "Error setting seed node in config.toml" fi diff --git a/DOCKER/chain_new.sh b/DOCKER/chain_new.sh index 06bedab70500bda6596f4dabe0437f80af4d2c4b..a487564af5a7f44aee41d937e2946935a9d592a2 100755 --- a/DOCKER/chain_new.sh +++ b/DOCKER/chain_new.sh @@ -2,7 +2,9 @@ echo "your new chain, kind marmot: $CHAIN_ID" -if [ "$GENERATE_GENESIS" = "true" ]; then +# lay the genesis +# if it exists, just overwrite the chain id +if [ ! -f $CHAIN_DIR/genesis.json ]; then if [ "$CSV" = "" ]; then mintgen random --dir="$CHAIN_DIR" 1 $CHAIN_ID ifExit "Error creating random genesis file" @@ -26,11 +28,15 @@ else cat $CHAIN_DIR/config.toml fi -if [ "$RUN" = "true" ]; then - tendermint node - ifExit "Error starting tendermint" +# run the node. +# TODO: maybe bring back this stopping option if we think its useful +# tendermint node & last_pid=$! && sleep 1 && kill -KILL $last_pid +if [ $ERISDB_API ]; then + echo "Running chain $CHAIN_ID (via ErisDB API)" + erisdb $TMROOT + ifExit "Error starting erisdb" else - # this will just run for a second and quit - tendermint node & last_pid=$! && sleep 1 && kill -KILL $last_pid + echo Running chain $CHAIN_ID + tendermint node ifExit "Error starting tendermint" fi diff --git a/DOCKER/chain_register.sh b/DOCKER/chain_register.sh new file mode 100755 index 0000000000000000000000000000000000000000..d3c16b728d95128c3ea86798dde0c0cc49200d34 --- /dev/null +++ b/DOCKER/chain_register.sh @@ -0,0 +1,30 @@ +#! /bin/bash + +echo "registering $CHAIN_ID in the grand registry of marmot mayhem and marmalade" + +# lay the genesis +# if it exists, just overwrite the chain id +if [ ! -f $CHAIN_DIR/genesis.json ]; then + "Could not find genesis file in $CHAIN_DIR. Did you run `eris chains new $CHAIN_ID`?" + exit 1 +fi + + +echo "or less dramatically, registering $CHAIN_ID with the $ETCB_CHAIN_ID chain at $MINTX_NODE_ADDR from address $PUBKEY" + +echo "NAME ${CHAIN_ID}_genesis" +cat $CHAIN_DIR/genesis.json + +# register the genesis +RES=`mintx name --pubkey=$PUBKEY --name="${CHAIN_ID}/genesis" --data-file=$CHAIN_DIR/genesis.json --amt=10000 --fee=0 --sign --broadcast --chainID=$ETCB_CHAIN_ID --wait` +ifExit "$RES" "Error registering genesis with etcb_testnet" +echo $RES | grep "Incorrect" +if0Exit "$RES" "Error registering genesis with etcb_testnet" +echo $RES + +# register the seed/s +RES=`mintx name --pubkey=$PUBKEY --name="${CHAIN_ID}/seeds" --data="$NEW_P2P_SEEDS" --amt=10000 --fee=0 --sign --broadcast --chainID=$ETCB_CHAIN_ID --wait` +ifExit "$RES" "Error registering seeds with etcb_testnet" +echo $RES | grep "Incorrect" +if0Exit "$RES" "Error registering seeds with etcb_testnet" +echo $RES diff --git a/DOCKER/chain_run.sh b/DOCKER/chain_run.sh index 7734f65e6478117aa72d9bc91137a90fff9be196..6728d41c74ca619f410c1407ea7762018637cb67 100755 --- a/DOCKER/chain_run.sh +++ b/DOCKER/chain_run.sh @@ -1,4 +1,11 @@ #! /bin/bash -echo Running chain $CHAIN_ID -tendermint node +if [ $ERISDB_API ]; then + echo "Running chain $CHAIN_ID (via ErisDB API)" + erisdb $TMROOT + ifExit "Error starting erisdb" +else + echo Running chain $CHAIN_ID + tendermint node + ifExit "Error starting tendermint" +fi diff --git a/DOCKER/start.sh b/DOCKER/start.sh index f7c8d163638d2288b0a3b7c53dd0f47a801a3a32..a0867615855facd4da1ed994ac93dfee6dbaccf6 100755 --- a/DOCKER/start.sh +++ b/DOCKER/start.sh @@ -1,13 +1,32 @@ #! /bin/bash ifExit(){ - if [ $? -ne 0 ]; then - echo $1 + if [[ $? != 0 ]]; then + echo "ifExit" + echo "$1" + for var in "$@" + do + echo "$var" + done exit 1 fi } +if0Exit(){ + if [[ $? == 0 ]]; then + echo "if0Exit" + echo "$1" + for var in "$@" + do + echo "$var" + done + exit 1 + fi +} + + export -f ifExit +export -f if0Exit #------------------------------------------------ # set and export directories @@ -19,7 +38,7 @@ fi # TODO: deal with chain numbers # and eg. $CONTAINER_NAME -CHAIN_DIR="/home/$USER/.eris/blockchains/$CHAIN_ID" +CHAIN_DIR="/home/$USER/.eris/chains/$CHAIN_ID" # set the tendermint directory TMROOT=$CHAIN_DIR @@ -30,11 +49,14 @@ if [ ! -d "$CHAIN_DIR" ]; then fi # our root chain -if [ ! $NODE_HOST ]; then - NODE_HOST=interblock.io:46657 +if [ ! $ROOT_CHAIN_ID ]; then + ROOT_CHAIN_ID=etcb_testnet fi if [ ! $NODE_ADDR ]; then - NODE_ADDR=http://$NODE_HOST + NODE_ADDR=interblock.io:46657 +fi +if [ ! $P2P_ADDR ]; then + P2P_ADDR=interblock.io:46656 fi # where the etcb client scripts are @@ -91,9 +113,12 @@ fi export TMROOT export CHAIN_DIR export NODE_ADDR -export NODE_HOST +export P2P_ADDR export ECM_PATH # set by Dockerfile +export MINTX_NODE_ADDR=$NODE_ADDR +export MINTX_SIGN_ADDR=keys:4767 + # print the version bash $ECM_PATH/version.sh @@ -108,6 +133,8 @@ case $CMD in ;; "run" ) $ECM_PATH/chain_run.sh ;; -*) echo "Enter a command for starting the chain (install, new, run)" +"register" ) $ECM_PATH/chain_register.sh + ;; +*) echo "Enter a command for starting the chain (new, install, run, register)" ;; -esac +esac \ No newline at end of file diff --git a/DOCKER/version.sh b/DOCKER/version.sh index a375c1c1e5fbb26e6f593d0fd458edf26ce9a574..116023d3dd6ea58d898098a2d894fd9c15555f2d 100644 --- a/DOCKER/version.sh +++ b/DOCKER/version.sh @@ -1 +1,2 @@ -echo "ecm version 0.0.2" +# json break +echo "ecm version 0.0.3" diff --git a/Godeps/Godeps.json b/Godeps/Godeps.json index 6205a23e05b54e04837337dadeb77b48f34295cd..bc3b36227626ca79b76423fb31c76c39d4dcf223 100644 --- a/Godeps/Godeps.json +++ b/Godeps/Godeps.json @@ -1,6 +1,6 @@ { "ImportPath": "github.com/eris-ltd/eris-db", - "GoVersion": "go1.4.2", + "GoVersion": "go1.5.1", "Packages": [ "./..." ], @@ -24,10 +24,6 @@ "Comment": "v1.0rc1-104-g1a7ab6e", "Rev": "1a7ab6e4d5fdc72d6df30ef562102ae6e0d18518" }, - { - "ImportPath": "github.com/google/go-snappy/snappy", - "Rev": "eaa750b9bf4dcb7cb20454be850613b66cda3273" - }, { "ImportPath": "github.com/gorilla/websocket", "Rev": "a3ec486e6a7a41858210b0fc5d7b5df593b3c4a3" @@ -81,6 +77,10 @@ "ImportPath": "github.com/syndtr/goleveldb/leveldb", "Rev": "a06509502ca32565bdf74afc1e573050023f261c" }, + { + "ImportPath": "github.com/syndtr/gosnappy/snappy", + "Rev": "ce8acff4829e0c2458a67ead32390ac0a381c862" + }, { "ImportPath": "github.com/tendermint/ed25519", "Rev": "533fb6548e2071076888eda3c38749d707ba49bc" @@ -92,87 +92,98 @@ }, { "ImportPath": "github.com/tendermint/tendermint/account", - "Rev": "3d35594e18621bce075d18fc354ac2f1e5485464" + "Comment": "0.1-26-g85d5b16", + "Rev": "85d5b16dbc610a6a27f6c3d4ece0316907babec6" }, { "ImportPath": "github.com/tendermint/tendermint/alert", - "Rev": "3d35594e18621bce075d18fc354ac2f1e5485464" + "Comment": "0.1-26-g85d5b16", + "Rev": "85d5b16dbc610a6a27f6c3d4ece0316907babec6" }, { "ImportPath": "github.com/tendermint/tendermint/blockchain", - "Rev": "3d35594e18621bce075d18fc354ac2f1e5485464" + "Comment": "0.1-26-g85d5b16", + "Rev": "85d5b16dbc610a6a27f6c3d4ece0316907babec6" }, { "ImportPath": "github.com/tendermint/tendermint/common", - "Rev": "3d35594e18621bce075d18fc354ac2f1e5485464" + "Comment": "0.1-26-g85d5b16", + "Rev": "85d5b16dbc610a6a27f6c3d4ece0316907babec6" }, { "ImportPath": "github.com/tendermint/tendermint/config", - "Rev": "3d35594e18621bce075d18fc354ac2f1e5485464" + "Comment": "0.1-26-g85d5b16", + "Rev": "85d5b16dbc610a6a27f6c3d4ece0316907babec6" }, { "ImportPath": "github.com/tendermint/tendermint/consensus", - "Rev": "3d35594e18621bce075d18fc354ac2f1e5485464" + "Comment": "0.1-26-g85d5b16", + "Rev": "85d5b16dbc610a6a27f6c3d4ece0316907babec6" }, { "ImportPath": "github.com/tendermint/tendermint/db", - "Rev": "3d35594e18621bce075d18fc354ac2f1e5485464" + "Comment": "0.1-26-g85d5b16", + "Rev": "85d5b16dbc610a6a27f6c3d4ece0316907babec6" }, { "ImportPath": "github.com/tendermint/tendermint/events", - "Rev": "3d35594e18621bce075d18fc354ac2f1e5485464" + "Comment": "0.1-26-g85d5b16", + "Rev": "85d5b16dbc610a6a27f6c3d4ece0316907babec6" }, { "ImportPath": "github.com/tendermint/tendermint/logger", - "Rev": "3d35594e18621bce075d18fc354ac2f1e5485464" + "Comment": "0.1-26-g85d5b16", + "Rev": "85d5b16dbc610a6a27f6c3d4ece0316907babec6" }, { "ImportPath": "github.com/tendermint/tendermint/mempool", - "Rev": "3d35594e18621bce075d18fc354ac2f1e5485464" + "Comment": "0.1-26-g85d5b16", + "Rev": "85d5b16dbc610a6a27f6c3d4ece0316907babec6" }, { "ImportPath": "github.com/tendermint/tendermint/merkle", - "Rev": "3d35594e18621bce075d18fc354ac2f1e5485464" + "Comment": "0.1-26-g85d5b16", + "Rev": "85d5b16dbc610a6a27f6c3d4ece0316907babec6" }, { "ImportPath": "github.com/tendermint/tendermint/node", - "Rev": "3d35594e18621bce075d18fc354ac2f1e5485464" + "Comment": "0.1-26-g85d5b16", + "Rev": "85d5b16dbc610a6a27f6c3d4ece0316907babec6" }, { "ImportPath": "github.com/tendermint/tendermint/p2p", - "Rev": "3d35594e18621bce075d18fc354ac2f1e5485464" + "Comment": "0.1-26-g85d5b16", + "Rev": "85d5b16dbc610a6a27f6c3d4ece0316907babec6" }, { "ImportPath": "github.com/tendermint/tendermint/permission/types", - "Rev": "3d35594e18621bce075d18fc354ac2f1e5485464" - }, - { - "ImportPath": "github.com/tendermint/tendermint/rpc/core", - "Rev": "3d35594e18621bce075d18fc354ac2f1e5485464" - }, - { - "ImportPath": "github.com/tendermint/tendermint/rpc/server", - "Rev": "3d35594e18621bce075d18fc354ac2f1e5485464" + "Comment": "0.1-26-g85d5b16", + "Rev": "85d5b16dbc610a6a27f6c3d4ece0316907babec6" }, { - "ImportPath": "github.com/tendermint/tendermint/rpc/types", - "Rev": "3d35594e18621bce075d18fc354ac2f1e5485464" + "ImportPath": "github.com/tendermint/tendermint/rpc", + "Comment": "0.1-26-g85d5b16", + "Rev": "85d5b16dbc610a6a27f6c3d4ece0316907babec6" }, { "ImportPath": "github.com/tendermint/tendermint/state", - "Rev": "3d35594e18621bce075d18fc354ac2f1e5485464" + "Comment": "0.1-26-g85d5b16", + "Rev": "85d5b16dbc610a6a27f6c3d4ece0316907babec6" }, { "ImportPath": "github.com/tendermint/tendermint/types", - "Rev": "3d35594e18621bce075d18fc354ac2f1e5485464" + "Comment": "0.1-26-g85d5b16", + "Rev": "85d5b16dbc610a6a27f6c3d4ece0316907babec6" }, { "ImportPath": "github.com/tendermint/tendermint/vm", - "Rev": "3d35594e18621bce075d18fc354ac2f1e5485464" + "Comment": "0.1-26-g85d5b16", + "Rev": "85d5b16dbc610a6a27f6c3d4ece0316907babec6" }, { "ImportPath": "github.com/tendermint/tendermint/wire", - "Rev": "3d35594e18621bce075d18fc354ac2f1e5485464" + "Comment": "0.1-26-g85d5b16", + "Rev": "85d5b16dbc610a6a27f6c3d4ece0316907babec6" }, { "ImportPath": "github.com/tommy351/gin-cors", diff --git a/Godeps/_workspace/src/code.google.com/p/mxk/go1/flowcontrol/flowcontrol.go b/Godeps/_workspace/src/code.google.com/p/mxk/go1/flowcontrol/flowcontrol.go index 40db5d89ece5cfe9a478be8f4dbe2ba70a7119ca..c94735dbd439f11f593306e7f22725fd836c3b16 100644 --- a/Godeps/_workspace/src/code.google.com/p/mxk/go1/flowcontrol/flowcontrol.go +++ b/Godeps/_workspace/src/code.google.com/p/mxk/go1/flowcontrol/flowcontrol.go @@ -72,6 +72,14 @@ func (m *Monitor) Update(n int) int { return n } +// Hack to set the current rEMA. +func (m *Monitor) SetREMA(rEMA float64) { + m.mu.Lock() + m.rEMA = rEMA + m.samples++ + m.mu.Unlock() +} + // IO is a convenience method intended to wrap io.Reader and io.Writer method // execution. It calls m.Update(n) and then returns (n, err) unmodified. func (m *Monitor) IO(n int, err error) (int, error) { diff --git a/Godeps/_workspace/src/github.com/gin-gonic/gin/context.go b/Godeps/_workspace/src/github.com/gin-gonic/gin/context.go index a5e946ccc5655dc498b5866c0da8cc2fb1b34f49..0455c0db4ba18653acb86e97144098bb1c27266c 100644 --- a/Godeps/_workspace/src/github.com/gin-gonic/gin/context.go +++ b/Godeps/_workspace/src/github.com/gin-gonic/gin/context.go @@ -14,8 +14,8 @@ import ( "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/gin-gonic/gin/binding" "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/gin-gonic/gin/render" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/manucorporat/sse" "github.com/eris-ltd/eris-db/Godeps/_workspace/src/golang.org/x/net/context" + "github.com/manucorporat/sse" ) const ( diff --git a/Godeps/_workspace/src/github.com/gin-gonic/gin/context_test.go b/Godeps/_workspace/src/github.com/gin-gonic/gin/context_test.go index 9e9f3dda4b8ea983c96fd42c1b3ff4a302d07414..e31411e84c7e4fce0f800dcd50145c00f73ea40b 100644 --- a/Godeps/_workspace/src/github.com/gin-gonic/gin/context_test.go +++ b/Godeps/_workspace/src/github.com/gin-gonic/gin/context_test.go @@ -14,8 +14,8 @@ import ( "testing" "time" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/manucorporat/sse" "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/stretchr/testify/assert" + "github.com/manucorporat/sse" ) // Unit tests TODO diff --git a/Godeps/_workspace/src/github.com/gin-gonic/gin/middleware_test.go b/Godeps/_workspace/src/github.com/gin-gonic/gin/middleware_test.go index 8af80d333d5b88142131abf6673c550775adc7f6..61535de2101687579494bc04eb0cb0687a802611 100644 --- a/Godeps/_workspace/src/github.com/gin-gonic/gin/middleware_test.go +++ b/Godeps/_workspace/src/github.com/gin-gonic/gin/middleware_test.go @@ -9,8 +9,8 @@ import ( "testing" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/manucorporat/sse" "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/stretchr/testify/assert" + "github.com/manucorporat/sse" ) func TestMiddlewareGeneralCase(t *testing.T) { diff --git a/Godeps/_workspace/src/github.com/gin-gonic/gin/mode.go b/Godeps/_workspace/src/github.com/gin-gonic/gin/mode.go index 5dcf4e85a2385fdbf6c4f5f61af2485236b84b5b..f563ae8192bd8400f4f031cd668a7f0649d281d1 100644 --- a/Godeps/_workspace/src/github.com/gin-gonic/gin/mode.go +++ b/Godeps/_workspace/src/github.com/gin-gonic/gin/mode.go @@ -9,7 +9,7 @@ import ( "os" "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/gin-gonic/gin/binding" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/mattn/go-colorable" + "github.com/mattn/go-colorable" ) const ENV_GIN_MODE = "GIN_MODE" diff --git a/Godeps/_workspace/src/github.com/google/go-snappy/snappy/decode.go b/Godeps/_workspace/src/github.com/google/go-snappy/snappy/decode.go deleted file mode 100644 index 552a17bfb0500fe0617753c9ca7df0263ec363db..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/google/go-snappy/snappy/decode.go +++ /dev/null @@ -1,292 +0,0 @@ -// Copyright 2011 The Snappy-Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package snappy - -import ( - "encoding/binary" - "errors" - "io" -) - -var ( - // ErrCorrupt reports that the input is invalid. - ErrCorrupt = errors.New("snappy: corrupt input") - // ErrUnsupported reports that the input isn't supported. - ErrUnsupported = errors.New("snappy: unsupported input") -) - -// DecodedLen returns the length of the decoded block. -func DecodedLen(src []byte) (int, error) { - v, _, err := decodedLen(src) - return v, err -} - -// decodedLen returns the length of the decoded block and the number of bytes -// that the length header occupied. -func decodedLen(src []byte) (blockLen, headerLen int, err error) { - v, n := binary.Uvarint(src) - if n == 0 { - return 0, 0, ErrCorrupt - } - if uint64(int(v)) != v { - return 0, 0, errors.New("snappy: decoded block is too large") - } - return int(v), n, nil -} - -// Decode returns the decoded form of src. The returned slice may be a sub- -// slice of dst if dst was large enough to hold the entire decoded block. -// Otherwise, a newly allocated slice will be returned. -// It is valid to pass a nil dst. -func Decode(dst, src []byte) ([]byte, error) { - dLen, s, err := decodedLen(src) - if err != nil { - return nil, err - } - if len(dst) < dLen { - dst = make([]byte, dLen) - } - - var d, offset, length int - for s < len(src) { - switch src[s] & 0x03 { - case tagLiteral: - x := uint(src[s] >> 2) - switch { - case x < 60: - s += 1 - case x == 60: - s += 2 - if s > len(src) { - return nil, ErrCorrupt - } - x = uint(src[s-1]) - case x == 61: - s += 3 - if s > len(src) { - return nil, ErrCorrupt - } - x = uint(src[s-2]) | uint(src[s-1])<<8 - case x == 62: - s += 4 - if s > len(src) { - return nil, ErrCorrupt - } - x = uint(src[s-3]) | uint(src[s-2])<<8 | uint(src[s-1])<<16 - case x == 63: - s += 5 - if s > len(src) { - return nil, ErrCorrupt - } - x = uint(src[s-4]) | uint(src[s-3])<<8 | uint(src[s-2])<<16 | uint(src[s-1])<<24 - } - length = int(x + 1) - if length <= 0 { - return nil, errors.New("snappy: unsupported literal length") - } - if length > len(dst)-d || length > len(src)-s { - return nil, ErrCorrupt - } - copy(dst[d:], src[s:s+length]) - d += length - s += length - continue - - case tagCopy1: - s += 2 - if s > len(src) { - return nil, ErrCorrupt - } - length = 4 + int(src[s-2])>>2&0x7 - offset = int(src[s-2])&0xe0<<3 | int(src[s-1]) - - case tagCopy2: - s += 3 - if s > len(src) { - return nil, ErrCorrupt - } - length = 1 + int(src[s-3])>>2 - offset = int(src[s-2]) | int(src[s-1])<<8 - - case tagCopy4: - return nil, errors.New("snappy: unsupported COPY_4 tag") - } - - end := d + length - if offset > d || end > len(dst) { - return nil, ErrCorrupt - } - for ; d < end; d++ { - dst[d] = dst[d-offset] - } - } - if d != dLen { - return nil, ErrCorrupt - } - return dst[:d], nil -} - -// NewReader returns a new Reader that decompresses from r, using the framing -// format described at -// https://code.google.com/p/snappy/source/browse/trunk/framing_format.txt -func NewReader(r io.Reader) *Reader { - return &Reader{ - r: r, - decoded: make([]byte, maxUncompressedChunkLen), - buf: make([]byte, MaxEncodedLen(maxUncompressedChunkLen)+checksumSize), - } -} - -// Reader is an io.Reader than can read Snappy-compressed bytes. -type Reader struct { - r io.Reader - err error - decoded []byte - buf []byte - // decoded[i:j] contains decoded bytes that have not yet been passed on. - i, j int - readHeader bool -} - -// Reset discards any buffered data, resets all state, and switches the Snappy -// reader to read from r. This permits reusing a Reader rather than allocating -// a new one. -func (r *Reader) Reset(reader io.Reader) { - r.r = reader - r.err = nil - r.i = 0 - r.j = 0 - r.readHeader = false -} - -func (r *Reader) readFull(p []byte) (ok bool) { - if _, r.err = io.ReadFull(r.r, p); r.err != nil { - if r.err == io.ErrUnexpectedEOF { - r.err = ErrCorrupt - } - return false - } - return true -} - -// Read satisfies the io.Reader interface. -func (r *Reader) Read(p []byte) (int, error) { - if r.err != nil { - return 0, r.err - } - for { - if r.i < r.j { - n := copy(p, r.decoded[r.i:r.j]) - r.i += n - return n, nil - } - if !r.readFull(r.buf[:4]) { - return 0, r.err - } - chunkType := r.buf[0] - if !r.readHeader { - if chunkType != chunkTypeStreamIdentifier { - r.err = ErrCorrupt - return 0, r.err - } - r.readHeader = true - } - chunkLen := int(r.buf[1]) | int(r.buf[2])<<8 | int(r.buf[3])<<16 - if chunkLen > len(r.buf) { - r.err = ErrUnsupported - return 0, r.err - } - - // The chunk types are specified at - // https://code.google.com/p/snappy/source/browse/trunk/framing_format.txt - switch chunkType { - case chunkTypeCompressedData: - // Section 4.2. Compressed data (chunk type 0x00). - if chunkLen < checksumSize { - r.err = ErrCorrupt - return 0, r.err - } - buf := r.buf[:chunkLen] - if !r.readFull(buf) { - return 0, r.err - } - checksum := uint32(buf[0]) | uint32(buf[1])<<8 | uint32(buf[2])<<16 | uint32(buf[3])<<24 - buf = buf[checksumSize:] - - n, err := DecodedLen(buf) - if err != nil { - r.err = err - return 0, r.err - } - if n > len(r.decoded) { - r.err = ErrCorrupt - return 0, r.err - } - if _, err := Decode(r.decoded, buf); err != nil { - r.err = err - return 0, r.err - } - if crc(r.decoded[:n]) != checksum { - r.err = ErrCorrupt - return 0, r.err - } - r.i, r.j = 0, n - continue - - case chunkTypeUncompressedData: - // Section 4.3. Uncompressed data (chunk type 0x01). - if chunkLen < checksumSize { - r.err = ErrCorrupt - return 0, r.err - } - buf := r.buf[:checksumSize] - if !r.readFull(buf) { - return 0, r.err - } - checksum := uint32(buf[0]) | uint32(buf[1])<<8 | uint32(buf[2])<<16 | uint32(buf[3])<<24 - // Read directly into r.decoded instead of via r.buf. - n := chunkLen - checksumSize - if !r.readFull(r.decoded[:n]) { - return 0, r.err - } - if crc(r.decoded[:n]) != checksum { - r.err = ErrCorrupt - return 0, r.err - } - r.i, r.j = 0, n - continue - - case chunkTypeStreamIdentifier: - // Section 4.1. Stream identifier (chunk type 0xff). - if chunkLen != len(magicBody) { - r.err = ErrCorrupt - return 0, r.err - } - if !r.readFull(r.buf[:len(magicBody)]) { - return 0, r.err - } - for i := 0; i < len(magicBody); i++ { - if r.buf[i] != magicBody[i] { - r.err = ErrCorrupt - return 0, r.err - } - } - continue - } - - if chunkType <= 0x7f { - // Section 4.5. Reserved unskippable chunks (chunk types 0x02-0x7f). - r.err = ErrUnsupported - return 0, r.err - - } else { - // Section 4.4 Padding (chunk type 0xfe). - // Section 4.6. Reserved skippable chunks (chunk types 0x80-0xfd). - if !r.readFull(r.buf[:chunkLen]) { - return 0, r.err - } - } - } -} diff --git a/Godeps/_workspace/src/github.com/gorilla/websocket/examples/autobahn/server.go b/Godeps/_workspace/src/github.com/gorilla/websocket/examples/autobahn/server.go index b7eed0da47c4cddf21b7fd9d37fc1f6e6dce0218..d96ac84dbf282d639c2619f233e124cedcb7a0d0 100644 --- a/Godeps/_workspace/src/github.com/gorilla/websocket/examples/autobahn/server.go +++ b/Godeps/_workspace/src/github.com/gorilla/websocket/examples/autobahn/server.go @@ -8,7 +8,7 @@ package main import ( "errors" "flag" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/gorilla/websocket" + "github.com/gorilla/websocket" "io" "log" "net/http" diff --git a/Godeps/_workspace/src/github.com/gorilla/websocket/examples/chat/conn.go b/Godeps/_workspace/src/github.com/gorilla/websocket/examples/chat/conn.go index 00b4645a47bb9ea0790e2cebf7b3bcd766d720e4..7cc0496c3e05d930ce8e47b218b696af3cad33d4 100644 --- a/Godeps/_workspace/src/github.com/gorilla/websocket/examples/chat/conn.go +++ b/Godeps/_workspace/src/github.com/gorilla/websocket/examples/chat/conn.go @@ -5,7 +5,7 @@ package main import ( - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/gorilla/websocket" + "github.com/gorilla/websocket" "log" "net/http" "time" diff --git a/Godeps/_workspace/src/github.com/gorilla/websocket/examples/filewatch/main.go b/Godeps/_workspace/src/github.com/gorilla/websocket/examples/filewatch/main.go index 37d7433ebf93f58856211f2050caf3ade9059ded..a2c7b85fab38b96b19c9c6145b80f95cd5262dea 100644 --- a/Godeps/_workspace/src/github.com/gorilla/websocket/examples/filewatch/main.go +++ b/Godeps/_workspace/src/github.com/gorilla/websocket/examples/filewatch/main.go @@ -14,7 +14,7 @@ import ( "text/template" "time" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/gorilla/websocket" + "github.com/gorilla/websocket" ) const ( diff --git a/Godeps/_workspace/src/github.com/inconshreveable/log15/stack/stack_test.go b/Godeps/_workspace/src/github.com/inconshreveable/log15/stack/stack_test.go index 64cd7d08075a7c43b884ce6076545c30a0564990..52371b1e45ab1ac08469a56607133e18cc6716d5 100644 --- a/Godeps/_workspace/src/github.com/inconshreveable/log15/stack/stack_test.go +++ b/Godeps/_workspace/src/github.com/inconshreveable/log15/stack/stack_test.go @@ -9,7 +9,7 @@ import ( "runtime" "testing" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/inconshreveable/log15/stack" + "github.com/inconshreveable/log15/stack" ) type testType struct{} diff --git a/Godeps/_workspace/src/github.com/naoina/go-stringutil/strings_bench_test.go b/Godeps/_workspace/src/github.com/naoina/go-stringutil/strings_bench_test.go index 9e9dbc45133be54bae72d4c567d91b5624d9bc46..90c280bda102f6cf23c7370fdf43231d4c880eb6 100644 --- a/Godeps/_workspace/src/github.com/naoina/go-stringutil/strings_bench_test.go +++ b/Godeps/_workspace/src/github.com/naoina/go-stringutil/strings_bench_test.go @@ -3,7 +3,7 @@ package stringutil_test import ( "testing" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/naoina/go-stringutil" + "github.com/naoina/go-stringutil" ) var benchcaseForCamelCase = "the_quick_brown_fox_jumps_over_the_lazy_dog" diff --git a/Godeps/_workspace/src/github.com/naoina/go-stringutil/strings_test.go b/Godeps/_workspace/src/github.com/naoina/go-stringutil/strings_test.go index 89384c2c0b3c822d4868f1092507b1cc72c57862..69c831e1238ca7e1068090be1b121b96573b05a2 100644 --- a/Godeps/_workspace/src/github.com/naoina/go-stringutil/strings_test.go +++ b/Godeps/_workspace/src/github.com/naoina/go-stringutil/strings_test.go @@ -4,7 +4,7 @@ import ( "reflect" "testing" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/naoina/go-stringutil" + "github.com/naoina/go-stringutil" ) func TestToUpperCamelCase(t *testing.T) { diff --git a/Godeps/_workspace/src/github.com/naoina/toml/decode.go b/Godeps/_workspace/src/github.com/naoina/toml/decode.go index d9cb862404ae19d9d58a42d6401dbe2f6a32c22f..c5446fe922d5fbd2e3ca6816f6bcccd268a19e5a 100644 --- a/Godeps/_workspace/src/github.com/naoina/toml/decode.go +++ b/Godeps/_workspace/src/github.com/naoina/toml/decode.go @@ -8,7 +8,7 @@ import ( "strconv" "strings" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/naoina/toml/ast" + "github.com/naoina/toml/ast" ) const ( diff --git a/Godeps/_workspace/src/github.com/naoina/toml/decode_bench_test.go b/Godeps/_workspace/src/github.com/naoina/toml/decode_bench_test.go index 94ffdfb365ba1f69ecb48a0a9a098956abe5a2b0..b85c1c680ffc50bd35f9789434ac820140d6fb3d 100644 --- a/Godeps/_workspace/src/github.com/naoina/toml/decode_bench_test.go +++ b/Godeps/_workspace/src/github.com/naoina/toml/decode_bench_test.go @@ -4,7 +4,7 @@ import ( "testing" "time" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/naoina/toml" + "github.com/naoina/toml" ) func BenchmarkUnmarshal(b *testing.B) { diff --git a/Godeps/_workspace/src/github.com/naoina/toml/decode_test.go b/Godeps/_workspace/src/github.com/naoina/toml/decode_test.go index 17dd2e79b56155af3609167becb7975ffafe5b66..1fcae9b7abcd64a96572e7640fcd449536d415ad 100644 --- a/Godeps/_workspace/src/github.com/naoina/toml/decode_test.go +++ b/Godeps/_workspace/src/github.com/naoina/toml/decode_test.go @@ -8,7 +8,7 @@ import ( "testing" "time" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/naoina/toml" + "github.com/naoina/toml" ) const ( diff --git a/Godeps/_workspace/src/github.com/naoina/toml/encode.go b/Godeps/_workspace/src/github.com/naoina/toml/encode.go index 94302f44d04d6166a3ee5e6401ed16f84f24e5db..1932538e67b9e4f6c3db7b14e85a49a48517d09a 100644 --- a/Godeps/_workspace/src/github.com/naoina/toml/encode.go +++ b/Godeps/_workspace/src/github.com/naoina/toml/encode.go @@ -9,7 +9,7 @@ import ( "go/ast" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/naoina/go-stringutil" + "github.com/naoina/go-stringutil" ) const ( diff --git a/Godeps/_workspace/src/github.com/naoina/toml/encode_test.go b/Godeps/_workspace/src/github.com/naoina/toml/encode_test.go index 3445c879e5756aab000beca1931bdcf125daac35..17e04fd0a9d501d30e905db2f93333040f4c1c5e 100644 --- a/Godeps/_workspace/src/github.com/naoina/toml/encode_test.go +++ b/Godeps/_workspace/src/github.com/naoina/toml/encode_test.go @@ -5,7 +5,7 @@ import ( "testing" "time" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/naoina/toml" + "github.com/naoina/toml" ) func TestMarshal(t *testing.T) { diff --git a/Godeps/_workspace/src/github.com/naoina/toml/parse.go b/Godeps/_workspace/src/github.com/naoina/toml/parse.go index f7a3c83cdb47604ca716a0da17fd2e33b4b0ff0d..e0186662525a4ae11660a97a6c16b6c683132331 100644 --- a/Godeps/_workspace/src/github.com/naoina/toml/parse.go +++ b/Godeps/_workspace/src/github.com/naoina/toml/parse.go @@ -3,7 +3,7 @@ package toml import ( "fmt" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/naoina/toml/ast" + "github.com/naoina/toml/ast" ) // Parse returns an AST representation of TOML. diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/batch.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/batch.go index 354ebe4fee5f2bfd622b5ec8700f5de7cc45af56..ccf390c9cff4bd120180dd47b5b58e9a0c00b102 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/batch.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/batch.go @@ -10,8 +10,8 @@ import ( "encoding/binary" "fmt" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/errors" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/memdb" + "github.com/syndtr/goleveldb/leveldb/errors" + "github.com/syndtr/goleveldb/leveldb/memdb" ) type ErrBatchCorrupted struct { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/batch_test.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/batch_test.go index e98b683cde11ad97fa83134167be6b7f74eb6b13..7fc842f4fedd6f8dbd9902945d6098d4d556b6f4 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/batch_test.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/batch_test.go @@ -10,8 +10,8 @@ import ( "bytes" "testing" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/comparer" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/memdb" + "github.com/syndtr/goleveldb/leveldb/comparer" + "github.com/syndtr/goleveldb/leveldb/memdb" ) type tbRec struct { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/bench_test.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/bench_test.go index 621e52db283da81202a19a0f464ae3ab0b0a0fb4..91b426709d59a8fb0860cec31ba601f9daca3605 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/bench_test.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/bench_test.go @@ -15,9 +15,9 @@ import ( "runtime" "testing" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage" + "github.com/syndtr/goleveldb/leveldb/iterator" + "github.com/syndtr/goleveldb/leveldb/opt" + "github.com/syndtr/goleveldb/leveldb/storage" ) func randomString(r *rand.Rand, n int) []byte { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/cache/cache.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/cache/cache.go index 9ae499311026ce392b16b641577337f946754ef0..c9670de5de6f70f4ba905df39776f67a42ff32d1 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/cache/cache.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/cache/cache.go @@ -12,7 +12,7 @@ import ( "sync/atomic" "unsafe" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/util" ) // Cacher provides interface to implements a caching functionality. diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/comparer.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/comparer.go index 6e57fab707a08b08c1bd088dac3088c7bd6e48a9..d33d5e9c78fcf566114dce757ffe4ea6e0f0ba46 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/comparer.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/comparer.go @@ -6,7 +6,7 @@ package leveldb -import "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/comparer" +import "github.com/syndtr/goleveldb/leveldb/comparer" type iComparer struct { ucmp comparer.Comparer diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/corrupt_test.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/corrupt_test.go index f1ef0743e955f114cea9018d051e45d898787464..a351874ed4351f6d0abf67719bf7698d4228216a 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/corrupt_test.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/corrupt_test.go @@ -9,9 +9,9 @@ package leveldb import ( "bytes" "fmt" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/filter" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage" + "github.com/syndtr/goleveldb/leveldb/filter" + "github.com/syndtr/goleveldb/leveldb/opt" + "github.com/syndtr/goleveldb/leveldb/storage" "io" "math/rand" "testing" diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db.go index 365d311f6f0d408ff5da18ebf9dd0a803565dca3..def86bc1aa8240e30aba67c204f0e0c311a48b37 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db.go @@ -17,14 +17,14 @@ import ( "sync/atomic" "time" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/errors" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/journal" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/memdb" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/errors" + "github.com/syndtr/goleveldb/leveldb/iterator" + "github.com/syndtr/goleveldb/leveldb/journal" + "github.com/syndtr/goleveldb/leveldb/memdb" + "github.com/syndtr/goleveldb/leveldb/opt" + "github.com/syndtr/goleveldb/leveldb/storage" + "github.com/syndtr/goleveldb/leveldb/table" + "github.com/syndtr/goleveldb/leveldb/util" ) // DB is a LevelDB database. diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_compaction.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_compaction.go index 2c2f409322e134a286f0d01edb1e98b697e92837..26003106ead5ad7436db63da0f49dbfcd1c2cdf1 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_compaction.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_compaction.go @@ -10,8 +10,8 @@ import ( "sync" "time" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/errors" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt" + "github.com/syndtr/goleveldb/leveldb/errors" + "github.com/syndtr/goleveldb/leveldb/opt" ) var ( diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_iter.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_iter.go index 453db5b1d20190957631cc2898b96ae72df1f2df..656ae98567f38ecae293500a2649021ec9fd525f 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_iter.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_iter.go @@ -13,9 +13,9 @@ import ( "sync" "sync/atomic" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/iterator" + "github.com/syndtr/goleveldb/leveldb/opt" + "github.com/syndtr/goleveldb/leveldb/util" ) var ( diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_snapshot.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_snapshot.go index 4af7403317888b03177c989614003cff84009589..0372848ff1e4f62ececce67d9abe04d8e08121bd 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_snapshot.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_snapshot.go @@ -13,9 +13,9 @@ import ( "sync" "sync/atomic" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/iterator" + "github.com/syndtr/goleveldb/leveldb/opt" + "github.com/syndtr/goleveldb/leveldb/util" ) type snapshotElement struct { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_state.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_state.go index 87cd33adc6b81ff39e6e2eb7a7b9dcf9823e8d4e..24671dd39ede09ec35cc01a5f0e9bdec926a11bc 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_state.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_state.go @@ -10,8 +10,8 @@ import ( "sync/atomic" "time" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/journal" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/memdb" + "github.com/syndtr/goleveldb/leveldb/journal" + "github.com/syndtr/goleveldb/leveldb/memdb" ) type memDB struct { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_test.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_test.go index 108fdc00b3d6cd6b072b81135c76ce45329c6f21..9d91ebf1a80e78e399b745edeb8e61bbaa3bf0c8 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_test.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_test.go @@ -23,13 +23,13 @@ import ( "time" "unsafe" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/comparer" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/errors" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/filter" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/comparer" + "github.com/syndtr/goleveldb/leveldb/errors" + "github.com/syndtr/goleveldb/leveldb/filter" + "github.com/syndtr/goleveldb/leveldb/iterator" + "github.com/syndtr/goleveldb/leveldb/opt" + "github.com/syndtr/goleveldb/leveldb/storage" + "github.com/syndtr/goleveldb/leveldb/util" ) func tkey(i int) []byte { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_util.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_util.go index 0cd4a99ec78d217d0e84d14e5f1eafece9903ade..a8a2bdf72e173d592b4eba894a2996595cb1af12 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_util.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_util.go @@ -7,11 +7,11 @@ package leveldb import ( - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/errors" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/errors" + "github.com/syndtr/goleveldb/leveldb/iterator" + "github.com/syndtr/goleveldb/leveldb/opt" + "github.com/syndtr/goleveldb/leveldb/storage" + "github.com/syndtr/goleveldb/leveldb/util" ) // Reader is the interface that wraps basic Get and NewIterator methods. diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_write.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_write.go index 476ec3a8384aa6bc98390a5bb70b86256054d0f8..176ee893f10c6896ceb5e2cabaa2f38426c7c1c8 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_write.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/db_write.go @@ -9,9 +9,9 @@ package leveldb import ( "time" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/memdb" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/memdb" + "github.com/syndtr/goleveldb/leveldb/opt" + "github.com/syndtr/goleveldb/leveldb/util" ) func (db *DB) writeJournal(b *Batch) error { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/errors.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/errors.go index f45199d11d6f916f8d7a105c83a01c9a60735792..c8bd66a5aa9ab6aded8e4782358e4621c3e019e7 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/errors.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/errors.go @@ -7,7 +7,7 @@ package leveldb import ( - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/errors" + "github.com/syndtr/goleveldb/leveldb/errors" ) var ( diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/errors/errors.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/errors/errors.go index a22b4b9d5722df1336e8b14dffeb97d019140681..84b5d6b7b2149744c0098d7ca31b0669554be8ed 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/errors/errors.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/errors/errors.go @@ -11,8 +11,8 @@ import ( "errors" "fmt" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/storage" + "github.com/syndtr/goleveldb/leveldb/util" ) var ( diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/external_test.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/external_test.go index 8ae2e50e8ea41980e5a5e2a7c3e8fb147fe67a98..b328ece4e2caffe0b1004bed2047d3a3cb56eb4d 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/external_test.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/external_test.go @@ -10,8 +10,8 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil" + "github.com/syndtr/goleveldb/leveldb/opt" + "github.com/syndtr/goleveldb/leveldb/testutil" ) var _ = testutil.Defer(func() { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/filter.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/filter.go index fcad1fbf8474328d7b01dd20f33e357f40176b40..37c1e146bcc088a5f7dc7ba621d68f3a9c7c8509 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/filter.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/filter.go @@ -7,7 +7,7 @@ package leveldb import ( - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/filter" + "github.com/syndtr/goleveldb/leveldb/filter" ) type iFilter struct { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/filter/bloom.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/filter/bloom.go index 68c925522f4fa25ced117d2b78a4785b53dcb51c..bab0e99705f59201d6920633893012938dc8a592 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/filter/bloom.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/filter/bloom.go @@ -7,7 +7,7 @@ package filter import ( - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/util" ) func bloomHash(key []byte) uint32 { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/filter/bloom_test.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/filter/bloom_test.go index 70bfdaa54ea848419067098e7978a8f61cb9d94a..1fb56f07136f23a4314455852a242109587fbcd6 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/filter/bloom_test.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/filter/bloom_test.go @@ -8,7 +8,7 @@ package filter import ( "encoding/binary" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/util" "testing" ) diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/go13_bench_test.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/go13_bench_test.go new file mode 100644 index 0000000000000000000000000000000000000000..e76657e5ec3ec065e80fc4335cb5dffb92a98277 --- /dev/null +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/go13_bench_test.go @@ -0,0 +1,58 @@ +// Copyright (c) 2012, Suryandaru Triandana <syndtr@gmail.com> +// All rights reserved. +// +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// +build go1.3 + +package leveldb + +import ( + "sync/atomic" + "testing" +) + +func BenchmarkDBReadConcurrent(b *testing.B) { + p := openDBBench(b, false) + p.populate(b.N) + p.fill() + p.gc() + defer p.close() + + b.ResetTimer() + b.SetBytes(116) + + b.RunParallel(func(pb *testing.PB) { + iter := p.newIter() + defer iter.Release() + for pb.Next() && iter.Next() { + } + }) +} + +func BenchmarkDBReadConcurrent2(b *testing.B) { + p := openDBBench(b, false) + p.populate(b.N) + p.fill() + p.gc() + defer p.close() + + b.ResetTimer() + b.SetBytes(116) + + var dir uint32 + b.RunParallel(func(pb *testing.PB) { + iter := p.newIter() + defer iter.Release() + if atomic.AddUint32(&dir, 1)%2 == 0 { + for pb.Next() && iter.Next() { + } + } else { + if pb.Next() && iter.Last() { + for pb.Next() && iter.Prev() { + } + } + } + }) +} diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/array_iter.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/array_iter.go index 3050fb86ae651d0dbf9de64f39df378b122825ba..a23ab05f70fe8e45c0c0a8e0e4617884219a0cbf 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/array_iter.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/array_iter.go @@ -7,7 +7,7 @@ package iterator import ( - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/util" ) // BasicArray is the interface that wraps basic Len and Search method. diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/array_iter_test.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/array_iter_test.go index 9c9c27a686462b1afa5b2a2ffbacfba8292d7c14..1ed6d07cbb6e041e4e999112fa3ccf0ec1328c6b 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/array_iter_test.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/array_iter_test.go @@ -9,8 +9,8 @@ package iterator_test import ( . "github.com/onsi/ginkgo" - . "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil" + . "github.com/syndtr/goleveldb/leveldb/iterator" + "github.com/syndtr/goleveldb/leveldb/testutil" ) var _ = testutil.Defer(func() { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/indexed_iter.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/indexed_iter.go index 71843607f34ae43d607f25712c91feee5ff7d950..939adbb9332bcc2ce462303b9f95c9601fada105 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/indexed_iter.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/indexed_iter.go @@ -7,8 +7,8 @@ package iterator import ( - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/errors" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/errors" + "github.com/syndtr/goleveldb/leveldb/util" ) // IteratorIndexer is the interface that wraps CommonIterator and basic Get diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/indexed_iter_test.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/indexed_iter_test.go index 8d64ed8b4ad803a45f777107ebd51f695f5c692e..72a7978924ebf0aaa52eefd16ef79ac57a40f086 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/indexed_iter_test.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/indexed_iter_test.go @@ -11,9 +11,9 @@ import ( . "github.com/onsi/ginkgo" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/comparer" - . "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil" + "github.com/syndtr/goleveldb/leveldb/comparer" + . "github.com/syndtr/goleveldb/leveldb/iterator" + "github.com/syndtr/goleveldb/leveldb/testutil" ) type keyValue struct { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/iter.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/iter.go index f6876eea87fbfd824c77831de93b911c06084f21..c2522860b0b8c0477fec8d54068053e22de6a1d4 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/iter.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/iter.go @@ -11,7 +11,7 @@ package iterator import ( "errors" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/util" ) var ( diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/iter_suite_test.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/iter_suite_test.go index 3e54f8b1977d9e29bf744acc78d28163231e77a5..5ef8d5bafb3f265754c74562d987ed2858bb174f 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/iter_suite_test.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/iter_suite_test.go @@ -3,7 +3,7 @@ package iterator_test import ( "testing" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil" + "github.com/syndtr/goleveldb/leveldb/testutil" ) func TestIterator(t *testing.T) { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/merged_iter.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/merged_iter.go index df1daffa352f21c63c16e6c6a2429f90be74ec88..1a7e29df8fbd975902e5042031cd777b9a9764ce 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/merged_iter.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/merged_iter.go @@ -7,9 +7,9 @@ package iterator import ( - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/comparer" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/errors" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/comparer" + "github.com/syndtr/goleveldb/leveldb/errors" + "github.com/syndtr/goleveldb/leveldb/util" ) type dir int diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/merged_iter_test.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/merged_iter_test.go index 8ef775f31657728ff39962dfda0f6fe890d130da..e523b63e4b6694cf6e0a016b06830aefdf8e8831 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/merged_iter_test.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator/merged_iter_test.go @@ -10,9 +10,9 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/comparer" - . "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil" + "github.com/syndtr/goleveldb/leveldb/comparer" + . "github.com/syndtr/goleveldb/leveldb/iterator" + "github.com/syndtr/goleveldb/leveldb/testutil" ) var _ = testutil.Defer(func() { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/journal/journal.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/journal/journal.go index 4e4aae982c72c8148dd3253050e6c02bc7f8c636..6519ec660eb7110425d545d6e7154c0a447a869f 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/journal/journal.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/journal/journal.go @@ -82,8 +82,8 @@ import ( "fmt" "io" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/errors" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/errors" + "github.com/syndtr/goleveldb/leveldb/util" ) // These constants are part of the wire format and should not be changed. diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/key.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/key.go index eeff53321e810198c67d6920ea6c437bd22eab99..572ae8150c792dd43a3cc0477d1ff44075a51db3 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/key.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/key.go @@ -10,7 +10,7 @@ import ( "encoding/binary" "fmt" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/errors" + "github.com/syndtr/goleveldb/leveldb/errors" ) type ErrIkeyCorrupted struct { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/key_test.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/key_test.go index eb9526f751f320238b90945a2dd4e8db359247cb..30eadf7847ed9b35495c2ee56f800de9fff79b84 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/key_test.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/key_test.go @@ -10,7 +10,7 @@ import ( "bytes" "testing" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/comparer" + "github.com/syndtr/goleveldb/leveldb/comparer" ) var defaultIComparer = &iComparer{comparer.DefaultComparer} diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/leveldb_suite_test.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/leveldb_suite_test.go index 33be15d6b59ec77c8b2ff71f8e9bf146c9b106fa..fefa007a7047c7c0f5dcf69769db92d74702a087 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/leveldb_suite_test.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/leveldb_suite_test.go @@ -3,7 +3,7 @@ package leveldb import ( "testing" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil" + "github.com/syndtr/goleveldb/leveldb/testutil" ) func TestLevelDB(t *testing.T) { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/memdb/bench_test.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/memdb/bench_test.go index 51ca66ba7d1b1125136ff074d13f2b314f0d78a1..b05084caa65eb0a607b796d8819dcd0656acdf3f 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/memdb/bench_test.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/memdb/bench_test.go @@ -11,7 +11,7 @@ import ( "math/rand" "testing" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/comparer" + "github.com/syndtr/goleveldb/leveldb/comparer" ) func BenchmarkPut(b *testing.B) { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/memdb/memdb.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/memdb/memdb.go index c90c3561d25aa7dc789351348fbf6041cfaf75d8..1395bd928080f5514643e2c7d24a53d57025c702 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/memdb/memdb.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/memdb/memdb.go @@ -11,10 +11,10 @@ import ( "math/rand" "sync" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/comparer" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/errors" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/comparer" + "github.com/syndtr/goleveldb/leveldb/errors" + "github.com/syndtr/goleveldb/leveldb/iterator" + "github.com/syndtr/goleveldb/leveldb/util" ) var ( diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/memdb/memdb_suite_test.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/memdb/memdb_suite_test.go index 7be1214f39d1186edb10e096581599af7b08f5b7..18c304b7f19a6c66b008e7fe2f6d879cf0a0a6ad 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/memdb/memdb_suite_test.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/memdb/memdb_suite_test.go @@ -3,7 +3,7 @@ package memdb import ( "testing" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil" + "github.com/syndtr/goleveldb/leveldb/testutil" ) func TestMemDB(t *testing.T) { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/memdb/memdb_test.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/memdb/memdb_test.go index 131333c16a033197f9ba0da6b7fdcd6a6bbbf39f..5dd6dbc7b7bbdb1d3e252c3cc1bb1995eb99ae4a 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/memdb/memdb_test.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/memdb/memdb_test.go @@ -10,10 +10,10 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/comparer" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/comparer" + "github.com/syndtr/goleveldb/leveldb/iterator" + "github.com/syndtr/goleveldb/leveldb/testutil" + "github.com/syndtr/goleveldb/leveldb/util" ) func (p *DB) TestFindLT(key []byte) (rkey, value []byte, err error) { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt/options.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt/options.go index 09cf9b6cffedfe9ef4f2efaaddcdce462c5fd37f..f9a309dac6f499fffaee3138179b1c0b46bd2912 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt/options.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt/options.go @@ -8,9 +8,9 @@ package opt import ( - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/cache" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/comparer" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/filter" + "github.com/syndtr/goleveldb/leveldb/cache" + "github.com/syndtr/goleveldb/leveldb/comparer" + "github.com/syndtr/goleveldb/leveldb/filter" "math" ) diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/options.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/options.go index a13abb675a960c430b5acb5084812c3794922d9e..a3d84ef60d53d4afb73ba7bdf1f848ebbb202808 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/options.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/options.go @@ -7,8 +7,8 @@ package leveldb import ( - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/filter" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt" + "github.com/syndtr/goleveldb/leveldb/filter" + "github.com/syndtr/goleveldb/leveldb/opt" ) func dupOptions(o *opt.Options) *opt.Options { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/session.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/session.go index cb07209eb0544b2c02d6af299c8dbd0886bb46ff..f0bba4602ca528493576243aaef1da156556cb58 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/session.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/session.go @@ -12,11 +12,11 @@ import ( "os" "sync" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/errors" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/journal" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/errors" + "github.com/syndtr/goleveldb/leveldb/journal" + "github.com/syndtr/goleveldb/leveldb/opt" + "github.com/syndtr/goleveldb/leveldb/storage" + "github.com/syndtr/goleveldb/leveldb/util" ) type ErrManifestCorrupted struct { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/session_compaction.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/session_compaction.go index 0c785f4d31ee454f618163a137413874682a07bf..7c5a79418cc4bb2a3bf70ba7314c4804e04349f9 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/session_compaction.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/session_compaction.go @@ -9,9 +9,9 @@ package leveldb import ( "sync/atomic" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/memdb" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt" + "github.com/syndtr/goleveldb/leveldb/iterator" + "github.com/syndtr/goleveldb/leveldb/memdb" + "github.com/syndtr/goleveldb/leveldb/opt" ) func (s *session) pickMemdbLevel(umin, umax []byte) int { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/session_record.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/session_record.go index b774bafac504552d75253d0943739e7e8229ef42..405e07bef4f1f7b881044a7e449d96b99c4bd68e 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/session_record.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/session_record.go @@ -12,7 +12,7 @@ import ( "io" "strings" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/errors" + "github.com/syndtr/goleveldb/leveldb/errors" ) type byteReader interface { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/session_record_test.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/session_record_test.go index 7a18cf448a7524a4d891bec7dccb150b48f70c06..33c14875618b53cd0408e77f4819c47adf9a1994 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/session_record_test.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/session_record_test.go @@ -10,7 +10,7 @@ import ( "bytes" "testing" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt" + "github.com/syndtr/goleveldb/leveldb/opt" ) func decodeEncode(v *sessionRecord) (res bool, err error) { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/session_util.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/session_util.go index 740f3447e21286a394507a1c3fbf53df1d8022f6..399a788bad2de7b07974e09f14e400f99e484d06 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/session_util.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/session_util.go @@ -10,8 +10,8 @@ import ( "fmt" "sync/atomic" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/journal" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage" + "github.com/syndtr/goleveldb/leveldb/journal" + "github.com/syndtr/goleveldb/leveldb/storage" ) // Logging. diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage/file_storage.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage/file_storage.go index 9329faf7a7676b75572f4ef612e6d7e320272858..46cc9d07012e91141cae7c08903f8421c394c412 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage/file_storage.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage/file_storage.go @@ -18,7 +18,7 @@ import ( "sync" "time" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/util" ) var errFileOpen = errors.New("leveldb/storage: file still open") diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage/mem_storage.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage/mem_storage.go index 8952193112728a24485df4d5cfca73ebae92ca6d..fc1c8165df1a0d05d432e47889fe8ccb0b943c7f 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage/mem_storage.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage/mem_storage.go @@ -11,7 +11,7 @@ import ( "os" "sync" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/util" ) const typeShift = 3 diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage/storage.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage/storage.go index bdda8c447e241d497b6dfc41fa6812b26ae157e2..85dd70b06f9f6c8955d60b382d4a8652b1ba1292 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage/storage.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage/storage.go @@ -12,7 +12,7 @@ import ( "fmt" "io" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/util" ) type FileType uint32 diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage_test.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage_test.go index a068113fd81ffef9cd6177a8468253f2bd3f9810..08be0bab3da3b28e9c889c50ef813f6c0603d29b 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage_test.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage_test.go @@ -17,8 +17,8 @@ import ( "sync" "testing" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/storage" + "github.com/syndtr/goleveldb/leveldb/util" ) const typeShift = 4 diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table.go index 57fce1314b202eea9e06bcc473c385ad3aa2489d..db386f3b5465b68faff4b7f709482bdfdb830b6f 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table.go @@ -11,12 +11,12 @@ import ( "sort" "sync/atomic" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/cache" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/cache" + "github.com/syndtr/goleveldb/leveldb/iterator" + "github.com/syndtr/goleveldb/leveldb/opt" + "github.com/syndtr/goleveldb/leveldb/storage" + "github.com/syndtr/goleveldb/leveldb/table" + "github.com/syndtr/goleveldb/leveldb/util" ) // tFile holds basic information about a table. diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table/block_test.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table/block_test.go index a8580cf324784e3d1122680de1e26477db26a4f2..00e6f9eea0dd97ae892eab1934d4f096f73a1b65 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table/block_test.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table/block_test.go @@ -13,10 +13,10 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/comparer" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/comparer" + "github.com/syndtr/goleveldb/leveldb/iterator" + "github.com/syndtr/goleveldb/leveldb/testutil" + "github.com/syndtr/goleveldb/leveldb/util" ) type blockTesting struct { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table/reader.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table/reader.go index 0ed58fb51be12eec4c780a98f1fa84510590b417..691ffc2aa8118f7e5c864853d34580ddbbf9b9aa 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table/reader.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table/reader.go @@ -14,16 +14,16 @@ import ( "strings" "sync" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/google/go-snappy/snappy" - - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/cache" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/comparer" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/errors" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/filter" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.comgoogle/go-snappy/snappy" + + "github.com/syndtr/goleveldb/leveldb/cache" + "github.com/syndtr/goleveldb/leveldb/comparer" + "github.com/syndtr/goleveldb/leveldb/errors" + "github.com/syndtr/goleveldb/leveldb/filter" + "github.com/syndtr/goleveldb/leveldb/iterator" + "github.com/syndtr/goleveldb/leveldb/opt" + "github.com/syndtr/goleveldb/leveldb/storage" + "github.com/syndtr/goleveldb/leveldb/util" ) var ( diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table/table_suite_test.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table/table_suite_test.go index d35a13051497c79133aa293560897c9b63276e67..6465da6e3707c48ab28ebc176c33b80b66c0c8b3 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table/table_suite_test.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table/table_suite_test.go @@ -3,7 +3,7 @@ package table import ( "testing" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil" + "github.com/syndtr/goleveldb/leveldb/testutil" ) func TestTable(t *testing.T) { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table/table_test.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table/table_test.go index 5429c465b6938b75d1f7e39662b66f1d4a507797..4b59b31f52b42f12e8e098ea3a20d3b10d6b334e 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table/table_test.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table/table_test.go @@ -12,10 +12,10 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/iterator" + "github.com/syndtr/goleveldb/leveldb/opt" + "github.com/syndtr/goleveldb/leveldb/testutil" + "github.com/syndtr/goleveldb/leveldb/util" ) type tableWrapper struct { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table/writer.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table/writer.go index f656f42199b1916facf2016f28df7c0f12df9e13..42285b5f29e98be0f40528bae2625e26d8fe1648 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table/writer.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/table/writer.go @@ -12,12 +12,12 @@ import ( "fmt" "io" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/google/go-snappy/snappy" + "github.comgoogle/go-snappy/snappy" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/comparer" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/filter" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/comparer" + "github.com/syndtr/goleveldb/leveldb/filter" + "github.com/syndtr/goleveldb/leveldb/opt" + "github.com/syndtr/goleveldb/leveldb/util" ) func sharedPrefixLen(a, b []byte) int { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil/db.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil/db.go index a0995a4b7b7c83efb955bb97f46b319b35b69d3b..ec3f177a12febb5259fb9d88a5b8b58e7d37dca7 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil/db.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil/db.go @@ -12,9 +12,9 @@ import ( . "github.com/onsi/gomega" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/errors" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/errors" + "github.com/syndtr/goleveldb/leveldb/iterator" + "github.com/syndtr/goleveldb/leveldb/util" ) type DB interface{} diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil/iter.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil/iter.go index 5e3cbb160d543800a09960a01c63b1c60e6ed4fd..df6d9db6a335bf388ba844ee0af918707e9caf34 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil/iter.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil/iter.go @@ -12,7 +12,7 @@ import ( . "github.com/onsi/gomega" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator" + "github.com/syndtr/goleveldb/leveldb/iterator" ) type IterAct int diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil/kv.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil/kv.go index 83a01a4719b84ab5da4aa0e23258fa9e057089bb..471d5708c37d826d7c5e75139f209c816b13f7c5 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil/kv.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil/kv.go @@ -12,7 +12,7 @@ import ( "sort" "strings" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/util" ) type KeyValueEntry struct { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil/kvtest.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil/kvtest.go index 78d981c7dcd38fc198fa4c70fd3b46a9c134d83a..a0b58f0e7252b632651a6480f32fc47e973cca01 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil/kvtest.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil/kvtest.go @@ -13,8 +13,8 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/errors" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/errors" + "github.com/syndtr/goleveldb/leveldb/util" ) func KeyValueTesting(rnd *rand.Rand, kv KeyValue, p DB, setup func(KeyValue) DB, teardown func(DB)) { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil/storage.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil/storage.go index d515438b175e1ae785a6ae3ee500808dc7c62cdb..59c496d54c62e90afe4cd057d81f412b10edef6b 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil/storage.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil/storage.go @@ -18,8 +18,8 @@ import ( . "github.com/onsi/gomega" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/storage" + "github.com/syndtr/goleveldb/leveldb/util" ) var ( diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil/util.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil/util.go index 7ac261ddba2bd4c5056f737f2af07dd0cdca1f61..97c5294b1b5dd0c16162cd49fb55ad27274cb89a 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil/util.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil/util.go @@ -15,7 +15,7 @@ import ( "github.com/onsi/ginkgo/config" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/comparer" + "github.com/syndtr/goleveldb/leveldb/comparer" ) var ( diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil_test.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil_test.go index 868f7ffab3e0df8ba7c583e05b1960529148e8ad..25bf2b29f99310e6af6ab1532ccfc9cdf1621e87 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil_test.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil_test.go @@ -9,10 +9,10 @@ package leveldb import ( . "github.com/onsi/gomega" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/testutil" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/iterator" + "github.com/syndtr/goleveldb/leveldb/opt" + "github.com/syndtr/goleveldb/leveldb/testutil" + "github.com/syndtr/goleveldb/leveldb/util" ) type testingDB struct { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util.go index 7de9260d0d38eb3b21e5e2c5d2841695bda8a4ad..1a5bf71a3254044964beba9aee5362e5da1ed763 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util.go @@ -10,7 +10,7 @@ import ( "fmt" "sort" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/storage" + "github.com/syndtr/goleveldb/leveldb/storage" ) func shorten(str string) string { diff --git a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/version.go b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/version.go index 25ae21da97e390fb12f92a32ae44053cf247e2ba..011d982da82c13eaf18b9b2abb9c106f2c4a012e 100644 --- a/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/version.go +++ b/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/version.go @@ -10,9 +10,9 @@ import ( "sync/atomic" "unsafe" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/iterator" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/util" + "github.com/syndtr/goleveldb/leveldb/iterator" + "github.com/syndtr/goleveldb/leveldb/opt" + "github.com/syndtr/goleveldb/leveldb/util" ) type tSet struct { diff --git a/Godeps/_workspace/src/github.com/syndtr/gosnappy/snappy/decode.go b/Godeps/_workspace/src/github.com/syndtr/gosnappy/snappy/decode.go new file mode 100644 index 0000000000000000000000000000000000000000..d93c1b9dbfd7cea5fe7b86520548181d3729fa94 --- /dev/null +++ b/Godeps/_workspace/src/github.com/syndtr/gosnappy/snappy/decode.go @@ -0,0 +1,124 @@ +// Copyright 2011 The Snappy-Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package snappy + +import ( + "encoding/binary" + "errors" +) + +// ErrCorrupt reports that the input is invalid. +var ErrCorrupt = errors.New("snappy: corrupt input") + +// DecodedLen returns the length of the decoded block. +func DecodedLen(src []byte) (int, error) { + v, _, err := decodedLen(src) + return v, err +} + +// decodedLen returns the length of the decoded block and the number of bytes +// that the length header occupied. +func decodedLen(src []byte) (blockLen, headerLen int, err error) { + v, n := binary.Uvarint(src) + if n == 0 { + return 0, 0, ErrCorrupt + } + if uint64(int(v)) != v { + return 0, 0, errors.New("snappy: decoded block is too large") + } + return int(v), n, nil +} + +// Decode returns the decoded form of src. The returned slice may be a sub- +// slice of dst if dst was large enough to hold the entire decoded block. +// Otherwise, a newly allocated slice will be returned. +// It is valid to pass a nil dst. +func Decode(dst, src []byte) ([]byte, error) { + dLen, s, err := decodedLen(src) + if err != nil { + return nil, err + } + if len(dst) < dLen { + dst = make([]byte, dLen) + } + + var d, offset, length int + for s < len(src) { + switch src[s] & 0x03 { + case tagLiteral: + x := uint(src[s] >> 2) + switch { + case x < 60: + s += 1 + case x == 60: + s += 2 + if s > len(src) { + return nil, ErrCorrupt + } + x = uint(src[s-1]) + case x == 61: + s += 3 + if s > len(src) { + return nil, ErrCorrupt + } + x = uint(src[s-2]) | uint(src[s-1])<<8 + case x == 62: + s += 4 + if s > len(src) { + return nil, ErrCorrupt + } + x = uint(src[s-3]) | uint(src[s-2])<<8 | uint(src[s-1])<<16 + case x == 63: + s += 5 + if s > len(src) { + return nil, ErrCorrupt + } + x = uint(src[s-4]) | uint(src[s-3])<<8 | uint(src[s-2])<<16 | uint(src[s-1])<<24 + } + length = int(x + 1) + if length <= 0 { + return nil, errors.New("snappy: unsupported literal length") + } + if length > len(dst)-d || length > len(src)-s { + return nil, ErrCorrupt + } + copy(dst[d:], src[s:s+length]) + d += length + s += length + continue + + case tagCopy1: + s += 2 + if s > len(src) { + return nil, ErrCorrupt + } + length = 4 + int(src[s-2])>>2&0x7 + offset = int(src[s-2])&0xe0<<3 | int(src[s-1]) + + case tagCopy2: + s += 3 + if s > len(src) { + return nil, ErrCorrupt + } + length = 1 + int(src[s-3])>>2 + offset = int(src[s-2]) | int(src[s-1])<<8 + + case tagCopy4: + return nil, errors.New("snappy: unsupported COPY_4 tag") + } + + end := d + length + if offset > d || end > len(dst) { + return nil, ErrCorrupt + } + for ; d < end; d++ { + dst[d] = dst[d-offset] + } + } + if d != dLen { + return nil, ErrCorrupt + } + return dst[:d], nil +} diff --git a/Godeps/_workspace/src/github.com/google/go-snappy/snappy/encode.go b/Godeps/_workspace/src/github.com/syndtr/gosnappy/snappy/encode.go similarity index 69% rename from Godeps/_workspace/src/github.com/google/go-snappy/snappy/encode.go rename to Godeps/_workspace/src/github.com/syndtr/gosnappy/snappy/encode.go index dda372422d437441e1932607737295eae4bd30fd..b2371db11c8f0c15a4be374eed72f96bd42b864c 100644 --- a/Godeps/_workspace/src/github.com/google/go-snappy/snappy/encode.go +++ b/Godeps/_workspace/src/github.com/syndtr/gosnappy/snappy/encode.go @@ -6,7 +6,6 @@ package snappy import ( "encoding/binary" - "io" ) // We limit how far copy back-references can go, the same as the C++ code. @@ -173,86 +172,3 @@ func MaxEncodedLen(srcLen int) int { // This last factor dominates the blowup, so the final estimate is: return 32 + srcLen + srcLen/6 } - -// NewWriter returns a new Writer that compresses to w, using the framing -// format described at -// https://code.google.com/p/snappy/source/browse/trunk/framing_format.txt -func NewWriter(w io.Writer) *Writer { - return &Writer{ - w: w, - enc: make([]byte, MaxEncodedLen(maxUncompressedChunkLen)), - } -} - -// Writer is an io.Writer than can write Snappy-compressed bytes. -type Writer struct { - w io.Writer - err error - enc []byte - buf [checksumSize + chunkHeaderSize]byte - wroteHeader bool -} - -// Reset discards the writer's state and switches the Snappy writer to write to -// w. This permits reusing a Writer rather than allocating a new one. -func (w *Writer) Reset(writer io.Writer) { - w.w = writer - w.err = nil - w.wroteHeader = false -} - -// Write satisfies the io.Writer interface. -func (w *Writer) Write(p []byte) (n int, errRet error) { - if w.err != nil { - return 0, w.err - } - if !w.wroteHeader { - copy(w.enc, magicChunk) - if _, err := w.w.Write(w.enc[:len(magicChunk)]); err != nil { - w.err = err - return n, err - } - w.wroteHeader = true - } - for len(p) > 0 { - var uncompressed []byte - if len(p) > maxUncompressedChunkLen { - uncompressed, p = p[:maxUncompressedChunkLen], p[maxUncompressedChunkLen:] - } else { - uncompressed, p = p, nil - } - checksum := crc(uncompressed) - - // Compress the buffer, discarding the result if the improvement - // isn't at least 12.5%. - chunkType := uint8(chunkTypeCompressedData) - chunkBody, err := Encode(w.enc, uncompressed) - if err != nil { - w.err = err - return n, err - } - if len(chunkBody) >= len(uncompressed)-len(uncompressed)/8 { - chunkType, chunkBody = chunkTypeUncompressedData, uncompressed - } - - chunkLen := 4 + len(chunkBody) - w.buf[0] = chunkType - w.buf[1] = uint8(chunkLen >> 0) - w.buf[2] = uint8(chunkLen >> 8) - w.buf[3] = uint8(chunkLen >> 16) - w.buf[4] = uint8(checksum >> 0) - w.buf[5] = uint8(checksum >> 8) - w.buf[6] = uint8(checksum >> 16) - w.buf[7] = uint8(checksum >> 24) - if _, err = w.w.Write(w.buf[:]); err != nil { - w.err = err - return n, err - } - if _, err = w.w.Write(chunkBody); err != nil { - w.err = err - return n, err - } - n += len(uncompressed) - } - return n, nil -} diff --git a/Godeps/_workspace/src/github.com/google/go-snappy/snappy/snappy.go b/Godeps/_workspace/src/github.com/syndtr/gosnappy/snappy/snappy.go similarity index 68% rename from Godeps/_workspace/src/github.com/google/go-snappy/snappy/snappy.go rename to Godeps/_workspace/src/github.com/syndtr/gosnappy/snappy/snappy.go index 043bf3d81a949af84bafdf12a7b1e06f93e75bb9..2f1b790d0b7170df134cdf3f95786120a1f54dae 100644 --- a/Godeps/_workspace/src/github.com/google/go-snappy/snappy/snappy.go +++ b/Godeps/_workspace/src/github.com/syndtr/gosnappy/snappy/snappy.go @@ -8,10 +8,6 @@ // The C++ snappy implementation is at http://code.google.com/p/snappy/ package snappy -import ( - "hash/crc32" -) - /* Each encoded block begins with the varint-encoded length of the decoded data, followed by a sequence of chunks. Chunks begin and end on byte boundaries. The @@ -40,29 +36,3 @@ const ( tagCopy2 = 0x02 tagCopy4 = 0x03 ) - -const ( - checksumSize = 4 - chunkHeaderSize = 4 - magicChunk = "\xff\x06\x00\x00" + magicBody - magicBody = "sNaPpY" - // https://code.google.com/p/snappy/source/browse/trunk/framing_format.txt says - // that "the uncompressed data in a chunk must be no longer than 65536 bytes". - maxUncompressedChunkLen = 65536 -) - -const ( - chunkTypeCompressedData = 0x00 - chunkTypeUncompressedData = 0x01 - chunkTypePadding = 0xfe - chunkTypeStreamIdentifier = 0xff -) - -var crcTable = crc32.MakeTable(crc32.Castagnoli) - -// crc implements the checksum specified in section 3 of -// https://code.google.com/p/snappy/source/browse/trunk/framing_format.txt -func crc(b []byte) uint32 { - c := crc32.Update(0, crcTable, b) - return uint32(c>>15|c<<17) + 0xa282ead8 -} diff --git a/Godeps/_workspace/src/github.com/google/go-snappy/snappy/snappy_test.go b/Godeps/_workspace/src/github.com/syndtr/gosnappy/snappy/snappy_test.go similarity index 57% rename from Godeps/_workspace/src/github.com/google/go-snappy/snappy/snappy_test.go rename to Godeps/_workspace/src/github.com/syndtr/gosnappy/snappy/snappy_test.go index 0623385b71d22ebe18ae8b5aae94e64d0825580d..7ba839244e9bb8b75ec49b2083eb428549190784 100644 --- a/Godeps/_workspace/src/github.com/google/go-snappy/snappy/snappy_test.go +++ b/Godeps/_workspace/src/github.com/syndtr/gosnappy/snappy/snappy_test.go @@ -18,10 +18,7 @@ import ( "testing" ) -var ( - download = flag.Bool("download", false, "If true, download any missing files before running benchmarks") - testdata = flag.String("testdata", "testdata", "Directory containing the test data") -) +var download = flag.Bool("download", false, "If true, download any missing files before running benchmarks") func roundtrip(b, ebuf, dbuf []byte) error { e, err := Encode(ebuf, b) @@ -58,11 +55,11 @@ func TestSmallCopy(t *testing.T) { } func TestSmallRand(t *testing.T) { - rng := rand.New(rand.NewSource(27354294)) + rand.Seed(27354294) for n := 1; n < 20000; n += 23 { b := make([]byte, n) - for i := range b { - b[i] = uint8(rng.Uint32()) + for i, _ := range b { + b[i] = uint8(rand.Uint32()) } if err := roundtrip(b, nil, nil); err != nil { t.Fatal(err) @@ -73,7 +70,7 @@ func TestSmallRand(t *testing.T) { func TestSmallRegular(t *testing.T) { for n := 1; n < 20000; n += 23 { b := make([]byte, n) - for i := range b { + for i, _ := range b { b[i] = uint8(i%10 + 'a') } if err := roundtrip(b, nil, nil); err != nil { @@ -82,120 +79,6 @@ func TestSmallRegular(t *testing.T) { } } -func cmp(a, b []byte) error { - if len(a) != len(b) { - return fmt.Errorf("got %d bytes, want %d", len(a), len(b)) - } - for i := range a { - if a[i] != b[i] { - return fmt.Errorf("byte #%d: got 0x%02x, want 0x%02x", i, a[i], b[i]) - } - } - return nil -} - -func TestFramingFormat(t *testing.T) { - // src is comprised of alternating 1e5-sized sequences of random - // (incompressible) bytes and repeated (compressible) bytes. 1e5 was chosen - // because it is larger than maxUncompressedChunkLen (64k). - src := make([]byte, 1e6) - rng := rand.New(rand.NewSource(1)) - for i := 0; i < 10; i++ { - if i%2 == 0 { - for j := 0; j < 1e5; j++ { - src[1e5*i+j] = uint8(rng.Intn(256)) - } - } else { - for j := 0; j < 1e5; j++ { - src[1e5*i+j] = uint8(i) - } - } - } - - buf := new(bytes.Buffer) - if _, err := NewWriter(buf).Write(src); err != nil { - t.Fatalf("Write: encoding: %v", err) - } - dst, err := ioutil.ReadAll(NewReader(buf)) - if err != nil { - t.Fatalf("ReadAll: decoding: %v", err) - } - if err := cmp(dst, src); err != nil { - t.Fatal(err) - } -} - -func TestReaderReset(t *testing.T) { - gold := bytes.Repeat([]byte("All that is gold does not glitter,\n"), 10000) - buf := new(bytes.Buffer) - if _, err := NewWriter(buf).Write(gold); err != nil { - t.Fatalf("Write: %v", err) - } - encoded, invalid, partial := buf.String(), "invalid", "partial" - r := NewReader(nil) - for i, s := range []string{encoded, invalid, partial, encoded, partial, invalid, encoded, encoded} { - if s == partial { - r.Reset(strings.NewReader(encoded)) - if _, err := r.Read(make([]byte, 101)); err != nil { - t.Errorf("#%d: %v", i, err) - continue - } - continue - } - r.Reset(strings.NewReader(s)) - got, err := ioutil.ReadAll(r) - switch s { - case encoded: - if err != nil { - t.Errorf("#%d: %v", i, err) - continue - } - if err := cmp(got, gold); err != nil { - t.Errorf("#%d: %v", i, err) - continue - } - case invalid: - if err == nil { - t.Errorf("#%d: got nil error, want non-nil", i) - continue - } - } - } -} - -func TestWriterReset(t *testing.T) { - gold := bytes.Repeat([]byte("Not all those who wander are lost;\n"), 10000) - var gots, wants [][]byte - const n = 20 - w, failed := NewWriter(nil), false - for i := 0; i <= n; i++ { - buf := new(bytes.Buffer) - w.Reset(buf) - want := gold[:len(gold)*i/n] - if _, err := w.Write(want); err != nil { - t.Errorf("#%d: Write: %v", i, err) - failed = true - continue - } - got, err := ioutil.ReadAll(NewReader(buf)) - if err != nil { - t.Errorf("#%d: ReadAll: %v", i, err) - failed = true - continue - } - gots = append(gots, got) - wants = append(wants, want) - } - if failed { - return - } - for i := range gots { - if err := cmp(gots[i], wants[i]); err != nil { - t.Errorf("#%d: %v", i, err) - } - } -} - func benchDecode(b *testing.B, src []byte) { encoded, err := Encode(nil, src) if err != nil { @@ -219,7 +102,7 @@ func benchEncode(b *testing.B, src []byte) { } } -func readFile(b testing.TB, filename string) []byte { +func readFile(b *testing.B, filename string) []byte { src, err := ioutil.ReadFile(filename) if err != nil { b.Fatalf("failed reading %s: %s", filename, err) @@ -261,7 +144,7 @@ func BenchmarkWordsEncode1e5(b *testing.B) { benchWords(b, 1e5, false) } func BenchmarkWordsEncode1e6(b *testing.B) { benchWords(b, 1e6, false) } // testFiles' values are copied directly from -// https://raw.githubusercontent.com/google/snappy/master/snappy_unittest.cc +// https://code.google.com/p/snappy/source/browse/trunk/snappy_unittest.cc. // The label field is unused in snappy-go. var testFiles = []struct { label string @@ -269,36 +152,29 @@ var testFiles = []struct { }{ {"html", "html"}, {"urls", "urls.10K"}, - {"jpg", "fireworks.jpeg"}, - {"jpg_200", "fireworks.jpeg"}, - {"pdf", "paper-100k.pdf"}, + {"jpg", "house.jpg"}, + {"pdf", "mapreduce-osdi-1.pdf"}, {"html4", "html_x_4"}, + {"cp", "cp.html"}, + {"c", "fields.c"}, + {"lsp", "grammar.lsp"}, + {"xls", "kennedy.xls"}, {"txt1", "alice29.txt"}, {"txt2", "asyoulik.txt"}, {"txt3", "lcet10.txt"}, {"txt4", "plrabn12.txt"}, + {"bin", "ptt5"}, + {"sum", "sum"}, + {"man", "xargs.1"}, {"pb", "geo.protodata"}, {"gaviota", "kppkn.gtb"}, } // The test data files are present at this canonical URL. -const baseURL = "https://raw.githubusercontent.com/google/snappy/master/testdata/" +const baseURL = "https://snappy.googlecode.com/svn/trunk/testdata/" func downloadTestdata(basename string) (errRet error) { - filename := filepath.Join(*testdata, basename) - if stat, err := os.Stat(filename); err == nil && stat.Size() != 0 { - return nil - } - - if !*download { - return fmt.Errorf("test data not found; skipping benchmark without the -download flag") - } - // Download the official snappy C++ implementation reference test data - // files for benchmarking. - if err := os.Mkdir(*testdata, 0777); err != nil && !os.IsExist(err) { - return fmt.Errorf("failed to create testdata: %s", err) - } - + filename := filepath.Join("testdata", basename) f, err := os.Create(filename) if err != nil { return fmt.Errorf("failed to create %s: %s", filename, err) @@ -309,27 +185,36 @@ func downloadTestdata(basename string) (errRet error) { os.Remove(filename) } }() - url := baseURL + basename - resp, err := http.Get(url) + resp, err := http.Get(baseURL + basename) if err != nil { - return fmt.Errorf("failed to download %s: %s", url, err) + return fmt.Errorf("failed to download %s: %s", baseURL+basename, err) } defer resp.Body.Close() - if s := resp.StatusCode; s != http.StatusOK { - return fmt.Errorf("downloading %s: HTTP status code %d (%s)", url, s, http.StatusText(s)) - } _, err = io.Copy(f, resp.Body) if err != nil { - return fmt.Errorf("failed to download %s to %s: %s", url, filename, err) + return fmt.Errorf("failed to write %s: %s", filename, err) } return nil } func benchFile(b *testing.B, n int, decode bool) { - if err := downloadTestdata(testFiles[n].filename); err != nil { - b.Fatalf("failed to download testdata: %s", err) + filename := filepath.Join("testdata", testFiles[n].filename) + if stat, err := os.Stat(filename); err != nil || stat.Size() == 0 { + if !*download { + b.Fatal("test data not found; skipping benchmark without the -download flag") + } + // Download the official snappy C++ implementation reference test data + // files for benchmarking. + if err := os.Mkdir("testdata", 0777); err != nil && !os.IsExist(err) { + b.Fatalf("failed to create testdata: %s", err) + } + for _, tf := range testFiles { + if err := downloadTestdata(tf.filename); err != nil { + b.Fatalf("failed to download testdata: %s", err) + } + } } - data := readFile(b, filepath.Join(*testdata, testFiles[n].filename)) + data := readFile(b, filename) if decode { benchDecode(b, data) } else { @@ -350,6 +235,12 @@ func Benchmark_UFlat8(b *testing.B) { benchFile(b, 8, true) } func Benchmark_UFlat9(b *testing.B) { benchFile(b, 9, true) } func Benchmark_UFlat10(b *testing.B) { benchFile(b, 10, true) } func Benchmark_UFlat11(b *testing.B) { benchFile(b, 11, true) } +func Benchmark_UFlat12(b *testing.B) { benchFile(b, 12, true) } +func Benchmark_UFlat13(b *testing.B) { benchFile(b, 13, true) } +func Benchmark_UFlat14(b *testing.B) { benchFile(b, 14, true) } +func Benchmark_UFlat15(b *testing.B) { benchFile(b, 15, true) } +func Benchmark_UFlat16(b *testing.B) { benchFile(b, 16, true) } +func Benchmark_UFlat17(b *testing.B) { benchFile(b, 17, true) } func Benchmark_ZFlat0(b *testing.B) { benchFile(b, 0, false) } func Benchmark_ZFlat1(b *testing.B) { benchFile(b, 1, false) } func Benchmark_ZFlat2(b *testing.B) { benchFile(b, 2, false) } @@ -362,3 +253,9 @@ func Benchmark_ZFlat8(b *testing.B) { benchFile(b, 8, false) } func Benchmark_ZFlat9(b *testing.B) { benchFile(b, 9, false) } func Benchmark_ZFlat10(b *testing.B) { benchFile(b, 10, false) } func Benchmark_ZFlat11(b *testing.B) { benchFile(b, 11, false) } +func Benchmark_ZFlat12(b *testing.B) { benchFile(b, 12, false) } +func Benchmark_ZFlat13(b *testing.B) { benchFile(b, 13, false) } +func Benchmark_ZFlat14(b *testing.B) { benchFile(b, 14, false) } +func Benchmark_ZFlat15(b *testing.B) { benchFile(b, 15, false) } +func Benchmark_ZFlat16(b *testing.B) { benchFile(b, 16, false) } +func Benchmark_ZFlat17(b *testing.B) { benchFile(b, 17, false) } diff --git a/Godeps/_workspace/src/github.com/tendermint/ed25519/ed25519.go b/Godeps/_workspace/src/github.com/tendermint/ed25519/ed25519.go index 6c7e5cbc4109740ed3d2ecb517d02d63e89b84cd..48ac4a423ec0452caf979154573e15485834a25a 100644 --- a/Godeps/_workspace/src/github.com/tendermint/ed25519/ed25519.go +++ b/Godeps/_workspace/src/github.com/tendermint/ed25519/ed25519.go @@ -14,7 +14,7 @@ import ( "crypto/subtle" "io" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/agl/ed25519/edwards25519" + "github.com/agl/ed25519/edwards25519" ) const ( diff --git a/Godeps/_workspace/src/github.com/tendermint/ed25519/extra25519/extra25519.go b/Godeps/_workspace/src/github.com/tendermint/ed25519/extra25519/extra25519.go index bbda91686372ac2982d68a41dac8b7fb446eb67a..571218f5516f5f679364e57cb3db1fcbf3fb3225 100644 --- a/Godeps/_workspace/src/github.com/tendermint/ed25519/extra25519/extra25519.go +++ b/Godeps/_workspace/src/github.com/tendermint/ed25519/extra25519/extra25519.go @@ -7,7 +7,7 @@ package extra25519 import ( "crypto/sha512" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/agl/ed25519/edwards25519" + "github.com/agl/ed25519/edwards25519" ) // PrivateKeyToCurve25519 converts an ed25519 private key into a corresponding diff --git a/Godeps/_workspace/src/github.com/tendermint/log15/handler.go b/Godeps/_workspace/src/github.com/tendermint/log15/handler.go index 5dc7299843978865fec11d9103ea519e1ee5af89..4c771b4ba65c25eddec2741d29863af9cb17222b 100644 --- a/Godeps/_workspace/src/github.com/tendermint/log15/handler.go +++ b/Godeps/_workspace/src/github.com/tendermint/log15/handler.go @@ -11,7 +11,7 @@ import ( "sync/atomic" "unsafe" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/inconshreveable/log15/stack" + "github.com/inconshreveable/log15/stack" ) // A Logger prints its log records by writing to a Handler. diff --git a/Godeps/_workspace/src/github.com/tendermint/log15/root.go b/Godeps/_workspace/src/github.com/tendermint/log15/root.go index 7034447afaeab3524567b74eb98c7bd3c65f7d7e..98103173063315850752f8c4752b70d09799325b 100644 --- a/Godeps/_workspace/src/github.com/tendermint/log15/root.go +++ b/Godeps/_workspace/src/github.com/tendermint/log15/root.go @@ -3,8 +3,8 @@ package log15 import ( "os" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/inconshreveable/log15/term" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/mattn/go-colorable" + "github.com/inconshreveable/log15/term" + "github.com/mattn/go-colorable" ) var ( diff --git a/Godeps/_workspace/src/github.com/tendermint/log15/stack/stack_test.go b/Godeps/_workspace/src/github.com/tendermint/log15/stack/stack_test.go index 64cd7d08075a7c43b884ce6076545c30a0564990..52371b1e45ab1ac08469a56607133e18cc6716d5 100644 --- a/Godeps/_workspace/src/github.com/tendermint/log15/stack/stack_test.go +++ b/Godeps/_workspace/src/github.com/tendermint/log15/stack/stack_test.go @@ -9,7 +9,7 @@ import ( "runtime" "testing" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/inconshreveable/log15/stack" + "github.com/inconshreveable/log15/stack" ) type testType struct{} diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/account/priv_account.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/account/priv_account.go index 42a650e6999ffeb84775c56f0e866a0ea1105ca7..0d37711bb35dc596281c96a1ad1e06ba85638d91 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/account/priv_account.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/account/priv_account.go @@ -47,9 +47,14 @@ func GenPrivAccount() *PrivAccount { } } +// Generates 32 priv key bytes from secret +func GenPrivKeyBytesFromSecret(secret string) []byte { + return wire.BinarySha256(secret) // Not Ripemd160 because we want 32 bytes. +} + // Generates a new account with private key from SHA256 hash of a secret -func GenPrivAccountFromSecret(secret []byte) *PrivAccount { - privKey32 := wire.BinarySha256(secret) // Not Ripemd160 because we want 32 bytes. +func GenPrivAccountFromSecret(secret string) *PrivAccount { + privKey32 := GenPrivKeyBytesFromSecret(secret) privKeyBytes := new([64]byte) copy(privKeyBytes[:32], privKey32) pubKeyBytes := ed25519.MakePublicKey(privKeyBytes) @@ -62,13 +67,15 @@ func GenPrivAccountFromSecret(secret []byte) *PrivAccount { } } -func GenPrivAccountFromPrivKeyBytes(privKeyBytes *[64]byte) *PrivAccount { +func GenPrivAccountFromPrivKeyBytes(privKeyBytes []byte) *PrivAccount { if len(privKeyBytes) != 64 { PanicSanity(Fmt("Expected 64 bytes but got %v", len(privKeyBytes))) } - pubKeyBytes := ed25519.MakePublicKey(privKeyBytes) + var privKeyArray [64]byte + copy(privKeyArray[:], privKeyBytes) + pubKeyBytes := ed25519.MakePublicKey(&privKeyArray) pubKey := PubKeyEd25519(*pubKeyBytes) - privKey := PrivKeyEd25519(*privKeyBytes) + privKey := PrivKeyEd25519(privKeyArray) return &PrivAccount{ Address: pubKey.Address(), PubKey: pubKey, diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/alert/alert.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/alert/alert.go index 497be012cd64708407554ad46cf04fbf7209ea46..c47633091d786c9c51ed40861ce8b890de856de0 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/alert/alert.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/alert/alert.go @@ -4,7 +4,7 @@ import ( "fmt" "time" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/sfreiberg/gotwilio" + "github.com/sfreiberg/gotwilio" ) var lastAlertUnix int64 = 0 diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/blockchain/pool.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/blockchain/pool.go index 95b33b88fd4ed65198c15e20265fcec41f0bdfb4..66be4dc820cd983b702ddd6349473fd8a5192c76 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/blockchain/pool.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/blockchain/pool.go @@ -1,24 +1,22 @@ package blockchain import ( + "math" "sync" "time" + flow "github.com/eris-ltd/eris-db/Godeps/_workspace/src/code.google.com/p/mxk/go1/flowcontrol" . "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/common" "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/types" ) const ( - maxTries = 3 - inputsChannelCapacity = 200 - requestIntervalMS = 500 - maxPendingRequests = 200 - maxTotalRequests = 300 - maxRequestsPerPeer = 300 -) - -var ( - requestTimeoutSeconds = time.Duration(3) + requestIntervalMS = 250 + maxTotalRequests = 300 + maxPendingRequests = maxTotalRequests + maxPendingRequestsPerPeer = 75 + peerTimeoutSeconds = 15 + minRecvRate = 10240 // 10Kb/s ) /* @@ -33,14 +31,14 @@ var ( */ type BlockPool struct { - BaseService + QuitService + startTime time.Time // block requests - requestsMtx sync.Mutex - requests map[int]*bpRequest - height int // the lowest key in requests. - numUnassigned int32 // number of requests not yet assigned to a peer - numPending int32 // number of requests pending assignment or block response + mtx sync.Mutex + requests map[int]*bpRequester + height int // the lowest key in requests. + numPending int32 // number of requests pending assignment or block response // peers peersMtx sync.Mutex @@ -48,51 +46,51 @@ type BlockPool struct { requestsCh chan<- BlockRequest timeoutsCh chan<- string - repeater *RepeatTimer } func NewBlockPool(start int, requestsCh chan<- BlockRequest, timeoutsCh chan<- string) *BlockPool { bp := &BlockPool{ peers: make(map[string]*bpPeer), - requests: make(map[int]*bpRequest), - height: start, - numUnassigned: 0, - numPending: 0, + requests: make(map[int]*bpRequester), + height: start, + numPending: 0, requestsCh: requestsCh, timeoutsCh: timeoutsCh, - repeater: nil, } - bp.BaseService = *NewBaseService(log, "BlockPool", bp) + bp.QuitService = *NewQuitService(log, "BlockPool", bp) return bp } -func (pool *BlockPool) OnStart() { - pool.BaseService.OnStart() - pool.repeater = NewRepeatTimer("", requestIntervalMS*time.Millisecond) - go pool.run() +func (pool *BlockPool) OnStart() error { + pool.QuitService.OnStart() + go pool.makeRequestsRoutine() + pool.startTime = time.Now() + return nil } func (pool *BlockPool) OnStop() { - pool.BaseService.OnStop() - pool.repeater.Stop() + pool.QuitService.OnStop() } // Run spawns requests as needed. -func (pool *BlockPool) run() { -RUN_LOOP: +func (pool *BlockPool) makeRequestsRoutine() { for { if !pool.IsRunning() { - break RUN_LOOP + break } - _, numPending, _ := pool.GetStatus() + _, numPending := pool.GetStatus() if numPending >= maxPendingRequests { // sleep for a bit. time.Sleep(requestIntervalMS * time.Millisecond) + // check for timed out peers + pool.removeTimedoutPeers() } else if len(pool.requests) >= maxTotalRequests { // sleep for a bit. time.Sleep(requestIntervalMS * time.Millisecond) + // check for timed out peers + pool.removeTimedoutPeers() } else { // request for more blocks. pool.makeNextRequest() @@ -100,24 +98,60 @@ RUN_LOOP: } } -func (pool *BlockPool) GetStatus() (height int, numPending int32, numUnssigned int32) { - pool.requestsMtx.Lock() // Lock - defer pool.requestsMtx.Unlock() +func (pool *BlockPool) removeTimedoutPeers() { + for _, peer := range pool.peers { + if !peer.didTimeout && peer.numPending > 0 { + curRate := peer.recvMonitor.Status().CurRate + // XXX remove curRate != 0 + if curRate != 0 && curRate < minRecvRate { + pool.sendTimeout(peer.id) + log.Warn("SendTimeout", "peer", peer.id, "reason", "curRate too low") + peer.didTimeout = true + } + } + if peer.didTimeout { + pool.peersMtx.Lock() // Lock + pool.removePeer(peer.id) + pool.peersMtx.Unlock() + } + } +} + +func (pool *BlockPool) GetStatus() (height int, numPending int32) { + pool.mtx.Lock() // Lock + defer pool.mtx.Unlock() - return pool.height, pool.numPending, pool.numUnassigned + return pool.height, pool.numPending +} + +// TODO: relax conditions, prevent abuse. +func (pool *BlockPool) IsCaughtUp() bool { + pool.mtx.Lock() + height := pool.height + pool.mtx.Unlock() + + pool.peersMtx.Lock() + numPeers := len(pool.peers) + maxPeerHeight := 0 + for _, peer := range pool.peers { + maxPeerHeight = MaxInt(maxPeerHeight, peer.height) + } + pool.peersMtx.Unlock() + + return numPeers >= 3 && (height > 0 || time.Now().Sub(pool.startTime) > 30*time.Second) && (maxPeerHeight == 0 || height == maxPeerHeight) } // We need to see the second block's Validation to validate the first block. // So we peek two blocks at a time. func (pool *BlockPool) PeekTwoBlocks() (first *types.Block, second *types.Block) { - pool.requestsMtx.Lock() // Lock - defer pool.requestsMtx.Unlock() + pool.mtx.Lock() // Lock + defer pool.mtx.Unlock() if r := pool.requests[pool.height]; r != nil { - first = r.block + first = r.getBlock() } if r := pool.requests[pool.height+1]; r != nil { - second = r.block + second = r.getBlock() } return } @@ -125,119 +159,90 @@ func (pool *BlockPool) PeekTwoBlocks() (first *types.Block, second *types.Block) // Pop the first block at pool.height // It must have been validated by 'second'.Validation from PeekTwoBlocks(). func (pool *BlockPool) PopRequest() { - pool.requestsMtx.Lock() // Lock - defer pool.requestsMtx.Unlock() + pool.mtx.Lock() // Lock + defer pool.mtx.Unlock() + /* The block can disappear at any time, due to removePeer(). if r := pool.requests[pool.height]; r == nil || r.block == nil { PanicSanity("PopRequest() requires a valid block") } + */ delete(pool.requests, pool.height) pool.height++ } -// Invalidates the block at pool.height. -// Remove the peer and request from others. +// Invalidates the block at pool.height, +// Remove the peer and redo request from others. func (pool *BlockPool) RedoRequest(height int) { - pool.requestsMtx.Lock() // Lock - defer pool.requestsMtx.Unlock() + pool.mtx.Lock() // Lock + defer pool.mtx.Unlock() request := pool.requests[height] if request.block == nil { PanicSanity("Expected block to be non-nil") } + // RemovePeer will redo all requests associated with this peer. // TODO: record this malfeasance - // maybe punish peer on switch (an invalid block!) - pool.RemovePeer(request.peerId) // Lock on peersMtx. - request.block = nil - request.peerId = "" - pool.numPending++ - pool.numUnassigned++ - - go requestRoutine(pool, height) -} - -func (pool *BlockPool) hasBlock(height int) bool { - pool.requestsMtx.Lock() // Lock - defer pool.requestsMtx.Unlock() - - request := pool.requests[height] - return request != nil && request.block != nil + pool.RemovePeer(request.peerID) // Lock on peersMtx. } -func (pool *BlockPool) setPeerForRequest(height int, peerId string) { - pool.requestsMtx.Lock() // Lock - defer pool.requestsMtx.Unlock() +// TODO: ensure that blocks come in order for each peer. +func (pool *BlockPool) AddBlock(peerID string, block *types.Block, blockSize int) { + pool.mtx.Lock() // Lock + defer pool.mtx.Unlock() - request := pool.requests[height] + request := pool.requests[block.Height] if request == nil { return } - pool.numUnassigned-- - request.peerId = peerId -} -func (pool *BlockPool) removePeerForRequest(height int, peerId string) { - pool.requestsMtx.Lock() // Lock - defer pool.requestsMtx.Unlock() - - request := pool.requests[height] - if request == nil { - return + if request.setBlock(block, peerID) { + pool.numPending-- + peer := pool.getPeer(peerID) + peer.decrPending(blockSize) + } else { + // Bad peer? } - pool.numUnassigned++ - request.peerId = "" } -func (pool *BlockPool) AddBlock(block *types.Block, peerId string) { - pool.requestsMtx.Lock() // Lock - defer pool.requestsMtx.Unlock() +// Sets the peer's alleged blockchain height. +func (pool *BlockPool) SetPeerHeight(peerID string, height int) { + pool.peersMtx.Lock() // Lock + defer pool.peersMtx.Unlock() - request := pool.requests[block.Height] - if request == nil { - return - } - if request.peerId != peerId { - return - } - if request.block != nil { - return + peer := pool.peers[peerID] + if peer != nil { + peer.height = height + } else { + peer = newBPPeer(pool, peerID, height) + pool.peers[peerID] = peer } - request.block = block - pool.numPending-- } -func (pool *BlockPool) getPeer(peerId string) *bpPeer { +func (pool *BlockPool) RemovePeer(peerID string) { pool.peersMtx.Lock() // Lock defer pool.peersMtx.Unlock() - peer := pool.peers[peerId] - return peer + pool.removePeer(peerID) } -// Sets the peer's alleged blockchain height. -func (pool *BlockPool) SetPeerHeight(peerId string, height int) { - pool.peersMtx.Lock() // Lock - defer pool.peersMtx.Unlock() - - peer := pool.peers[peerId] - if peer != nil { - peer.height = height - } else { - peer = &bpPeer{ - height: height, - id: peerId, - numRequests: 0, +func (pool *BlockPool) removePeer(peerID string) { + for _, request := range pool.requests { + if request.getPeerID() == peerID { + pool.numPending++ + go request.redo() // pick another peer and ... } - pool.peers[peerId] = peer } + delete(pool.peers, peerID) } -func (pool *BlockPool) RemovePeer(peerId string) { +func (pool *BlockPool) getPeer(peerID string) *bpPeer { pool.peersMtx.Lock() // Lock defer pool.peersMtx.Unlock() - delete(pool.peers, peerId) + peer := pool.peers[peerID] + return peer } // Pick an available peer with at least the given minHeight. @@ -247,64 +252,53 @@ func (pool *BlockPool) pickIncrAvailablePeer(minHeight int) *bpPeer { defer pool.peersMtx.Unlock() for _, peer := range pool.peers { - if peer.numRequests >= maxRequestsPerPeer { + if peer.isBad() { + pool.removePeer(peer.id) + continue + } else { + } + if peer.numPending >= maxPendingRequestsPerPeer { continue } if peer.height < minHeight { continue } - peer.numRequests++ + peer.incrPending() return peer } return nil } -func (pool *BlockPool) decrPeer(peerId string) { - pool.peersMtx.Lock() - defer pool.peersMtx.Unlock() - - peer := pool.peers[peerId] - if peer == nil { - return - } - peer.numRequests-- -} - func (pool *BlockPool) makeNextRequest() { - pool.requestsMtx.Lock() // Lock - defer pool.requestsMtx.Unlock() + pool.mtx.Lock() // Lock + defer pool.mtx.Unlock() nextHeight := pool.height + len(pool.requests) - request := &bpRequest{ - height: nextHeight, - peerId: "", - block: nil, - } + request := newBPRequester(pool, nextHeight) pool.requests[nextHeight] = request - pool.numUnassigned++ pool.numPending++ - go requestRoutine(pool, nextHeight) + request.Start() } -func (pool *BlockPool) sendRequest(height int, peerId string) { +func (pool *BlockPool) sendRequest(height int, peerID string) { if !pool.IsRunning() { return } - pool.requestsCh <- BlockRequest{height, peerId} + pool.requestsCh <- BlockRequest{height, peerID} } -func (pool *BlockPool) sendTimeout(peerId string) { +func (pool *BlockPool) sendTimeout(peerID string) { if !pool.IsRunning() { return } - pool.timeoutsCh <- peerId + pool.timeoutsCh <- peerID } func (pool *BlockPool) debug() string { - pool.requestsMtx.Lock() // Lock - defer pool.requestsMtx.Unlock() + pool.mtx.Lock() // Lock + defer pool.mtx.Unlock() str := "" for h := pool.height; h < pool.height+len(pool.requests); h++ { @@ -321,64 +315,188 @@ func (pool *BlockPool) debug() string { //------------------------------------- type bpPeer struct { + pool *BlockPool id string height int - numRequests int32 + numPending int32 + recvMonitor *flow.Monitor + timeout *time.Timer + didTimeout bool } -type bpRequest struct { - height int - peerId string - block *types.Block +func newBPPeer(pool *BlockPool, peerID string, height int) *bpPeer { + peer := &bpPeer{ + pool: pool, + id: peerID, + height: height, + numPending: 0, + } + return peer +} + +func (peer *bpPeer) resetMonitor() { + peer.recvMonitor = flow.New(time.Second, time.Second*40) + var initialValue = float64(minRecvRate) * math.E + peer.recvMonitor.SetREMA(initialValue) +} + +func (peer *bpPeer) resetTimeout() { + if peer.timeout == nil { + peer.timeout = time.AfterFunc(time.Second*peerTimeoutSeconds, peer.onTimeout) + } else { + peer.timeout.Reset(time.Second * peerTimeoutSeconds) + } +} + +func (peer *bpPeer) incrPending() { + if peer.numPending == 0 { + peer.resetMonitor() + peer.resetTimeout() + } + peer.numPending++ +} + +func (peer *bpPeer) decrPending(recvSize int) { + peer.numPending-- + if peer.numPending == 0 { + peer.timeout.Stop() + } else { + peer.recvMonitor.Update(recvSize) + peer.resetTimeout() + } +} + +func (peer *bpPeer) onTimeout() { + peer.pool.sendTimeout(peer.id) + log.Warn("SendTimeout", "peer", peer.id, "reason", "onTimeout") + peer.didTimeout = true +} + +func (peer *bpPeer) isBad() bool { + return peer.didTimeout } //------------------------------------- +type bpRequester struct { + QuitService + pool *BlockPool + height int + gotBlockCh chan struct{} + redoCh chan struct{} + + mtx sync.Mutex + peerID string + block *types.Block +} + +func newBPRequester(pool *BlockPool, height int) *bpRequester { + bpr := &bpRequester{ + pool: pool, + height: height, + gotBlockCh: make(chan struct{}), + redoCh: make(chan struct{}), + + peerID: "", + block: nil, + } + bpr.QuitService = *NewQuitService(nil, "bpRequester", bpr) + return bpr +} + +func (bpr *bpRequester) OnStart() error { + bpr.QuitService.OnStart() + go bpr.requestRoutine() + return nil +} + +// Returns true if the peer matches +func (bpr *bpRequester) setBlock(block *types.Block, peerID string) bool { + bpr.mtx.Lock() + if bpr.block != nil || bpr.peerID != peerID { + bpr.mtx.Unlock() + return false + } + bpr.block = block + bpr.mtx.Unlock() + + bpr.gotBlockCh <- struct{}{} + return true +} + +func (bpr *bpRequester) getBlock() *types.Block { + bpr.mtx.Lock() + defer bpr.mtx.Unlock() + return bpr.block +} + +func (bpr *bpRequester) getPeerID() string { + bpr.mtx.Lock() + defer bpr.mtx.Unlock() + return bpr.peerID +} + +func (bpr *bpRequester) reset() { + bpr.mtx.Lock() + bpr.peerID = "" + bpr.block = nil + bpr.mtx.Unlock() +} + +// Tells bpRequester to pick another peer and try again. +// NOTE: blocking +func (bpr *bpRequester) redo() { + bpr.redoCh <- struct{}{} +} + // Responsible for making more requests as necessary // Returns only when a block is found (e.g. AddBlock() is called) -func requestRoutine(pool *BlockPool, height int) { +func (bpr *bpRequester) requestRoutine() { +OUTER_LOOP: for { + // Pick a peer to send request to. var peer *bpPeer = nil - PICK_LOOP: + PICK_PEER_LOOP: for { - if !pool.IsRunning() { - log.Info("BlockPool not running. Stopping requestRoutine", "height", height) + if !bpr.IsRunning() || !bpr.pool.IsRunning() { return } - peer = pool.pickIncrAvailablePeer(height) + peer = bpr.pool.pickIncrAvailablePeer(bpr.height) if peer == nil { //log.Info("No peers available", "height", height) time.Sleep(requestIntervalMS * time.Millisecond) - continue PICK_LOOP + continue PICK_PEER_LOOP } - break PICK_LOOP + break PICK_PEER_LOOP } - - // set the peer, decrement numUnassigned - pool.setPeerForRequest(height, peer.id) - - for try := 0; try < maxTries; try++ { - pool.sendRequest(height, peer.id) - time.Sleep(requestTimeoutSeconds * time.Second) - // if successful the block is either in the pool, - if pool.hasBlock(height) { - pool.decrPeer(peer.id) + bpr.mtx.Lock() + bpr.peerID = peer.id + bpr.mtx.Unlock() + + // Send request and wait. + bpr.pool.sendRequest(bpr.height, peer.id) + select { + case <-bpr.pool.Quit: + bpr.Stop() + return + case <-bpr.Quit: + return + case <-bpr.redoCh: + bpr.reset() + continue OUTER_LOOP // When peer is removed + case <-bpr.gotBlockCh: + // We got the block, now see if it's good. + select { + case <-bpr.pool.Quit: + bpr.Stop() return - } - // or already processed and we've moved past it - bpHeight, _, _ := pool.GetStatus() - if height < bpHeight { - pool.decrPeer(peer.id) + case <-bpr.Quit: return + case <-bpr.redoCh: + bpr.reset() + continue OUTER_LOOP } } - - // unset the peer, increment numUnassigned - pool.removePeerForRequest(height, peer.id) - - // this peer failed us, try again - pool.RemovePeer(peer.id) - pool.sendTimeout(peer.id) } } @@ -386,5 +504,5 @@ func requestRoutine(pool *BlockPool, height int) { type BlockRequest struct { Height int - PeerId string + PeerID string } diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/blockchain/pool_test.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/blockchain/pool_test.go index 33840b49eb73a6e0c691df490970da0860e5a3e1..50a55b43248dc8cf49edfd90b3be6fc1098706a1 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/blockchain/pool_test.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/blockchain/pool_test.go @@ -17,16 +17,16 @@ type testPeer struct { func makePeers(numPeers int, minHeight, maxHeight int) map[string]testPeer { peers := make(map[string]testPeer, numPeers) for i := 0; i < numPeers; i++ { - peerId := RandStr(12) + peerID := RandStr(12) height := minHeight + rand.Intn(maxHeight-minHeight) - peers[peerId] = testPeer{peerId, height} + peers[peerID] = testPeer{peerID, height} } return peers } func TestBasic(t *testing.T) { - peers := makePeers(10, 0, 1000) start := 42 + peers := makePeers(10, start+1, 1000) timeoutsCh := make(chan string, 100) requestsCh := make(chan BlockRequest, 100) pool := NewBlockPool(start, requestsCh, timeoutsCh) @@ -57,8 +57,8 @@ func TestBasic(t *testing.T) { // Pull from channels for { select { - case peerId := <-timeoutsCh: - t.Errorf("timeout: %v", peerId) + case peerID := <-timeoutsCh: + t.Errorf("timeout: %v", peerID) case request := <-requestsCh: log.Info("TEST: Pulled new BlockRequest", "request", request) if request.Height == 300 { @@ -67,8 +67,8 @@ func TestBasic(t *testing.T) { // Request desired, pretend like we got the block immediately. go func() { block := &types.Block{Header: &types.Header{Height: request.Height}} - pool.AddBlock(block, request.PeerId) - log.Info("TEST: Added block", "block", request.Height, "peer", request.PeerId) + pool.AddBlock(request.PeerID, block, 123) + log.Info("TEST: Added block", "block", request.Height, "peer", request.PeerID) }() } } @@ -77,13 +77,17 @@ func TestBasic(t *testing.T) { } func TestTimeout(t *testing.T) { - peers := makePeers(10, 0, 1000) start := 42 + peers := makePeers(10, start+1, 1000) timeoutsCh := make(chan string, 100) requestsCh := make(chan BlockRequest, 100) pool := NewBlockPool(start, requestsCh, timeoutsCh) pool.Start() + for _, peer := range peers { + log.Info("Peer", "id", peer.id) + } + // Introduce each peer. go func() { for _, peer := range peers { @@ -111,9 +115,9 @@ func TestTimeout(t *testing.T) { timedOut := map[string]struct{}{} for { select { - case peerId := <-timeoutsCh: - log.Info("Timeout", "peerId", peerId) - if _, ok := timedOut[peerId]; !ok { + case peerID := <-timeoutsCh: + log.Info("Timeout", "peerID", peerID) + if _, ok := timedOut[peerID]; !ok { counter++ if counter == len(peers) { return // Done! diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/blockchain/reactor.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/blockchain/reactor.go index c9cfc5b755811dd972e0715ae2fb93bf6d8f0b4c..bd50d5a679588550e537f29b1f174fe6089831db 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/blockchain/reactor.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/blockchain/reactor.go @@ -27,7 +27,7 @@ const ( // ask for best height every 10s statusUpdateIntervalSeconds = 10 // check if we should switch to consensus reactor - switchToConsensusIntervalSeconds = 10 + switchToConsensusIntervalSeconds = 1 ) type consensusReactor interface { @@ -76,12 +76,16 @@ func NewBlockchainReactor(state *sm.State, store *BlockStore, sync bool) *Blockc return bcR } -func (bcR *BlockchainReactor) OnStart() { +func (bcR *BlockchainReactor) OnStart() error { bcR.BaseReactor.OnStart() if bcR.sync { - bcR.pool.Start() + _, err := bcR.pool.Start() + if err != nil { + return err + } go bcR.poolRoutine() } + return nil } func (bcR *BlockchainReactor) OnStop() { @@ -93,7 +97,7 @@ func (bcR *BlockchainReactor) OnStop() { func (bcR *BlockchainReactor) GetChannels() []*p2p.ChannelDescriptor { return []*p2p.ChannelDescriptor{ &p2p.ChannelDescriptor{ - Id: BlockchainChannel, + ID: BlockchainChannel, Priority: 5, SendQueueCapacity: 100, }, @@ -113,14 +117,14 @@ func (bcR *BlockchainReactor) RemovePeer(peer *p2p.Peer, reason interface{}) { } // Implements Reactor -func (bcR *BlockchainReactor) Receive(chId byte, src *p2p.Peer, msgBytes []byte) { +func (bcR *BlockchainReactor) Receive(chID byte, src *p2p.Peer, msgBytes []byte) { _, msg, err := DecodeMessage(msgBytes) if err != nil { log.Warn("Error decoding message", "error", err) return } - log.Notice("Received message", "msg", msg) + log.Notice("Received message", "src", src, "chID", chID, "msg", msg) switch msg := msg.(type) { case *bcBlockRequestMessage: @@ -137,7 +141,7 @@ func (bcR *BlockchainReactor) Receive(chId byte, src *p2p.Peer, msgBytes []byte) } case *bcBlockResponseMessage: // Got a block. - bcR.pool.AddBlock(msg.Block, src.Key) + bcR.pool.AddBlock(src.Key, msg.Block, len(msgBytes)) case *bcStatusRequestMessage: // Send peer our state. queued := src.TrySend(BlockchainChannel, &bcStatusResponseMessage{bcR.store.Height()}) @@ -165,21 +169,20 @@ FOR_LOOP: for { select { case request := <-bcR.requestsCh: // chan BlockRequest - peer := bcR.Switch.Peers().Get(request.PeerId) + peer := bcR.Switch.Peers().Get(request.PeerID) if peer == nil { - // We can't assign the request. - continue FOR_LOOP + continue FOR_LOOP // Peer has since been disconnected. } msg := &bcBlockRequestMessage{request.Height} queued := peer.TrySend(BlockchainChannel, msg) if !queued { // We couldn't make the request, send-queue full. - // The pool handles retries, so just let it go. + // The pool handles timeouts, just let it go. continue FOR_LOOP } - case peerId := <-bcR.timeoutsCh: // chan string + case peerID := <-bcR.timeoutsCh: // chan string // Peer timed out. - peer := bcR.Switch.Peers().Get(peerId) + peer := bcR.Switch.Peers().Get(peerID) if peer != nil { bcR.Switch.StopPeerForError(peer, errors.New("BlockchainReactor Timeout")) } @@ -187,17 +190,11 @@ FOR_LOOP: // ask for status updates go bcR.BroadcastStatusRequest() case _ = <-switchToConsensusTicker.C: - height, numPending, numUnassigned := bcR.pool.GetStatus() + height, numPending := bcR.pool.GetStatus() outbound, inbound, _ := bcR.Switch.NumPeers() - log.Info("Consensus ticker", "numUnassigned", numUnassigned, "numPending", numPending, - "total", len(bcR.pool.requests), "outbound", outbound, "inbound", inbound) - // NOTE: this condition is very strict right now. may need to weaken - // If all `maxPendingRequests` requests are unassigned - // and we have some peers (say >= 3), then we're caught up - maxPending := numPending == maxPendingRequests - allUnassigned := numPending == numUnassigned - enoughPeers := outbound+inbound >= 3 - if maxPending && allUnassigned && enoughPeers { + log.Info("Consensus ticker", "numPending", numPending, "total", len(bcR.pool.requests), + "outbound", outbound, "inbound", inbound) + if bcR.pool.IsCaughtUp() { log.Notice("Time to switch to consensus reactor!", "height", height) bcR.pool.Stop() @@ -279,11 +276,15 @@ var _ = wire.RegisterInterface( wire.ConcreteType{&bcStatusRequestMessage{}, msgTypeStatusRequest}, ) +// TODO: ensure that bz is completely read. func DecodeMessage(bz []byte) (msgType byte, msg BlockchainMessage, err error) { msgType = bz[0] - n := new(int64) + n := int64(0) r := bytes.NewReader(bz) - msg = wire.ReadBinary(struct{ BlockchainMessage }{}, r, n, &err).(struct{ BlockchainMessage }).BlockchainMessage + msg = wire.ReadBinary(struct{ BlockchainMessage }{}, r, &n, &err).(struct{ BlockchainMessage }).BlockchainMessage + if err != nil && n != int64(len(bz)) { + err = errors.New("DecodeMessage() had bytes left over.") + } return } diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/common/os.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/common/os.go index 5cdfd10ae8b7832f6a55ee169c5190890ad9e13e..170c6f82ae5b97544a3a8a5ebd39a95fef8b5570 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/common/os.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/common/os.go @@ -1,10 +1,12 @@ package common import ( + "bufio" "fmt" "io/ioutil" "os" "os/signal" + "strings" "sync" "time" ) @@ -67,7 +69,7 @@ func WriteFile(filePath string, contents []byte) error { if err != nil { return err } - fmt.Printf("File written to %v.\n", filePath) + // fmt.Printf("File written to %v.\n", filePath) return nil } @@ -198,3 +200,26 @@ func (af *AutoFile) openFile() error { af.file = file return nil } + +func Tempfile(prefix string) (*os.File, string) { + file, err := ioutil.TempFile("", prefix) + if err != nil { + PanicCrisis(err) + } + return file, file.Name() +} + +func Prompt(prompt string, defaultValue string) (string, error) { + fmt.Print(prompt) + reader := bufio.NewReader(os.Stdin) + line, err := reader.ReadString('\n') + if err != nil { + return defaultValue, err + } else { + line = strings.TrimSpace(line) + if line == "" { + return defaultValue, nil + } + return line, nil + } +} diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/common/service.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/common/service.go index fd6f8546630845101c5827cd03e9b569f62e23ae..e000b439411e05ba69421f2889c80b59d36fa0a2 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/common/service.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/common/service.go @@ -23,13 +23,13 @@ func NewFooService() *FooService { return fs } -func (fs *FooService) OnStart() { +func (fs *FooService) OnStart() error { fs.BaseService.OnStart() // Always call the overridden method. // initialize private fields // start subroutines, etc. } -func (fs *FooService) OnStop() { +func (fs *FooService) OnStop() error { fs.BaseService.OnStop() // Always call the overridden method. // close/destroy private fields // stop subroutines, etc. @@ -42,8 +42,8 @@ import "sync/atomic" import "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/log15" type Service interface { - Start() bool - OnStart() + Start() (bool, error) + OnStart() error Stop() bool OnStop() @@ -72,33 +72,43 @@ func NewBaseService(log log15.Logger, name string, impl Service) *BaseService { } // Implements Servce -func (bs *BaseService) Start() bool { +func (bs *BaseService) Start() (bool, error) { if atomic.CompareAndSwapUint32(&bs.started, 0, 1) { if atomic.LoadUint32(&bs.stopped) == 1 { - bs.log.Warn(Fmt("Not starting %v -- already stopped", bs.name), "impl", bs.impl) - return false + if bs.log != nil { + bs.log.Warn(Fmt("Not starting %v -- already stopped", bs.name), "impl", bs.impl) + } + return false, nil } else { - bs.log.Notice(Fmt("Starting %v", bs.name), "impl", bs.impl) + if bs.log != nil { + bs.log.Notice(Fmt("Starting %v", bs.name), "impl", bs.impl) + } } - bs.impl.OnStart() - return true + err := bs.impl.OnStart() + return true, err } else { - bs.log.Info(Fmt("Not starting %v -- already started", bs.name), "impl", bs.impl) - return false + if bs.log != nil { + bs.log.Info(Fmt("Not starting %v -- already started", bs.name), "impl", bs.impl) + } + return false, nil } } // Implements Service -func (bs *BaseService) OnStart() {} +func (bs *BaseService) OnStart() error { return nil } // Implements Service func (bs *BaseService) Stop() bool { if atomic.CompareAndSwapUint32(&bs.stopped, 0, 1) { - bs.log.Notice(Fmt("Stopping %v", bs.name), "impl", bs.impl) + if bs.log != nil { + bs.log.Notice(Fmt("Stopping %v", bs.name), "impl", bs.impl) + } bs.impl.OnStop() return true } else { - bs.log.Notice(Fmt("Not stopping %v", bs.name), "impl", bs.impl) + if bs.log != nil { + bs.log.Notice(Fmt("Not stopping %v", bs.name), "impl", bs.impl) + } return false } } @@ -131,11 +141,14 @@ func NewQuitService(log log15.Logger, name string, impl Service) *QuitService { } // NOTE: when overriding OnStart, must call .QuitService.OnStart(). -func (qs *QuitService) OnStart() { +func (qs *QuitService) OnStart() error { qs.Quit = make(chan struct{}) + return nil } // NOTE: when overriding OnStop, must call .QuitService.OnStop(). func (qs *QuitService) OnStop() { - close(qs.Quit) + if qs.Quit != nil { + close(qs.Quit) + } } diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/config/config.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/config/config.go index 27e2037a5b6284f4fee39968d4d8eecac0e9d9a1..43963e25ad7f5aa302db7df3e3d26dab5e160850 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/config/config.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/config/config.go @@ -1,30 +1,10 @@ package config import ( - "bufio" - "fmt" - "os" - "strings" "sync" "time" ) -func Prompt(prompt string, defaultValue string) string { - fmt.Print(prompt) - reader := bufio.NewReader(os.Stdin) - line, err := reader.ReadString('\n') - if err != nil { - log.Warn("Error reading stdin", "err", err) - return defaultValue - } else { - line = strings.TrimSpace(line) - if line == "" { - return defaultValue - } - return line - } -} - type Config interface { Get(key string) interface{} GetBool(key string) bool diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/config/tendermint/config.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/config/tendermint/config.go index 802a27cd4e0980ed08a22dd1ef7f527d3062eb22..1a6b0225d78e20ab574f839f8acfc207723eec96 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/config/tendermint/config.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/config/tendermint/config.go @@ -1,7 +1,7 @@ package tendermint import ( - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/naoina/toml" + "github.com/naoina/toml" "os" "path" "strings" @@ -30,8 +30,8 @@ func initTMRoot(rootDir string) { // Write default config file if missing. if !FileExists(configFilePath) { // Ask user for moniker - moniker := cfg.Prompt("Type hostname: ", "anonymous") - MustWriteFile(configFilePath, []byte(defaultConfig(moniker))) + // moniker := cfg.Prompt("Type hostname: ", "anonymous") + MustWriteFile(configFilePath, []byte(defaultConfig("anonymous"))) } if !FileExists(genesisFilePath) { MustWriteFile(genesisFilePath, []byte(defaultGenesis)) @@ -54,16 +54,13 @@ func GetConfig(rootDir string) cfg.Config { if mapConfig.IsSet("chain_id") { Exit("Cannot set 'chain_id' via config.toml") } - if mapConfig.IsSet("version") { - Exit("Cannot set 'version' via config.toml") - } - mapConfig.SetDefault("chain_id", "tendermint_testnet_9") - mapConfig.SetDefault("version", "0.5.0") // JAE: encrypted p2p! + mapConfig.SetDefault("chain_id", "tendermint_testnet_10") mapConfig.SetDefault("genesis_file", rootDir+"/genesis.json") mapConfig.SetDefault("moniker", "anonymous") mapConfig.SetDefault("node_laddr", "0.0.0.0:46656") // mapConfig.SetDefault("seeds", "goldenalchemist.chaintest.net:46656") mapConfig.SetDefault("fast_sync", true) + mapConfig.SetDefault("skip_upnp", false) mapConfig.SetDefault("addrbook_file", rootDir+"/addrbook.json") mapConfig.SetDefault("priv_validator_file", rootDir+"/priv_validator.json") mapConfig.SetDefault("db_backend", "leveldb") @@ -88,7 +85,7 @@ node_laddr = "0.0.0.0:46656" seeds = "goldenalchemist.chaintest.net:46656" fast_sync = true db_backend = "leveldb" -log_level = "debug" +log_level = "notice" rpc_laddr = "0.0.0.0:46657" ` @@ -98,81 +95,61 @@ func defaultConfig(moniker string) (defaultConfig string) { } var defaultGenesis = `{ - "chain_id": "tendermint_testnet_9", + "chain_id": "tendermint_testnet_11", "accounts": [ { "address": "9FCBA7F840A0BFEBBE755E853C9947270A912D04", - "amount": 690000000000 + "amount": 1995999998000000 + }, + { + "address": "964B1493BBE3312278B7DEB94C39149F7899A345", + "amount": 100000000000000 + }, + { + "address": "B9FA4AB462B9C6BF6A62DB4AE77C9E7087209A04", + "amount": 1000000000000 + }, + { + "address": "F171824590D69386F709E7B6704B369C5A370D60", + "amount": 1000000000000 + }, + { + "address": "56EFE746A13D9A6054AC89C3E2A361C2DB8B9EAE", + "amount": 1000000000000 + }, + { + "address": "7C2E032D8407EDF66A04D88CF0E1D9B15D98AE2D", + "amount": 1000000000000 }, { "address": "A88A61069B6660F30F65E8786AFDD4F1D8F625E9", - "amount": 1000000 - }, + "amount": 1000000 + }, { "address": "EE2EE9247973B4AFC3867CFE5F415410AC251B61", - "amount": 1000000 - } + "amount": 1000000 + } ], "validators": [ { "pub_key": [1, "178EC6008A4364508979C70CBF100BD4BCBAA12DDE6251F5F486B4FD09014F06"], - "amount": 5000000000, - "unbond_to": [ - { - "address": "93E243AC8A01F723DE353A4FA1ED911529CCB6E5", - "amount": 5000000000 - } - ] + "amount": 100000000000 }, { "pub_key": [1, "2A77777CC51467DE42350D4A8F34720D527734189BE64C7A930DD169E1FED3C6"], - "amount": 5000000000, - "unbond_to": [ - { - "address": "93E243AC8A01F723DE353A4FA1ED911529CCB6E5", - "amount": 5000000000 - } - ] + "amount": 100000000000 }, { "pub_key": [1, "3718E69D09B11B3AD3FA31AEF07EC416D2AEED241CACE7B0F30AE9803FFB0F08"], - "amount": 5000000000, - "unbond_to": [ - { - "address": "93E243AC8A01F723DE353A4FA1ED911529CCB6E5", - "amount": 5000000000 - } - ] + "amount": 100000000000 }, { "pub_key": [1, "C6B0440DEACD1E4CF1C736CEB8E38E788B700BA2B2045A55CB657A455CF5F889"], - "amount": 5000000000, - "unbond_to": [ - { - "address": "93E243AC8A01F723DE353A4FA1ED911529CCB6E5", - "amount": 5000000000 - } - ] + "amount": 100000000000 }, { "pub_key": [1, "3BA1190D54F91EFBF8B0125F7EC116AD4BA2894B6EE38564A5D5FD3230D91F7B"], - "amount": 5000000000, - "unbond_to": [ - { - "address": "93E243AC8A01F723DE353A4FA1ED911529CCB6E5", - "amount": 5000000000 - } - ] - }, - { - "pub_key": [1, "E56663353D01C58A1D4CDB4D14B70C2E3335BE1EBB6C3F697AF7882C03837962"], - "amount": 5000000000, - "unbond_to": [ - { - "address": "9E54C9ECA9A3FD5D4496696818DA17A9E17F69DA", - "amount": 5000000000 - } - ] + "amount": 100000000000 } ] }` diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/config/tendermint/genesis.json b/Godeps/_workspace/src/github.com/tendermint/tendermint/config/tendermint/genesis.json new file mode 100644 index 0000000000000000000000000000000000000000..eca00696edb4414df42fe6770cc23cde5a758529 --- /dev/null +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/config/tendermint/genesis.json @@ -0,0 +1,75 @@ +{ + "chain_id": "tendermint_testnet_11.c", + "accounts": [ + { + "address": "9FCBA7F840A0BFEBBE755E853C9947270A912D04", + "amount": 1991999998000000 + }, + { + "address": "964B1493BBE3312278B7DEB94C39149F7899A345", + "amount": 100000000000000 + }, + { + "address": "B9FA4AB462B9C6BF6A62DB4AE77C9E7087209A04", + "amount": 1000000000000 + }, + { + "address": "F171824590D69386F709E7B6704B369C5A370D60", + "amount": 1000000000000 + }, + { + "address": "56EFE746A13D9A6054AC89C3E2A361C2DB8B9EAE", + "amount": 1000000000000 + }, + { + "address": "7C2E032D8407EDF66A04D88CF0E1D9B15D98AE2D", + "amount": 1000000000000 + }, + { + "address": "636EF5823E082AD66EBC203FD4DFB1031F0C61CA", + "amount": 1000000000000 + }, + { + "address": "9008419E6351360A59B124E707E4CA2A5BFB9BE6", + "amount": 1000000000000 + }, + { + "address": "C78F48919B8A4030AD3E5ED643F8D2302E41953D", + "amount": 1000000000000 + }, + { + "address": "5290AC90CE2422DDC3F91F6A246F7E3C542EA51A", + "amount": 1000000000000 + }, + { + "address": "A88A61069B6660F30F65E8786AFDD4F1D8F625E9", + "amount": 1000000 + }, + { + "address": "EE2EE9247973B4AFC3867CFE5F415410AC251B61", + "amount": 1000000 + } + ], + "validators": [ + { + "pub_key": [1, "178EC6008A4364508979C70CBF100BD4BCBAA12DDE6251F5F486B4FD09014F06"], + "amount": 100000000000 + }, + { + "pub_key": [1, "2A77777CC51467DE42350D4A8F34720D527734189BE64C7A930DD169E1FED3C6"], + "amount": 100000000000 + }, + { + "pub_key": [1, "3718E69D09B11B3AD3FA31AEF07EC416D2AEED241CACE7B0F30AE9803FFB0F08"], + "amount": 100000000000 + }, + { + "pub_key": [1, "C6B0440DEACD1E4CF1C736CEB8E38E788B700BA2B2045A55CB657A455CF5F889"], + "amount": 100000000000 + }, + { + "pub_key": [1, "3BA1190D54F91EFBF8B0125F7EC116AD4BA2894B6EE38564A5D5FD3230D91F7B"], + "amount": 100000000000 + } + ] +} diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/config/tendermint_test/config.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/config/tendermint_test/config.go index f3eb7316cc8173f531ad7b2986163c907e0b1a55..108d37a3f9ac8fd758fbcfc3ed14c374ef45c432 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/config/tendermint_test/config.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/config/tendermint_test/config.go @@ -3,7 +3,7 @@ package tendermint_test import ( - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/naoina/toml" + "github.com/naoina/toml" "os" "path" "strings" @@ -35,8 +35,8 @@ func initTMRoot(rootDir string) { // Write default config file if missing. if !FileExists(configFilePath) { // Ask user for moniker - moniker := cfg.Prompt("Type hostname: ", "anonymous") - MustWriteFile(configFilePath, []byte(defaultConfig(moniker))) + // moniker := cfg.Prompt("Type hostname: ", "anonymous") + MustWriteFile(configFilePath, []byte(defaultConfig("anonymous"))) } if !FileExists(genesisFilePath) { MustWriteFile(genesisFilePath, []byte(defaultGenesis)) @@ -59,15 +59,12 @@ func GetConfig(rootDir string) cfg.Config { if mapConfig.IsSet("chain_id") { Exit("Cannot set 'chain_id' via config.toml") } - if mapConfig.IsSet("version") { - Exit("Cannot set 'version' via config.toml") - } mapConfig.SetDefault("chain_id", "tendermint_test") - mapConfig.SetDefault("version", "0.5.0") mapConfig.SetDefault("genesis_file", rootDir+"/genesis.json") mapConfig.SetDefault("moniker", "anonymous") mapConfig.SetDefault("node_laddr", "0.0.0.0:36656") mapConfig.SetDefault("fast_sync", false) + mapConfig.SetDefault("skip_upnp", true) mapConfig.SetDefault("addrbook_file", rootDir+"/addrbook.json") mapConfig.SetDefault("priv_validator_file", rootDir+"/priv_validator.json") mapConfig.SetDefault("db_backend", "memdb") diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/consensus/height_vote_set.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/consensus/height_vote_set.go index f0683ae878b37c40abb1742a337e62c7f1acb11c..37e6ad6231e09455bf597abd7d2f68b06881a7b2 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/consensus/height_vote_set.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/consensus/height_vote_set.go @@ -5,13 +5,12 @@ import ( "sync" . "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/common" - sm "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/state" "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/types" ) type RoundVoteSet struct { - Prevotes *VoteSet - Precommits *VoteSet + Prevotes *types.VoteSet + Precommits *types.VoteSet } /* @@ -28,7 +27,7 @@ peer to prevent abuse. */ type HeightVoteSet struct { height int - valSet *sm.ValidatorSet + valSet *types.ValidatorSet mtx sync.Mutex round int // max tracked round @@ -36,7 +35,7 @@ type HeightVoteSet struct { peerCatchupRounds map[string]int // keys: peer.Key; values: round } -func NewHeightVoteSet(height int, valSet *sm.ValidatorSet) *HeightVoteSet { +func NewHeightVoteSet(height int, valSet *types.ValidatorSet) *HeightVoteSet { hvs := &HeightVoteSet{ height: height, valSet: valSet, @@ -79,8 +78,8 @@ func (hvs *HeightVoteSet) addRound(round int) { PanicSanity("addRound() for an existing round") } log.Debug("addRound(round)", "round", round) - prevotes := NewVoteSet(hvs.height, round, types.VoteTypePrevote, hvs.valSet) - precommits := NewVoteSet(hvs.height, round, types.VoteTypePrecommit, hvs.valSet) + prevotes := types.NewVoteSet(hvs.height, round, types.VoteTypePrevote, hvs.valSet) + precommits := types.NewVoteSet(hvs.height, round, types.VoteTypePrecommit, hvs.valSet) hvs.roundVoteSets[round] = RoundVoteSet{ Prevotes: prevotes, Precommits: precommits, @@ -89,7 +88,7 @@ func (hvs *HeightVoteSet) addRound(round int) { // Duplicate votes return added=false, err=nil. // By convention, peerKey is "" if origin is self. -func (hvs *HeightVoteSet) AddByAddress(address []byte, vote *types.Vote, peerKey string) (added bool, index int, err error) { +func (hvs *HeightVoteSet) AddByIndex(valIndex int, vote *types.Vote, peerKey string) (added bool, address []byte, err error) { hvs.mtx.Lock() defer hvs.mtx.Unlock() voteSet := hvs.getVoteSet(vote.Round, vote.Type) @@ -105,23 +104,23 @@ func (hvs *HeightVoteSet) AddByAddress(address []byte, vote *types.Vote, peerKey } return } - added, index, err = voteSet.AddByAddress(address, vote) + added, address, err = voteSet.AddByIndex(valIndex, vote) return } -func (hvs *HeightVoteSet) Prevotes(round int) *VoteSet { +func (hvs *HeightVoteSet) Prevotes(round int) *types.VoteSet { hvs.mtx.Lock() defer hvs.mtx.Unlock() return hvs.getVoteSet(round, types.VoteTypePrevote) } -func (hvs *HeightVoteSet) Precommits(round int) *VoteSet { +func (hvs *HeightVoteSet) Precommits(round int) *types.VoteSet { hvs.mtx.Lock() defer hvs.mtx.Unlock() return hvs.getVoteSet(round, types.VoteTypePrecommit) } -// Last round that has +2/3 prevotes for a particular block or nik. +// Last round that has +2/3 prevotes for a particular block or nil. // Returns -1 if no such round exists. func (hvs *HeightVoteSet) POLRound() int { hvs.mtx.Lock() @@ -134,7 +133,7 @@ func (hvs *HeightVoteSet) POLRound() int { return -1 } -func (hvs *HeightVoteSet) getVoteSet(round int, type_ byte) *VoteSet { +func (hvs *HeightVoteSet) getVoteSet(round int, type_ byte) *types.VoteSet { log.Debug("getVoteSet(round)", "round", round, "type", type_) rvs, ok := hvs.roundVoteSets[round] if !ok { diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/consensus/reactor.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/consensus/reactor.go index 218ff002dd4310a43487df55fffca357b78db1bc..0b4378ee0fe4570c2a74a96d640df4d83a1a84ba 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/consensus/reactor.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/consensus/reactor.go @@ -10,7 +10,6 @@ import ( bc "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/blockchain" . "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/common" - . "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/consensus/types" "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/events" "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/p2p" sm "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/state" @@ -49,13 +48,17 @@ func NewConsensusReactor(consensusState *ConsensusState, blockStore *bc.BlockSto return conR } -func (conR *ConsensusReactor) OnStart() { +func (conR *ConsensusReactor) OnStart() error { log.Notice("ConsensusReactor ", "fastSync", conR.fastSync) conR.BaseReactor.OnStart() if !conR.fastSync { - conR.conS.Start() + _, err := conR.conS.Start() + if err != nil { + return err + } } go conR.broadcastNewRoundStepRoutine() + return nil } func (conR *ConsensusReactor) OnStop() { @@ -69,7 +72,7 @@ func (conR *ConsensusReactor) SwitchToConsensus(state *sm.State) { log.Notice("SwitchToConsensus") // NOTE: The line below causes broadcastNewRoundStepRoutine() to // broadcast a NewRoundStepMessage. - conR.conS.updateToState(state, false) + conR.conS.updateToState(state) conR.fastSync = false conR.conS.Start() } @@ -79,17 +82,17 @@ func (conR *ConsensusReactor) GetChannels() []*p2p.ChannelDescriptor { // TODO optimize return []*p2p.ChannelDescriptor{ &p2p.ChannelDescriptor{ - Id: StateChannel, + ID: StateChannel, Priority: 5, SendQueueCapacity: 100, }, &p2p.ChannelDescriptor{ - Id: DataChannel, + ID: DataChannel, Priority: 5, SendQueueCapacity: 2, }, &p2p.ChannelDescriptor{ - Id: VoteChannel, + ID: VoteChannel, Priority: 5, SendQueueCapacity: 40, }, @@ -128,27 +131,27 @@ func (conR *ConsensusReactor) RemovePeer(peer *p2p.Peer, reason interface{}) { // Implements Reactor // NOTE: We process these messages even when we're fast_syncing. -func (conR *ConsensusReactor) Receive(chId byte, peer *p2p.Peer, msgBytes []byte) { +func (conR *ConsensusReactor) Receive(chID byte, peer *p2p.Peer, msgBytes []byte) { if !conR.IsRunning() { - log.Debug("Receive", "channel", chId, "peer", peer, "bytes", msgBytes) + log.Debug("Receive", "channel", chID, "peer", peer, "bytes", msgBytes) return } - // Get round state - rs := conR.conS.GetRoundState() + // Get peer states ps := peer.Data.Get(PeerStateKey).(*PeerState) _, msg, err := DecodeMessage(msgBytes) if err != nil { - log.Warn("Error decoding message", "channel", chId, "peer", peer, "msg", msg, "error", err, "bytes", msgBytes) + log.Warn("Error decoding message", "channel", chID, "peer", peer, "msg", msg, "error", err, "bytes", msgBytes) + // TODO punish peer? return } - log.Debug("Receive", "channel", chId, "peer", peer, "msg", msg, "rsHeight", rs.Height) + log.Debug("Receive", "channel", chID, "peer", peer, "msg", msg) - switch chId { + switch chID { case StateChannel: switch msg := msg.(type) { case *NewRoundStepMessage: - ps.ApplyNewRoundStepMessage(msg, rs) + ps.ApplyNewRoundStepMessage(msg) case *CommitStepMessage: ps.ApplyCommitStepMessage(msg) case *HasVoteMessage: @@ -182,54 +185,37 @@ func (conR *ConsensusReactor) Receive(chId byte, peer *p2p.Peer, msgBytes []byte } switch msg := msg.(type) { case *VoteMessage: - vote := msg.Vote - var validators *sm.ValidatorSet - if rs.Height == vote.Height { - validators = rs.Validators - } else if rs.Height == vote.Height+1 { - if !(rs.Step == RoundStepNewHeight && vote.Type == types.VoteTypePrecommit) { - return // Wrong height, not a LastCommit straggler commit. - } - validators = rs.LastValidators - } else { - return // Wrong height. Not necessarily a bad peer. + vote, valIndex := msg.Vote, msg.ValidatorIndex + + // attempt to add the vote and dupeout the validator if its a duplicate signature + added, err := conR.conS.TryAddVote(valIndex, vote, peer.Key) + if err == ErrAddingVote { + // TODO: punish peer + } else if err != nil { + return } - // We have vote/validators. Height may not be rs.Height - - address, _ := validators.GetByIndex(msg.ValidatorIndex) - added, index, err := conR.conS.AddVote(address, vote, peer.Key) - if err != nil { - // If conflicting sig, broadcast evidence tx for slashing. Else punish peer. - if errDupe, ok := err.(*types.ErrVoteConflictingSignature); ok { - log.Warn("Found conflicting vote. Publish evidence") - evidenceTx := &types.DupeoutTx{ - Address: address, - VoteA: *errDupe.VoteA, - VoteB: *errDupe.VoteB, - } - conR.conS.mempoolReactor.BroadcastTx(evidenceTx) // shouldn't need to check returned err - } else { - // Probably an invalid signature. Bad peer. - log.Warn("Error attempting to add vote", "error", err) - // TODO: punish peer - } - } - ps.EnsureVoteBitArrays(rs.Height, rs.Validators.Size()) - ps.EnsureVoteBitArrays(rs.Height-1, rs.LastCommit.Size()) - ps.SetHasVote(vote, index) + cs := conR.conS + cs.mtx.Lock() + height, valSize, lastCommitSize := cs.Height, cs.Validators.Size(), cs.LastCommit.Size() + cs.mtx.Unlock() + ps.EnsureVoteBitArrays(height, valSize) + ps.EnsureVoteBitArrays(height-1, lastCommitSize) + ps.SetHasVote(vote, valIndex) + if added { // If rs.Height == vote.Height && rs.Round < vote.Round, // the peer is sending us CatchupCommit precommits. // We could make note of this and help filter in broadcastHasVoteMessage(). - conR.broadcastHasVoteMessage(vote, index) + conR.broadcastHasVoteMessage(vote, valIndex) } default: + // don't punish (leave room for soft upgrades) log.Warn(Fmt("Unknown message type %v", reflect.TypeOf(msg))) } default: - log.Warn(Fmt("Unknown channel %X", chId)) + log.Warn(Fmt("Unknown channel %X", chID)) } if err != nil { @@ -264,7 +250,7 @@ func (conR *ConsensusReactor) broadcastHasVoteMessage(vote *types.Vote, index in } // Sets our private validator account for signing votes. -func (conR *ConsensusReactor) SetPrivValidator(priv *sm.PrivValidator) { +func (conR *ConsensusReactor) SetPrivValidator(priv *types.PrivValidator) { conR.conS.SetPrivValidator(priv) } @@ -342,7 +328,7 @@ OUTER_LOOP: // Send proposal Block parts? if rs.ProposalBlockParts.HasHeader(prs.ProposalBlockPartsHeader) { - //log.Debug("ProposalBlockParts matched", "blockParts", prs.ProposalBlockParts) + //log.Info("ProposalBlockParts matched", "blockParts", prs.ProposalBlockParts) if index, ok := rs.ProposalBlockParts.BitArray().Sub(prs.ProposalBlockParts.Copy()).PickRandom(); ok { part := rs.ProposalBlockParts.GetPart(index) msg := &BlockPartMessage{ @@ -358,12 +344,12 @@ OUTER_LOOP: // If the peer is on a previous height, help catch up. if (0 < prs.Height) && (prs.Height < rs.Height) { - //log.Debug("Data catchup", "height", rs.Height, "peerHeight", prs.Height, "peerProposalBlockParts", prs.ProposalBlockParts) + //log.Info("Data catchup", "height", rs.Height, "peerHeight", prs.Height, "peerProposalBlockParts", prs.ProposalBlockParts) if index, ok := prs.ProposalBlockParts.Not().PickRandom(); ok { // Ensure that the peer's PartSetHeader is correct blockMeta := conR.blockStore.LoadBlockMeta(prs.Height) if !blockMeta.PartsHeader.Equals(prs.ProposalBlockPartsHeader) { - log.Debug("Peer ProposalBlockPartsHeader mismatch, sleeping", + log.Info("Peer ProposalBlockPartsHeader mismatch, sleeping", "peerHeight", prs.Height, "blockPartsHeader", blockMeta.PartsHeader, "peerBlockPartsHeader", prs.ProposalBlockPartsHeader) time.Sleep(peerGossipSleepDuration) continue OUTER_LOOP @@ -386,7 +372,7 @@ OUTER_LOOP: ps.SetHasProposalBlockPart(prs.Height, prs.Round, index) continue OUTER_LOOP } else { - //log.Debug("No parts to send in catch-up, sleeping") + //log.Info("No parts to send in catch-up, sleeping") time.Sleep(peerGossipSleepDuration) continue OUTER_LOOP } @@ -394,7 +380,7 @@ OUTER_LOOP: // If height and round don't match, sleep. if (rs.Height != prs.Height) || (rs.Round != prs.Round) { - //log.Debug("Peer Height|Round mismatch, sleeping", "peerHeight", prs.Height, "peerRound", prs.Round, "peer", peer) + //log.Info("Peer Height|Round mismatch, sleeping", "peerHeight", prs.Height, "peerRound", prs.Round, "peer", peer) time.Sleep(peerGossipSleepDuration) continue OUTER_LOOP } @@ -464,35 +450,35 @@ OUTER_LOOP: // If there are lastCommits to send... if prs.Step == RoundStepNewHeight { if ps.PickSendVote(rs.LastCommit) { - log.Debug("Picked rs.LastCommit to send") + log.Info("Picked rs.LastCommit to send") continue OUTER_LOOP } } // If there are prevotes to send... if rs.Round == prs.Round && prs.Step <= RoundStepPrevote { if ps.PickSendVote(rs.Votes.Prevotes(rs.Round)) { - log.Debug("Picked rs.Prevotes(rs.Round) to send") + log.Info("Picked rs.Prevotes(rs.Round) to send") continue OUTER_LOOP } } // If there are precommits to send... if rs.Round == prs.Round && prs.Step <= RoundStepPrecommit { if ps.PickSendVote(rs.Votes.Precommits(rs.Round)) { - log.Debug("Picked rs.Precommits(rs.Round) to send") + log.Info("Picked rs.Precommits(rs.Round) to send") continue OUTER_LOOP } } // If there are prevotes to send for the last round... if rs.Round == prs.Round+1 && prs.Step <= RoundStepPrevote { if ps.PickSendVote(rs.Votes.Prevotes(prs.Round)) { - log.Debug("Picked rs.Prevotes(prs.Round) to send") + log.Info("Picked rs.Prevotes(prs.Round) to send") continue OUTER_LOOP } } // If there are precommits to send for the last round... if rs.Round == prs.Round+1 && prs.Step <= RoundStepPrecommit { if ps.PickSendVote(rs.Votes.Precommits(prs.Round)) { - log.Debug("Picked rs.Precommits(prs.Round) to send") + log.Info("Picked rs.Precommits(prs.Round) to send") continue OUTER_LOOP } } @@ -500,7 +486,7 @@ OUTER_LOOP: if 0 <= prs.ProposalPOLRound { if polPrevotes := rs.Votes.Prevotes(prs.ProposalPOLRound); polPrevotes != nil { if ps.PickSendVote(polPrevotes) { - log.Debug("Picked rs.Prevotes(prs.ProposalPOLRound) to send") + log.Info("Picked rs.Prevotes(prs.ProposalPOLRound) to send") continue OUTER_LOOP } } @@ -511,7 +497,7 @@ OUTER_LOOP: // If peer is lagging by height 1, send LastCommit. if prs.Height != 0 && rs.Height == prs.Height+1 { if ps.PickSendVote(rs.LastCommit) { - log.Debug("Picked rs.LastCommit to send") + log.Info("Picked rs.LastCommit to send") continue OUTER_LOOP } } @@ -522,9 +508,9 @@ OUTER_LOOP: // Load the block validation for prs.Height, // which contains precommit signatures for prs.Height. validation := conR.blockStore.LoadBlockValidation(prs.Height) - log.Debug("Loaded BlockValidation for catch-up", "height", prs.Height, "validation", validation) + log.Info("Loaded BlockValidation for catch-up", "height", prs.Height, "validation", validation) if ps.PickSendVote(validation) { - log.Debug("Picked Catchup validation to send") + log.Info("Picked Catchup validation to send") continue OUTER_LOOP } } @@ -532,7 +518,7 @@ OUTER_LOOP: if sleeping == 0 { // We sent nothing. Sleep... sleeping = 1 - log.Debug("No votes to send, sleeping", "peer", peer, + log.Info("No votes to send, sleeping", "peer", peer, "localPV", rs.Votes.Prevotes(rs.Round).BitArray(), "peerPV", prs.Prevotes, "localPC", rs.Votes.Precommits(rs.Round).BitArray(), "peerPC", prs.Precommits) } else if sleeping == 2 { @@ -550,19 +536,19 @@ OUTER_LOOP: // Read only when returned by PeerState.GetRoundState(). type PeerRoundState struct { Height int // Height peer is at - Round int // Round peer is at + Round int // Round peer is at, -1 if unknown. Step RoundStepType // Step peer is at StartTime time.Time // Estimated start of round 0 at this height Proposal bool // True if peer has proposal for this round ProposalBlockPartsHeader types.PartSetHeader // ProposalBlockParts *BitArray // - ProposalPOLRound int // -1 if none + ProposalPOLRound int // Proposal's POL round. -1 if none. ProposalPOL *BitArray // nil until ProposalPOLMessage received. Prevotes *BitArray // All votes peer has for this round Precommits *BitArray // All precommits peer has for this round - LastCommitRound int // Round of commit for last height. + LastCommitRound int // Round of commit for last height. -1 if none. LastCommit *BitArray // All commit precommits of commit for last height. - CatchupCommitRound int // Round that we believe commit round is. + CatchupCommitRound int // Round that we believe commit round is. -1 if none. CatchupCommit *BitArray // All commit precommits peer has for this height } @@ -581,7 +567,15 @@ type PeerState struct { } func NewPeerState(peer *p2p.Peer) *PeerState { - return &PeerState{Peer: peer} + return &PeerState{ + Peer: peer, + PeerRoundState: PeerRoundState{ + Round: -1, + ProposalPOLRound: -1, + LastCommitRound: -1, + CatchupCommitRound: -1, + }, + } } // Returns an atomic snapshot of the PeerRoundState. @@ -594,7 +588,7 @@ func (ps *PeerState) GetRoundState() *PeerRoundState { return &prs } -func (ps *PeerState) SetHasProposal(proposal *Proposal) { +func (ps *PeerState) SetHasProposal(proposal *types.Proposal) { ps.mtx.Lock() defer ps.mtx.Unlock() @@ -768,23 +762,23 @@ func (ps *PeerState) setHasVote(height int, round int, type_ byte, index int) { switch type_ { case types.VoteTypePrevote: ps.Prevotes.SetIndex(index, true) - log.Debug("SetHasVote(round-match)", "prevotes", ps.Prevotes, "index", index) + log.Info("SetHasVote(round-match)", "prevotes", ps.Prevotes, "index", index) case types.VoteTypePrecommit: ps.Precommits.SetIndex(index, true) - log.Debug("SetHasVote(round-match)", "precommits", ps.Precommits, "index", index) + log.Info("SetHasVote(round-match)", "precommits", ps.Precommits, "index", index) } } else if ps.CatchupCommitRound == round { switch type_ { case types.VoteTypePrevote: case types.VoteTypePrecommit: ps.CatchupCommit.SetIndex(index, true) - log.Debug("SetHasVote(CatchupCommit)", "precommits", ps.Precommits, "index", index) + log.Info("SetHasVote(CatchupCommit)", "precommits", ps.Precommits, "index", index) } } else if ps.ProposalPOLRound == round { switch type_ { case types.VoteTypePrevote: ps.ProposalPOL.SetIndex(index, true) - log.Debug("SetHasVote(ProposalPOL)", "prevotes", ps.Prevotes, "index", index) + log.Info("SetHasVote(ProposalPOL)", "prevotes", ps.Prevotes, "index", index) case types.VoteTypePrecommit: } } @@ -794,7 +788,7 @@ func (ps *PeerState) setHasVote(height int, round int, type_ byte, index int) { case types.VoteTypePrevote: case types.VoteTypePrecommit: ps.LastCommit.SetIndex(index, true) - log.Debug("setHasVote(LastCommit)", "lastCommit", ps.LastCommit, "index", index) + log.Info("setHasVote(LastCommit)", "lastCommit", ps.LastCommit, "index", index) } } } else { @@ -802,7 +796,7 @@ func (ps *PeerState) setHasVote(height int, round int, type_ byte, index int) { } } -func (ps *PeerState) ApplyNewRoundStepMessage(msg *NewRoundStepMessage, rs *RoundState) { +func (ps *PeerState) ApplyNewRoundStepMessage(msg *NewRoundStepMessage) { ps.mtx.Lock() defer ps.mtx.Unlock() @@ -960,7 +954,7 @@ func (m *CommitStepMessage) String() string { //------------------------------------- type ProposalMessage struct { - Proposal *Proposal + Proposal *types.Proposal } func (m *ProposalMessage) String() string { diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/consensus/state.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/consensus/state.go index 32cec68c1abd571e74ffe6e56917acdef890c41d..72ec17c6b4bb0df9a0e86900bc755e5f7d941f9c 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/consensus/state.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/consensus/state.go @@ -89,7 +89,7 @@ it locks (changes lock to) that block and precommits that block. * Else, if the validator had seen +2/3 of prevotes for <nil>, it unlocks and precommits <nil>. * Else, if +2/3 of prevotes for a particular block or <nil> is not received on time, - it precommits what it's locked on, or <nil>. + it precommits <nil>. * The Precommit step ends: * After +2/3 precommits for a particular block. --> goto Commit(H) * After +2/3 precommits for <nil>. --> goto NewRound(H,R+1) @@ -160,7 +160,6 @@ import ( acm "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/account" bc "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/blockchain" . "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/common" - . "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/consensus/types" "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/events" mempl "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/mempool" sm "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/state" @@ -180,6 +179,8 @@ var ( var ( ErrInvalidProposalSignature = errors.New("Error invalid proposal signature") ErrInvalidProposalPOLRound = errors.New("Error invalid proposal POL round") + ErrAddingVote = errors.New("Error adding vote") + ErrVoteHeightMismatch = errors.New("Error vote height mismatch") ) //----------------------------------------------------------------------------- @@ -231,16 +232,33 @@ type RoundState struct { Step RoundStepType StartTime time.Time CommitTime time.Time // Subjective time when +2/3 precommits for Block at Round were found - Validators *sm.ValidatorSet - Proposal *Proposal + Validators *types.ValidatorSet + Proposal *types.Proposal ProposalBlock *types.Block ProposalBlockParts *types.PartSet LockedRound int LockedBlock *types.Block LockedBlockParts *types.PartSet Votes *HeightVoteSet - LastCommit *VoteSet // Last precommits at Height-1 - LastValidators *sm.ValidatorSet + CommitRound int // + LastCommit *types.VoteSet // Last precommits at Height-1 + LastValidators *types.ValidatorSet +} + +func (rs *RoundState) RoundStateEvent() *types.EventDataRoundState { + return &types.EventDataRoundState{ + CurrentTime: time.Now(), + Height: rs.Height, + Round: rs.Round, + Step: rs.Step.String(), + StartTime: rs.StartTime, + CommitTime: rs.CommitTime, + Proposal: rs.Proposal, + ProposalBlock: rs.ProposalBlock, + LockedRound: rs.LockedRound, + LockedBlock: rs.LockedBlock, + POLRound: rs.Votes.POLRound(), + } } func (rs *RoundState) String() string { @@ -288,7 +306,7 @@ type ConsensusState struct { blockStore *bc.BlockStore mempoolReactor *mempl.MempoolReactor - privValidator *sm.PrivValidator + privValidator *types.PrivValidator newStepCh chan *RoundState mtx sync.Mutex @@ -307,7 +325,7 @@ func NewConsensusState(state *sm.State, blockStore *bc.BlockStore, mempoolReacto mempoolReactor: mempoolReactor, newStepCh: make(chan *RoundState, 10), } - cs.updateToState(state, true) + cs.updateToState(state) // Don't call scheduleRound0 yet. // We do that upon Start(). cs.maybeRebond() @@ -322,7 +340,7 @@ func (cs *ConsensusState) reconstructLastCommit(state *sm.State) { if state.LastBlockHeight == 0 { return } - lastPrecommits := NewVoteSet(state.LastBlockHeight, 0, types.VoteTypePrecommit, state.LastBondedValidators) + lastPrecommits := types.NewVoteSet(state.LastBlockHeight, 0, types.VoteTypePrecommit, state.LastBondedValidators) seenValidation := cs.blockStore.LoadSeenValidation(state.LastBlockHeight) for idx, precommit := range seenValidation.Precommits { if precommit == nil { @@ -360,32 +378,34 @@ func (cs *ConsensusState) NewStepCh() chan *RoundState { return cs.newStepCh } -func (cs *ConsensusState) OnStart() { +func (cs *ConsensusState) OnStart() error { cs.BaseService.OnStart() cs.scheduleRound0(cs.Height) + return nil } func (cs *ConsensusState) OnStop() { - // It's mostly asynchronous so, there's not much to stop. + // It's asynchronous so, there's not much to stop. cs.BaseService.OnStop() } // EnterNewRound(height, 0) at cs.StartTime. func (cs *ConsensusState) scheduleRound0(height int) { - //log.Debug("scheduleRound0", "now", time.Now(), "startTime", cs.StartTime) + //log.Info("scheduleRound0", "now", time.Now(), "startTime", cs.StartTime) sleepDuration := cs.StartTime.Sub(time.Now()) go func() { if 0 < sleepDuration { time.Sleep(sleepDuration) + // TODO: event? } - cs.EnterNewRound(height, 0) + cs.EnterNewRound(height, 0, false) }() } // Updates ConsensusState and increments height to match that of state. // The round becomes 0 and cs.Step becomes RoundStepNewHeight. -func (cs *ConsensusState) updateToState(state *sm.State, contiguous bool) { - if contiguous && 0 < cs.Height && cs.Height != state.LastBlockHeight { +func (cs *ConsensusState) updateToState(state *sm.State) { + if cs.CommitRound > -1 && 0 < cs.Height && cs.Height != state.LastBlockHeight { PanicSanity(Fmt("updateToState() expected state height of %v but found %v", cs.Height, state.LastBlockHeight)) } @@ -407,12 +427,12 @@ func (cs *ConsensusState) updateToState(state *sm.State, contiguous bool) { // Reset fields based on state. validators := state.BondedValidators height := state.LastBlockHeight + 1 // next desired block height - lastPrecommits := (*VoteSet)(nil) - if contiguous && cs.Votes != nil { - if !cs.Votes.Precommits(cs.Round).HasTwoThirdsMajority() { - PanicSanity("updateToState(state, true) called but last Precommit round didn't have +2/3") + lastPrecommits := (*types.VoteSet)(nil) + if cs.CommitRound > -1 && cs.Votes != nil { + if !cs.Votes.Precommits(cs.CommitRound).HasTwoThirdsMajority() { + PanicSanity("updateToState(state) called but last Precommit round didn't have +2/3") } - lastPrecommits = cs.Votes.Precommits(cs.Round) + lastPrecommits = cs.Votes.Precommits(cs.CommitRound) } // RoundState fields @@ -438,6 +458,7 @@ func (cs *ConsensusState) updateToState(state *sm.State, contiguous bool) { cs.LockedBlock = nil cs.LockedBlockParts = nil cs.Votes = NewHeightVoteSet(height, validators) + cs.CommitRound = -1 cs.LastCommit = lastPrecommits cs.LastValidators = state.LastBondedValidators @@ -473,7 +494,7 @@ func (cs *ConsensusState) maybeRebond() { } } -func (cs *ConsensusState) SetPrivValidator(priv *sm.PrivValidator) { +func (cs *ConsensusState) SetPrivValidator(priv *types.PrivValidator) { cs.mtx.Lock() defer cs.mtx.Unlock() cs.privValidator = priv @@ -485,13 +506,18 @@ func (cs *ConsensusState) SetPrivValidator(priv *sm.PrivValidator) { // Enter: `timeoutPrecommits` after any +2/3 precommits from (height,round-1) // Enter: `startTime = commitTime+timeoutCommit` from NewHeight(height) // NOTE: cs.StartTime was already set for height. -func (cs *ConsensusState) EnterNewRound(height int, round int) { +func (cs *ConsensusState) EnterNewRound(height int, round int, timedOut bool) { cs.mtx.Lock() defer cs.mtx.Unlock() if cs.Height != height || round < cs.Round || (cs.Round == round && cs.Step != RoundStepNewHeight) { log.Debug(Fmt("EnterNewRound(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) return } + + if timedOut { + cs.evsw.FireEvent(types.EventStringTimeoutWait(), cs.RoundStateEvent()) + } + if now := time.Now(); cs.StartTime.After(now) { log.Warn("Need to set a buffer and log.Warn() here for sanity.", "startTime", cs.StartTime, "now", now) } @@ -519,6 +545,8 @@ func (cs *ConsensusState) EnterNewRound(height int, round int) { } cs.Votes.SetRound(round + 1) // also track next round (round+1) to allow round-skipping + cs.evsw.FireEvent(types.EventStringNewRound(), cs.RoundStateEvent()) + // Immediately go to EnterPropose. go cs.EnterPropose(height, round) } @@ -531,7 +559,7 @@ func (cs *ConsensusState) EnterPropose(height int, round int) { log.Debug(Fmt("EnterPropose(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) return } - log.Debug(Fmt("EnterPropose(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) + log.Info(Fmt("EnterPropose(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) defer func() { // Done EnterPropose: @@ -539,16 +567,18 @@ func (cs *ConsensusState) EnterPropose(height int, round int) { cs.Step = RoundStepPropose cs.newStepCh <- cs.getRoundState() - // If we already have the proposal + POL, then goto Prevote + // If we have the whole proposal + POL, then goto Prevote now. + // else, we'll EnterPrevote when the rest of the proposal is received (in AddProposalBlockPart), + // or else after timeoutPropose if cs.isProposalComplete() { - go cs.EnterPrevote(height, cs.Round) + go cs.EnterPrevote(height, cs.Round, false) } }() // This step times out after `timeoutPropose` go func() { time.Sleep(timeoutPropose) - cs.EnterPrevote(height, round) + cs.EnterPrevote(height, round, true) }() // Nothing more to do if we're not a validator @@ -557,9 +587,9 @@ func (cs *ConsensusState) EnterPropose(height int, round int) { } if !bytes.Equal(cs.Validators.Proposer().Address, cs.privValidator.Address) { - log.Debug("EnterPropose: Not our turn to propose", "proposer", cs.Validators.Proposer().Address, "privValidator", cs.privValidator) + log.Info("EnterPropose: Not our turn to propose", "proposer", cs.Validators.Proposer().Address, "privValidator", cs.privValidator) } else { - log.Debug("EnterPropose: Our turn to propose", "proposer", cs.Validators.Proposer().Address, "privValidator", cs.privValidator) + log.Info("EnterPropose: Our turn to propose", "proposer", cs.Validators.Proposer().Address, "privValidator", cs.privValidator) cs.decideProposal(height, round) } } @@ -579,10 +609,10 @@ func (cs *ConsensusState) decideProposal(height int, round int) { } // Make proposal - proposal := NewProposal(height, round, blockParts.Header(), cs.Votes.POLRound()) + proposal := types.NewProposal(height, round, blockParts.Header(), cs.Votes.POLRound()) err := cs.privValidator.SignProposal(cs.state.ChainID, proposal) if err == nil { - log.Debug("Signed and set proposal", "height", height, "round", round, "proposal", proposal) + log.Notice("Signed and set proposal", "height", height, "round", round, "proposal", proposal) log.Debug(Fmt("Signed and set proposal block: %v", block)) // Set fields cs.Proposal = proposal @@ -600,15 +630,18 @@ func (cs *ConsensusState) isProposalComplete() bool { if cs.Proposal == nil || cs.ProposalBlock == nil { return false } + // we have the proposal. if there's a POLRound, + // make sure we have the prevotes from it too if cs.Proposal.POLRound < 0 { return true } else { + // if this is false the proposer is lying or we haven't received the POL yet return cs.Votes.Prevotes(cs.Proposal.POLRound).HasTwoThirdsMajority() } } // Create the next block to propose and return it. -// NOTE: make it side-effect free for clarity. +// NOTE: keep it side-effect free for clarity. func (cs *ConsensusState) createProposalBlock() (block *types.Block, blockParts *types.PartSet) { var validation *types.Validation if cs.Height == 1 { @@ -640,6 +673,7 @@ func (cs *ConsensusState) createProposalBlock() (block *types.Block, blockParts Txs: txs, }, } + block.FillHeader() // Set the block.Header.StateHash. err := cs.state.ComputeBlockStateHash(block) @@ -657,14 +691,25 @@ func (cs *ConsensusState) createProposalBlock() (block *types.Block, blockParts // Enter: any +2/3 prevotes for future round. // Prevote for LockedBlock if we're locked, or ProposalBlock if valid. // Otherwise vote nil. -func (cs *ConsensusState) EnterPrevote(height int, round int) { +func (cs *ConsensusState) EnterPrevote(height int, round int, timedOut bool) { cs.mtx.Lock() defer cs.mtx.Unlock() if cs.Height != height || round < cs.Round || (cs.Round == round && RoundStepPrevote <= cs.Step) { log.Debug(Fmt("EnterPrevote(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) return } - log.Debug(Fmt("EnterPrevote(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) + + // fire event for how we got here + if timedOut { + cs.evsw.FireEvent(types.EventStringTimeoutPropose(), cs.RoundStateEvent()) + } else if cs.isProposalComplete() { + cs.evsw.FireEvent(types.EventStringCompleteProposal(), cs.RoundStateEvent()) + } else { + // we received +2/3 prevotes for a future round + // TODO: catchup event? + } + + log.Info(Fmt("EnterPrevote(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) // Sign and broadcast vote as necessary cs.doPrevote(height, round) @@ -673,16 +718,15 @@ func (cs *ConsensusState) EnterPrevote(height int, round int) { cs.Round = round cs.Step = RoundStepPrevote cs.newStepCh <- cs.getRoundState() - /* This isn't necessary because addVote() does it for us. - if cs.Votes.Prevotes(round).HasTwoThirdsAny() { - go cs.EnterPrevoteWait(height, round) - }*/ + + // Once `addVote` hits any +2/3 prevotes, we will go to PrevoteWait + // (so we have more time to try and collect +2/3 prevotes for a single block) } func (cs *ConsensusState) doPrevote(height int, round int) { // If a block is locked, prevote that. if cs.LockedBlock != nil { - log.Debug("EnterPrevote: Block was locked") + log.Info("EnterPrevote: Block was locked") cs.signAddVote(types.VoteTypePrevote, cs.LockedBlock.Hash(), cs.LockedBlockParts.Header()) return } @@ -704,6 +748,8 @@ func (cs *ConsensusState) doPrevote(height int, round int) { } // Prevote cs.ProposalBlock + // NOTE: the proposal signature is validated when it is received, + // and the proposal block parts are validated as they are received (against the merkle hash in the proposal) cs.signAddVote(types.VoteTypePrevote, cs.ProposalBlock.Hash(), cs.ProposalBlockParts.Header()) return } @@ -719,7 +765,7 @@ func (cs *ConsensusState) EnterPrevoteWait(height int, round int) { if !cs.Votes.Prevotes(round).HasTwoThirdsAny() { PanicSanity(Fmt("EnterPrevoteWait(%v/%v), but Prevotes does not have any +2/3 votes", height, round)) } - log.Debug(Fmt("EnterPrevoteWait(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) + log.Info(Fmt("EnterPrevoteWait(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) // Done EnterPrevoteWait: cs.Round = round @@ -728,60 +774,69 @@ func (cs *ConsensusState) EnterPrevoteWait(height int, round int) { // After `timeoutPrevote0+timeoutPrevoteDelta*round`, EnterPrecommit() go func() { - time.Sleep(timeoutPrevote0 + timeoutPrevote0*time.Duration(round)) - cs.EnterPrecommit(height, round) + time.Sleep(timeoutPrevote0 + timeoutPrevoteDelta*time.Duration(round)) + cs.EnterPrecommit(height, round, true) }() } // Enter: +2/3 precomits for block or nil. // Enter: `timeoutPrevote` after any +2/3 prevotes. // Enter: any +2/3 precommits for next round. -// Lock & precommit the ProposalBlock if we have enough prevotes for it, +// Lock & precommit the ProposalBlock if we have enough prevotes for it (a POL in this round) // else, unlock an existing lock and precommit nil if +2/3 of prevotes were nil, -// else, precommit locked block or nil otherwise. -func (cs *ConsensusState) EnterPrecommit(height int, round int) { +// else, precommit nil otherwise. +func (cs *ConsensusState) EnterPrecommit(height int, round int, timedOut bool) { cs.mtx.Lock() defer cs.mtx.Unlock() if cs.Height != height || round < cs.Round || (cs.Round == round && RoundStepPrecommit <= cs.Step) { log.Debug(Fmt("EnterPrecommit(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) return } - log.Debug(Fmt("EnterPrecommit(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) + + if timedOut { + cs.evsw.FireEvent(types.EventStringTimeoutWait(), cs.RoundStateEvent()) + } + + log.Info(Fmt("EnterPrecommit(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) defer func() { // Done EnterPrecommit: cs.Round = round cs.Step = RoundStepPrecommit cs.newStepCh <- cs.getRoundState() - /* This isn't necessary because addVote() does it for us. - if cs.Votes.Precommits(round).HasTwoThirdsAny() { - go cs.EnterPrecommitWait(height, round) - }*/ }() hash, partsHeader, ok := cs.Votes.Prevotes(round).TwoThirdsMajority() - // If we don't have two thirds of prevotes, just precommit locked block or nil + // If we don't have a polka, we must precommit nil if !ok { if cs.LockedBlock != nil { - log.Debug("EnterPrecommit: No +2/3 prevotes during EnterPrecommit. Precommitting lock.") - cs.signAddVote(types.VoteTypePrecommit, cs.LockedBlock.Hash(), cs.LockedBlockParts.Header()) + log.Info("EnterPrecommit: No +2/3 prevotes during EnterPrecommit while we're locked. Precommitting nil") } else { - log.Debug("EnterPrecommit: No +2/3 prevotes during EnterPrecommit. Precommitting nil.") - cs.signAddVote(types.VoteTypePrecommit, nil, types.PartSetHeader{}) + log.Info("EnterPrecommit: No +2/3 prevotes during EnterPrecommit. Precommitting nil.") } + cs.signAddVote(types.VoteTypePrecommit, nil, types.PartSetHeader{}) return } + // At this point +2/3 prevoted for a particular block or nil + cs.evsw.FireEvent(types.EventStringPolka(), cs.RoundStateEvent()) + + // the latest POLRound should be this round + if cs.Votes.POLRound() < round { + PanicSanity(Fmt("This POLRound should be %v but got %", round, cs.Votes.POLRound())) + } + // +2/3 prevoted nil. Unlock and precommit nil. if len(hash) == 0 { if cs.LockedBlock == nil { - log.Debug("EnterPrecommit: +2/3 prevoted for nil.") + log.Info("EnterPrecommit: +2/3 prevoted for nil.") } else { - log.Debug("EnterPrecommit: +2/3 prevoted for nil. Unlocking") + log.Info("EnterPrecommit: +2/3 prevoted for nil. Unlocking") cs.LockedRound = 0 cs.LockedBlock = nil cs.LockedBlockParts = nil + cs.evsw.FireEvent(types.EventStringUnlock(), cs.RoundStateEvent()) } cs.signAddVote(types.VoteTypePrecommit, nil, types.PartSetHeader{}) return @@ -789,16 +844,18 @@ func (cs *ConsensusState) EnterPrecommit(height int, round int) { // At this point, +2/3 prevoted for a particular block. - // If +2/3 prevoted for already locked block, precommit it. + // If we're already locked on that block, precommit it, and update the LockedRound if cs.LockedBlock.HashesTo(hash) { - log.Debug("EnterPrecommit: +2/3 prevoted locked block.") + log.Info("EnterPrecommit: +2/3 prevoted locked block. Relocking") + cs.LockedRound = round + cs.evsw.FireEvent(types.EventStringRelock(), cs.RoundStateEvent()) cs.signAddVote(types.VoteTypePrecommit, hash, partsHeader) return } // If +2/3 prevoted for proposal block, stage and precommit it if cs.ProposalBlock.HashesTo(hash) { - log.Debug("EnterPrecommit: +2/3 prevoted proposal block.") + log.Info("EnterPrecommit: +2/3 prevoted proposal block. Locking", "hash", hash) // Validate the block. if err := cs.stageBlock(cs.ProposalBlock, cs.ProposalBlockParts); err != nil { PanicConsensus(Fmt("EnterPrecommit: +2/3 prevoted for an invalid block: %v", err)) @@ -806,16 +863,15 @@ func (cs *ConsensusState) EnterPrecommit(height int, round int) { cs.LockedRound = round cs.LockedBlock = cs.ProposalBlock cs.LockedBlockParts = cs.ProposalBlockParts + cs.evsw.FireEvent(types.EventStringLock(), cs.RoundStateEvent()) cs.signAddVote(types.VoteTypePrecommit, hash, partsHeader) return } - // Otherwise, we need to fetch the +2/3 prevoted block. - // Unlock and precommit nil. + // There was a polka in this round for a block we don't have. + // Fetch that block, unlock, and precommit nil. // The +2/3 prevotes for this round is the POL for our unlock. - if cs.Votes.POLRound() < round { - PanicSanity(Fmt("This POLRound shold be %v but got %", round, cs.Votes.POLRound())) - } + // TODO: In the future save the POL prevotes for justification. cs.LockedRound = 0 cs.LockedBlock = nil cs.LockedBlockParts = nil @@ -823,6 +879,7 @@ func (cs *ConsensusState) EnterPrecommit(height int, round int) { cs.ProposalBlock = nil cs.ProposalBlockParts = types.NewPartSetFromHeader(partsHeader) } + cs.evsw.FireEvent(types.EventStringUnlock(), cs.RoundStateEvent()) cs.signAddVote(types.VoteTypePrecommit, nil, types.PartSetHeader{}) return } @@ -838,7 +895,7 @@ func (cs *ConsensusState) EnterPrecommitWait(height int, round int) { if !cs.Votes.Precommits(round).HasTwoThirdsAny() { PanicSanity(Fmt("EnterPrecommitWait(%v/%v), but Precommits does not have any +2/3 votes", height, round)) } - log.Debug(Fmt("EnterPrecommitWait(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) + log.Info(Fmt("EnterPrecommitWait(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) // Done EnterPrecommitWait: cs.Round = round @@ -852,48 +909,42 @@ func (cs *ConsensusState) EnterPrecommitWait(height int, round int) { // we already entered commit (or the next round). // So just try to transition to the next round, // which is what we'd do otherwise. - cs.EnterNewRound(height, round+1) + cs.EnterNewRound(height, round+1, true) }() } // Enter: +2/3 precommits for block -func (cs *ConsensusState) EnterCommit(height int) { +func (cs *ConsensusState) EnterCommit(height int, commitRound int) { cs.mtx.Lock() defer cs.mtx.Unlock() if cs.Height != height || RoundStepCommit <= cs.Step { - log.Debug(Fmt("EnterCommit(%v): Invalid args. Current step: %v/%v/%v", height, cs.Height, cs.Round, cs.Step)) + log.Debug(Fmt("EnterCommit(%v/%v): Invalid args. Current step: %v/%v/%v", height, commitRound, cs.Height, cs.Round, cs.Step)) return } - log.Debug(Fmt("EnterCommit(%v). Current: %v/%v/%v", height, cs.Height, cs.Round, cs.Step)) + log.Info(Fmt("EnterCommit(%v/%v). Current: %v/%v/%v", height, commitRound, cs.Height, cs.Round, cs.Step)) defer func() { // Done Entercommit: // keep ca.Round the same, it points to the right Precommits set. cs.Step = RoundStepCommit + cs.CommitRound = commitRound cs.newStepCh <- cs.getRoundState() // Maybe finalize immediately. cs.tryFinalizeCommit(height) }() - hash, partsHeader, ok := cs.Votes.Precommits(cs.Round).TwoThirdsMajority() + hash, partsHeader, ok := cs.Votes.Precommits(commitRound).TwoThirdsMajority() if !ok { PanicSanity("RunActionCommit() expects +2/3 precommits") } // The Locked* fields no longer matter. // Move them over to ProposalBlock if they match the commit hash, - // otherwise they can now be cleared. + // otherwise they'll be cleared in updateToState. if cs.LockedBlock.HashesTo(hash) { cs.ProposalBlock = cs.LockedBlock cs.ProposalBlockParts = cs.LockedBlockParts - cs.LockedRound = 0 - cs.LockedBlock = nil - cs.LockedBlockParts = nil - } else { - cs.LockedRound = 0 - cs.LockedBlock = nil - cs.LockedBlockParts = nil } // If we don't have the block being committed, set up to get it. @@ -915,12 +966,14 @@ func (cs *ConsensusState) tryFinalizeCommit(height int) { PanicSanity(Fmt("tryFinalizeCommit() cs.Height: %v vs height: %v", cs.Height, height)) } - hash, _, ok := cs.Votes.Precommits(cs.Round).TwoThirdsMajority() + hash, _, ok := cs.Votes.Precommits(cs.CommitRound).TwoThirdsMajority() if !ok || len(hash) == 0 { - return // There was no +2/3 majority, or +2/3 was for <nil>. + log.Warn("Attempt to finalize failed. There was no +2/3 majority, or +2/3 was for <nil>.") + return } if !cs.ProposalBlock.HashesTo(hash) { - return // We don't have the commit block. + log.Warn("Attempt to finalize failed. We don't have the commit block.") + return } go cs.FinalizeCommit(height) } @@ -935,7 +988,7 @@ func (cs *ConsensusState) FinalizeCommit(height int) { return } - hash, header, ok := cs.Votes.Precommits(cs.Round).TwoThirdsMajority() + hash, header, ok := cs.Votes.Precommits(cs.CommitRound).TwoThirdsMajority() if !ok { PanicSanity(Fmt("Cannot FinalizeCommit, commit does not have two thirds majority")) @@ -950,11 +1003,11 @@ func (cs *ConsensusState) FinalizeCommit(height int) { PanicConsensus(Fmt("+2/3 committed an invalid block: %v", err)) } - log.Debug(Fmt("Finalizing commit of block: %v", cs.ProposalBlock)) + log.Info(Fmt("Finalizing commit of block: %v", cs.ProposalBlock)) // We have the block, so stage/save/commit-vote. - cs.saveBlock(cs.ProposalBlock, cs.ProposalBlockParts, cs.Votes.Precommits(cs.Round)) + cs.saveBlock(cs.ProposalBlock, cs.ProposalBlockParts, cs.Votes.Precommits(cs.CommitRound)) // Increment height. - cs.updateToState(cs.stagedState, true) + cs.updateToState(cs.stagedState) // cs.StartTime is already set. // Schedule Round0 to start soon. go cs.scheduleRound0(height + 1) @@ -970,7 +1023,7 @@ func (cs *ConsensusState) FinalizeCommit(height int) { //----------------------------------------------------------------------------- -func (cs *ConsensusState) SetProposal(proposal *Proposal) error { +func (cs *ConsensusState) SetProposal(proposal *types.Proposal) error { cs.mtx.Lock() defer cs.mtx.Unlock() @@ -1006,6 +1059,7 @@ func (cs *ConsensusState) SetProposal(proposal *Proposal) error { } // NOTE: block is not necessarily valid. +// This can trigger us to go into EnterPrevote asynchronously (before we timeout of propose) or to attempt to commit func (cs *ConsensusState) AddProposalBlockPart(height int, part *types.Part) (added bool, err error) { cs.mtx.Lock() defer cs.mtx.Unlock() @@ -1029,10 +1083,10 @@ func (cs *ConsensusState) AddProposalBlockPart(height int, part *types.Part) (ad var n int64 var err error cs.ProposalBlock = wire.ReadBinary(&types.Block{}, cs.ProposalBlockParts.GetReader(), &n, &err).(*types.Block) - log.Debug("Received complete proposal", "hash", cs.ProposalBlock.Hash()) + log.Info("Received complete proposal", "hash", cs.ProposalBlock.Hash()) if cs.Step == RoundStepPropose && cs.isProposalComplete() { // Move onto the next step - go cs.EnterPrevote(height, cs.Round) + go cs.EnterPrevote(height, cs.Round, false) } else if cs.Step == RoundStepCommit { // If we're waiting on the proposal block... cs.tryFinalizeCommit(height) @@ -1042,23 +1096,61 @@ func (cs *ConsensusState) AddProposalBlockPart(height int, part *types.Part) (ad return added, nil } -func (cs *ConsensusState) AddVote(address []byte, vote *types.Vote, peerKey string) (added bool, index int, err error) { +// Attempt to add the vote. if its a duplicate signature, dupeout the validator +func (cs *ConsensusState) TryAddVote(valIndex int, vote *types.Vote, peerKey string) (bool, error) { + added, address, err := cs.AddVote(valIndex, vote, peerKey) + if err != nil { + // If the vote height is off, we'll just ignore it, + // But if it's a conflicting sig, broadcast evidence tx for slashing. + // If it's otherwise invalid, punish peer. + if err == ErrVoteHeightMismatch { + return added, err + } else if errDupe, ok := err.(*types.ErrVoteConflictingSignature); ok { + log.Warn("Found conflicting vote. Publish evidence") + evidenceTx := &types.DupeoutTx{ + Address: address, + VoteA: *errDupe.VoteA, + VoteB: *errDupe.VoteB, + } + cs.mempoolReactor.BroadcastTx(evidenceTx) // shouldn't need to check returned err + return added, err + } else { + // Probably an invalid signature. Bad peer. + log.Warn("Error attempting to add vote", "error", err) + return added, ErrAddingVote + } + } + return added, nil +} + +func (cs *ConsensusState) AddVote(valIndex int, vote *types.Vote, peerKey string) (added bool, address []byte, err error) { cs.mtx.Lock() defer cs.mtx.Unlock() - return cs.addVote(address, vote, peerKey) + return cs.addVote(valIndex, vote, peerKey) } //----------------------------------------------------------------------------- -func (cs *ConsensusState) addVote(address []byte, vote *types.Vote, peerKey string) (added bool, index int, err error) { +func (cs *ConsensusState) addVote(valIndex int, vote *types.Vote, peerKey string) (added bool, address []byte, err error) { log.Debug("addVote", "voteHeight", vote.Height, "voteType", vote.Type, "csHeight", cs.Height) + defer func() { + if added { + cs.evsw.FireEvent(types.EventStringVote(), &types.EventDataVote{valIndex, address, vote}) + } + }() + // A precommit for the previous height? - if vote.Height+1 == cs.Height && vote.Type == types.VoteTypePrecommit { - added, index, err = cs.LastCommit.AddByAddress(address, vote) + if vote.Height+1 == cs.Height { + if !(cs.Step == RoundStepNewHeight && vote.Type == types.VoteTypePrecommit) { + // TODO: give the reason .. + // fmt.Errorf("TryAddVote: Wrong height, not a LastCommit straggler commit.") + return added, nil, ErrVoteHeightMismatch + } + added, address, err = cs.LastCommit.AddByIndex(valIndex, vote) if added { - log.Debug(Fmt("Added to lastPrecommits: %v", cs.LastCommit.StringShort())) + log.Info(Fmt("Added to lastPrecommits: %v", cs.LastCommit.StringShort())) } return } @@ -1066,12 +1158,12 @@ func (cs *ConsensusState) addVote(address []byte, vote *types.Vote, peerKey stri // A prevote/precommit for this height? if vote.Height == cs.Height { height := cs.Height - added, index, err = cs.Votes.AddByAddress(address, vote, peerKey) + added, address, err = cs.Votes.AddByIndex(valIndex, vote, peerKey) if added { switch vote.Type { case types.VoteTypePrevote: prevotes := cs.Votes.Prevotes(vote.Round) - log.Debug(Fmt("Added to prevotes: %v", prevotes.StringShort())) + log.Info(Fmt("Added to prevotes: %v", prevotes.StringShort())) // First, unlock if prevotes is a valid POL. // >> lockRound < POLRound <= unlockOrChangeLockRound (see spec) // NOTE: If (lockRound < POLRound) but !(POLRound <= unlockOrChangeLockRound), @@ -1084,57 +1176,59 @@ func (cs *ConsensusState) addVote(address []byte, vote *types.Vote, peerKey stri cs.LockedRound = 0 cs.LockedBlock = nil cs.LockedBlockParts = nil + cs.evsw.FireEvent(types.EventStringUnlock(), cs.RoundStateEvent()) } } if cs.Round <= vote.Round && prevotes.HasTwoThirdsAny() { // Round-skip over to PrevoteWait or goto Precommit. go func() { - if cs.Round < vote.Round { - cs.EnterNewRound(height, vote.Round) - } + cs.EnterNewRound(height, vote.Round, false) if prevotes.HasTwoThirdsMajority() { - cs.EnterPrecommit(height, vote.Round) + cs.EnterPrecommit(height, vote.Round, false) } else { - cs.EnterPrevote(height, vote.Round) + cs.EnterPrevote(height, vote.Round, false) cs.EnterPrevoteWait(height, vote.Round) } }() } else if cs.Proposal != nil && 0 <= cs.Proposal.POLRound && cs.Proposal.POLRound == vote.Round { // If the proposal is now complete, enter prevote of cs.Round. if cs.isProposalComplete() { - go cs.EnterPrevote(height, cs.Round) + go cs.EnterPrevote(height, cs.Round, false) } } case types.VoteTypePrecommit: precommits := cs.Votes.Precommits(vote.Round) - log.Debug(Fmt("Added to precommit: %v", precommits.StringShort())) - if cs.Round <= vote.Round && precommits.HasTwoThirdsAny() { + log.Info(Fmt("Added to precommit: %v", precommits.StringShort())) + hash, _, ok := precommits.TwoThirdsMajority() + if ok { go func() { - hash, _, ok := precommits.TwoThirdsMajority() - if ok && len(hash) == 0 { - cs.EnterNewRound(height, vote.Round+1) - return - } else if cs.Round < vote.Round { - cs.EnterNewRound(height, vote.Round) - } - if ok { - cs.EnterCommit(height) + if len(hash) == 0 { + cs.EnterNewRound(height, vote.Round+1, false) } else { - cs.EnterPrecommit(height, vote.Round) - cs.EnterPrecommitWait(height, vote.Round) + cs.EnterNewRound(height, vote.Round, false) + cs.EnterPrecommit(height, vote.Round, false) + cs.EnterCommit(height, vote.Round) } }() + } else if cs.Round <= vote.Round && precommits.HasTwoThirdsAny() { + go func() { + cs.EnterNewRound(height, vote.Round, false) + cs.EnterPrecommit(height, vote.Round, false) + cs.EnterPrecommitWait(height, vote.Round) + }() } default: PanicSanity(Fmt("Unexpected vote type %X", vote.Type)) // Should not happen. } } - // Either duplicate, or error upon cs.Votes.AddByAddress() + // Either duplicate, or error upon cs.Votes.AddByIndex() return + } else { + err = ErrVoteHeightMismatch } // Height mismatch, bad peer? - log.Debug("Vote ignored and not added", "voteHeight", vote.Height, "csHeight", cs.Height) + log.Info("Vote ignored and not added", "voteHeight", vote.Height, "csHeight", cs.Height) return } @@ -1167,21 +1261,28 @@ func (cs *ConsensusState) stageBlock(block *types.Block, blockParts *types.PartS } } +func (cs *ConsensusState) signVote(type_ byte, hash []byte, header types.PartSetHeader) (*types.Vote, error) { + vote := &types.Vote{ + Height: cs.Height, + Round: cs.Round, + Type: type_, + BlockHash: hash, + BlockPartsHeader: header, + } + err := cs.privValidator.SignVote(cs.state.ChainID, vote) + return vote, err +} + func (cs *ConsensusState) signAddVote(type_ byte, hash []byte, header types.PartSetHeader) *types.Vote { if cs.privValidator == nil || !cs.Validators.HasAddress(cs.privValidator.Address) { return nil } - vote := &types.Vote{ - Height: cs.Height, - Round: cs.Round, - Type: type_, - BlockHash: hash, - BlockParts: header, - } - err := cs.privValidator.SignVote(cs.state.ChainID, vote) + vote, err := cs.signVote(type_, hash, header) if err == nil { - _, _, err := cs.addVote(cs.privValidator.Address, vote, "") - log.Debug("Signed and added vote", "height", cs.Height, "round", cs.Round, "vote", vote, "error", err) + // NOTE: store our index in the cs so we don't have to do this every time + valIndex, _ := cs.Validators.GetByAddress(cs.privValidator.Address) + _, _, err := cs.addVote(valIndex, vote, "") + log.Notice("Signed and added vote", "height", cs.Height, "round", cs.Round, "vote", vote, "error", err) return vote } else { log.Warn("Error signing vote", "height", cs.Height, "round", cs.Round, "vote", vote, "error", err) @@ -1190,7 +1291,7 @@ func (cs *ConsensusState) signAddVote(type_ byte, hash []byte, header types.Part } // Save Block, save the +2/3 Commits we've seen -func (cs *ConsensusState) saveBlock(block *types.Block, blockParts *types.PartSet, commits *VoteSet) { +func (cs *ConsensusState) saveBlock(block *types.Block, blockParts *types.PartSet, commits *types.VoteSet) { // The proposal must be valid. if err := cs.stageBlock(block, blockParts); err != nil { @@ -1210,10 +1311,12 @@ func (cs *ConsensusState) saveBlock(block *types.Block, blockParts *types.PartSe cs.mempoolReactor.Mempool.ResetForBlockAndState(block, cs.stagedState) // Fire off event - go func(block *types.Block) { - cs.evsw.FireEvent(types.EventStringNewBlock(), block) - cs.evc.Flush() - }(block) + if cs.evsw != nil && cs.evc != nil { + go func(block *types.Block) { + cs.evsw.FireEvent(types.EventStringNewBlock(), types.EventDataNewBlock{block}) + cs.evc.Flush() + }(block) + } } diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/consensus/state_test.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/consensus/state_test.go index f5d99db74758e2bb16332dc8fc18f9733a79f769..a3d8b3ae85065f2a3afd35c5cc69a3ddd87fcabc 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/consensus/state_test.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/consensus/state_test.go @@ -1,38 +1,1177 @@ package consensus import ( + "bytes" + "fmt" "testing" + "time" _ "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/config/tendermint_test" + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/events" + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/types" ) +/* + +ProposeSuite +x * TestEnterProposeNoValidator - timeout into prevote round +x * TestEnterPropose - finish propose without timing out (we have the proposal) +x * TestBadProposal - 2 vals, bad proposal (bad block state hash), should prevote and precommit nil +FullRoundSuite +x * TestFullRound1 - 1 val, full successful round +x * TestFullRoundNil - 1 val, full round of nil +x * TestFullRound2 - 2 vals, both required for fuill round +LockSuite +x * TestLockNoPOL - 2 vals, 4 rounds. one val locked, precommits nil every round except first. +x * TestLockPOLRelock - 4 vals, one precommits, other 3 polka at next round, so we unlock and precomit the polka +x * TestLockPOLUnlock - 4 vals, one precommits, other 3 polka nil at next round, so we unlock and precomit nil +x * TestLockPOLSafety1 - 4 vals. We shouldn't change lock based on polka at earlier round +x * TestLockPOLSafety2 - 4 vals. After unlocking, we shouldn't relock based on polka at earlier round + * TestNetworkLock - once +1/3 precommits, network should be locked + * TestNetworkLockPOL - once +1/3 precommits, the block with more recent polka is committed +SlashingSuite +x * TestSlashingPrevotes - a validator prevoting twice in a round gets slashed +x * TestSlashingPrecommits - a validator precomitting twice in a round gets slashed +CatchupSuite + * TestCatchup - if we might be behind and we've seen any 2/3 prevotes, round skip to new round, precommit, or prevote +HaltSuite +x * TestHalt1 - if we see +2/3 precommits after timing out into new round, we should still commit + +*/ + +//---------------------------------------------------------------------------------------------------- +// ProposeSuite + +func init() { + fmt.Println("") + timeoutPropose = 1000 * time.Millisecond +} + +// a non-validator should timeout into the prevote round func TestEnterProposeNoPrivValidator(t *testing.T) { - cs, _ := randConsensusState() - cs.EnterPropose(1, 0) - rs := cs.GetRoundState() - if rs.Proposal != nil { - t.Error("Expected to make no proposal, since no privValidator") + css, _ := simpleConsensusState(1) + cs := css[0] + cs.SetPrivValidator(nil) + + timeoutChan := make(chan struct{}) + evsw := events.NewEventSwitch() + evsw.OnStart() + evsw.AddListenerForEvent("tester", types.EventStringTimeoutPropose(), func(data types.EventData) { + timeoutChan <- struct{}{} + }) + cs.SetFireable(evsw) + + // starts a go routine for EnterPropose + cs.EnterNewRound(cs.Height, 0, false) + + // go to prevote + <-cs.NewStepCh() + + // if we're not a validator, EnterPropose should timeout + select { + case rs := <-cs.NewStepCh(): + log.Info(rs.String()) + t.Fatal("Expected EnterPropose to timeout") + case <-timeoutChan: + rs := cs.GetRoundState() + if rs.Proposal != nil { + t.Error("Expected to make no proposal, since no privValidator") + } + break } } +// a validator should not timeout of the prevote round (TODO: unless the block is really big!) func TestEnterPropose(t *testing.T) { - cs, privValidators := randConsensusState() - val0 := privValidators[0] - cs.SetPrivValidator(val0) + css, _ := simpleConsensusState(1) + cs := css[0] + + timeoutChan := make(chan struct{}) + evsw := events.NewEventSwitch() + evsw.OnStart() + evsw.AddListenerForEvent("tester", types.EventStringTimeoutPropose(), func(data types.EventData) { + timeoutChan <- struct{}{} + }) + cs.SetFireable(evsw) + + // starts a go routine for EnterPropose + cs.EnterNewRound(cs.Height, 0, false) + + // go to prevote + <-cs.NewStepCh() + + // if we are a validator, we expect it not to timeout + select { + case <-cs.NewStepCh(): + rs := cs.GetRoundState() + + // Check that Proposal, ProposalBlock, ProposalBlockParts are set. + if rs.Proposal == nil { + t.Error("rs.Proposal should be set") + } + if rs.ProposalBlock == nil { + t.Error("rs.ProposalBlock should be set") + } + if rs.ProposalBlockParts.Total() == 0 { + t.Error("rs.ProposalBlockParts should be set") + } + break + case <-timeoutChan: + t.Fatal("Expected EnterPropose not to timeout") + } +} + +func TestBadProposal(t *testing.T) { + css, privVals := simpleConsensusState(2) + cs1, cs2 := css[0], css[1] + cs1.newStepCh = make(chan *RoundState) // so it blocks + + timeoutChan := make(chan struct{}) + evsw := events.NewEventSwitch() + evsw.OnStart() + evsw.AddListenerForEvent("tester", types.EventStringTimeoutPropose(), func(data types.EventData) { + timeoutChan <- struct{}{} + }) + evsw.AddListenerForEvent("tester", types.EventStringTimeoutWait(), func(data types.EventData) { + timeoutChan <- struct{}{} + }) + cs1.SetFireable(evsw) + + // make the second validator the proposer + propBlock := changeProposer(t, cs1, cs2) + + // make the block bad by tampering with statehash + stateHash := propBlock.StateHash + stateHash[0] = byte((stateHash[0] + 1) % 255) + propBlock.StateHash = stateHash + propBlockParts := propBlock.MakePartSet() + proposal := types.NewProposal(cs2.Height, cs2.Round, propBlockParts.Header(), cs2.Votes.POLRound()) + if err := cs2.privValidator.SignProposal(cs2.state.ChainID, proposal); err != nil { + t.Fatal("failed to sign bad proposal", err) + } + + // start round + cs1.EnterNewRound(cs1.Height, 0, false) + + // now we're on a new round and not the proposer + <-cs1.NewStepCh() + // so set the proposal block (and fix voting power) + cs1.mtx.Lock() + cs1.Proposal, cs1.ProposalBlock, cs1.ProposalBlockParts = proposal, propBlock, propBlockParts + fixVotingPower(t, cs1, privVals[1].Address) + cs1.mtx.Unlock() + // and wait for timeout + <-timeoutChan + + // go to prevote, prevote for nil (proposal is bad) + <-cs1.NewStepCh() + validatePrevote(t, cs1, 0, privVals[0], nil) + + // add bad prevote from cs2. we should precommit nil + signAddVoteToFrom(types.VoteTypePrevote, cs1, cs2, propBlock.Hash(), propBlock.MakePartSet().Header()) + _, _, _ = <-cs1.NewStepCh(), <-timeoutChan, <-cs1.NewStepCh() + validatePrecommit(t, cs1, 0, 0, privVals[0], nil, nil) + signAddVoteToFrom(types.VoteTypePrecommit, cs1, cs2, propBlock.Hash(), propBlock.MakePartSet().Header()) +} + +//---------------------------------------------------------------------------------------------------- +// FulLRoundSuite + +// propose, prevote, and precommit a block +func TestFullRound1(t *testing.T) { + css, privVals := simpleConsensusState(1) + cs := css[0] + + // starts a go routine for EnterPropose + cs.EnterNewRound(cs.Height, 0, false) + // wait to finish propose and prevote + _, _ = <-cs.NewStepCh(), <-cs.NewStepCh() + + // we should now be in precommit + // verify our prevote is there + cs.mtx.Lock() + propBlockHash := cs.ProposalBlock.Hash() + cs.mtx.Unlock() + + // the proposed block should be prevoted, precommitted, and locked + validatePrevoteAndPrecommit(t, cs, 0, 0, privVals[0], propBlockHash, propBlockHash, nil) +} + +// nil is proposed, so prevote and precommit nil +func TestFullRoundNil(t *testing.T) { + css, privVals := simpleConsensusState(1) + cs := css[0] + cs.newStepCh = make(chan *RoundState) // so it blocks + cs.SetPrivValidator(nil) + + timeoutChan := make(chan struct{}) + evsw := events.NewEventSwitch() + evsw.OnStart() + evsw.AddListenerForEvent("tester", types.EventStringTimeoutPropose(), func(data types.EventData) { + timeoutChan <- struct{}{} + }) + cs.SetFireable(evsw) + + // starts a go routine for EnterPropose + cs.EnterNewRound(cs.Height, 0, false) + + // wait to finish propose (we should time out) + <-cs.NewStepCh() + cs.SetPrivValidator(privVals[0]) // this might be a race condition (uses the mutex that EnterPropose has just released and EnterPrevote is about to grab) + <-timeoutChan + + // wait to finish prevote + <-cs.NewStepCh() + + // should prevote and precommit nil + validatePrevoteAndPrecommit(t, cs, 0, 0, privVals[0], nil, nil, nil) +} + +// run through propose, prevote, precommit commit with two validators +// where the first validator has to wait for votes from the second +func TestFullRound2(t *testing.T) { + css, privVals := simpleConsensusState(2) + cs1, cs2 := css[0], css[1] + cs1.newStepCh = make(chan *RoundState) // so it blocks + cs2.newStepCh = make(chan *RoundState) // so it blocks + + // start round and wait for propose and prevote + cs1.EnterNewRound(cs1.Height, 0, false) + _, _ = <-cs1.NewStepCh(), <-cs1.NewStepCh() + + // we should now be stuck in limbo forever, waiting for more prevotes + ensureNoNewStep(t, cs1) + + propBlockHash, propPartsHeader := cs1.ProposalBlock.Hash(), cs1.ProposalBlockParts.Header() + + // prevote arrives from cs2: + signAddVoteToFrom(types.VoteTypePrevote, cs1, cs2, propBlockHash, propPartsHeader) + + // wait to finish precommit + <-cs1.NewStepCh() + + // the proposed block should now be locked and our precommit added + validatePrecommit(t, cs1, 0, 0, privVals[0], propBlockHash, propBlockHash) + + // we should now be stuck in limbo forever, waiting for more precommits + ensureNoNewStep(t, cs1) + + // precommit arrives from cs2: + signAddVoteToFrom(types.VoteTypePrecommit, cs1, cs2, propBlockHash, propPartsHeader) + + // wait to finish commit, propose in next height + _, rs := <-cs1.NewStepCh(), <-cs1.NewStepCh() + if rs.Height != 2 { + t.Fatal("Expected height to increment") + } +} + +//------------------------------------------------------------------------------------------ +// LockSuite + +// two validators, 4 rounds. +// val1 proposes the first 2 rounds, and is locked in the first. +// val2 proposes the next two. val1 should precommit nil on all (except first where he locks) +func TestLockNoPOL(t *testing.T) { + css, privVals := simpleConsensusState(2) + cs1, cs2 := css[0], css[1] + cs1.newStepCh = make(chan *RoundState) // so it blocks + + timeoutChan := make(chan struct{}) + evsw := events.NewEventSwitch() + evsw.OnStart() + evsw.AddListenerForEvent("tester", types.EventStringTimeoutPropose(), func(data types.EventData) { + timeoutChan <- struct{}{} + }) + evsw.AddListenerForEvent("tester", types.EventStringTimeoutWait(), func(data types.EventData) { + timeoutChan <- struct{}{} + }) + cs1.SetFireable(evsw) + + /* + Round1 (cs1, B) // B B // B B2 + */ + + // start round and wait for propose and prevote + cs1.EnterNewRound(cs1.Height, 0, false) + _, _ = <-cs1.NewStepCh(), <-cs1.NewStepCh() + + // we should now be stuck in limbo forever, waiting for more prevotes + // prevote arrives from cs2: + signAddVoteToFrom(types.VoteTypePrevote, cs1, cs2, cs1.ProposalBlock.Hash(), cs1.ProposalBlockParts.Header()) + + cs1.mtx.Lock() // XXX: sigh + theBlockHash := cs1.ProposalBlock.Hash() + cs1.mtx.Unlock() + + // wait to finish precommit + <-cs1.NewStepCh() + + // the proposed block should now be locked and our precommit added + validatePrecommit(t, cs1, 0, 0, privVals[0], theBlockHash, theBlockHash) + + // we should now be stuck in limbo forever, waiting for more precommits + // lets add one for a different block + // NOTE: in practice we should never get to a point where there are precommits for different blocks at the same round + hash := cs1.ProposalBlock.Hash() + hash[0] = byte((hash[0] + 1) % 255) + signAddVoteToFrom(types.VoteTypePrecommit, cs1, cs2, hash, cs1.ProposalBlockParts.Header()) + + // (note we're entering precommit for a second time this round) + // but with invalid args. then we EnterPrecommitWait, and the timeout to new round + _, _ = <-cs1.NewStepCh(), <-timeoutChan + + log.Info("#### ONTO ROUND 2") + /* + Round2 (cs1, B) // B B2 + */ + + incrementRound(cs2) + + // go to prevote + <-cs1.NewStepCh() + + // now we're on a new round and the proposer + if cs1.ProposalBlock != cs1.LockedBlock { + t.Fatalf("Expected proposal block to be locked block. Got %v, Expected %v", cs1.ProposalBlock, cs1.LockedBlock) + } + + // wait to finish prevote + <-cs1.NewStepCh() + + // we should have prevoted our locked block + validatePrevote(t, cs1, 1, privVals[0], cs1.LockedBlock.Hash()) + + // add a conflicting prevote from the other validator + signAddVoteToFrom(types.VoteTypePrevote, cs1, cs2, hash, cs1.ProposalBlockParts.Header()) + + // now we're going to enter prevote again, but with invalid args + // and then prevote wait, which should timeout. then wait for precommit + _, _, _ = <-cs1.NewStepCh(), <-timeoutChan, <-cs1.NewStepCh() + + // the proposed block should still be locked and our precommit added + // we should precommit nil and be locked on the proposal + validatePrecommit(t, cs1, 1, 0, privVals[0], nil, theBlockHash) + + // add conflicting precommit from cs2 + // NOTE: in practice we should never get to a point where there are precommits for different blocks at the same round + signAddVoteToFrom(types.VoteTypePrecommit, cs1, cs2, hash, cs1.ProposalBlockParts.Header()) + + // (note we're entering precommit for a second time this round, but with invalid args + // then we EnterPrecommitWait and timeout into NewRound + _, _ = <-cs1.NewStepCh(), <-timeoutChan + + log.Info("#### ONTO ROUND 3") + /* + Round3 (cs2, _) // B, B2 + */ + + incrementRound(cs2) + + // now we're on a new round and not the proposer, so wait for timeout + _, _ = <-cs1.NewStepCh(), <-timeoutChan + if cs1.ProposalBlock != nil { + t.Fatal("Expected proposal block to be nil") + } + + // go to prevote, prevote for locked block + <-cs1.NewStepCh() + validatePrevote(t, cs1, 0, privVals[0], cs1.LockedBlock.Hash()) + + // TODO: quick fastforward to new round, set proposer + signAddVoteToFrom(types.VoteTypePrevote, cs1, cs2, hash, cs1.ProposalBlockParts.Header()) + _, _, _ = <-cs1.NewStepCh(), <-timeoutChan, <-cs1.NewStepCh() + validatePrecommit(t, cs1, 2, 0, privVals[0], nil, theBlockHash) // precommit nil but be locked on proposal + signAddVoteToFrom(types.VoteTypePrecommit, cs1, cs2, hash, cs1.ProposalBlockParts.Header()) // NOTE: conflicting precommits at same height + + <-cs1.NewStepCh() + + // before we time out into new round, set next proposer + // and next proposal block + _, v1 := cs1.Validators.GetByAddress(privVals[0].Address) + v1.VotingPower = 1 + if updated := cs1.Validators.Update(v1); !updated { + t.Fatal("failed to update validator") + } + + cs2.decideProposal(cs2.Height, cs2.Round+1) + prop, propBlock := cs2.Proposal, cs2.ProposalBlock + if prop == nil || propBlock == nil { + t.Fatal("Failed to create proposal block with cs2") + } + + incrementRound(cs2) + + <-timeoutChan + + log.Info("#### ONTO ROUND 4") + /* + Round4 (cs2, C) // B C // B C + */ + + // now we're on a new round and not the proposer + <-cs1.NewStepCh() + // so set the proposal block + cs1.mtx.Lock() + cs1.Proposal, cs1.ProposalBlock = prop, propBlock + cs1.mtx.Unlock() + // and wait for timeout + <-timeoutChan + // go to prevote, prevote for locked block (not proposal) + <-cs1.NewStepCh() + validatePrevote(t, cs1, 0, privVals[0], cs1.LockedBlock.Hash()) + + signAddVoteToFrom(types.VoteTypePrevote, cs1, cs2, propBlock.Hash(), propBlock.MakePartSet().Header()) + _, _, _ = <-cs1.NewStepCh(), <-timeoutChan, <-cs1.NewStepCh() + validatePrecommit(t, cs1, 2, 0, privVals[0], nil, theBlockHash) // precommit nil but locked on proposal + signAddVoteToFrom(types.VoteTypePrecommit, cs1, cs2, propBlock.Hash(), propBlock.MakePartSet().Header()) // NOTE: conflicting precommits at same height +} + +// 4 vals, one precommits, other 3 polka at next round, so we unlock and precomit the polka +func TestLockPOLRelock(t *testing.T) { + css, privVals := simpleConsensusState(4) + cs1, cs2, cs3, cs4 := css[0], css[1], css[2], css[3] + cs1.newStepCh = make(chan *RoundState) // so it blocks + + timeoutChan := make(chan *types.EventDataRoundState) + voteChan := make(chan *types.EventDataVote) + evsw := events.NewEventSwitch() + evsw.OnStart() + evsw.AddListenerForEvent("tester", types.EventStringTimeoutPropose(), func(data types.EventData) { + timeoutChan <- data.(*types.EventDataRoundState) + }) + evsw.AddListenerForEvent("tester", types.EventStringTimeoutWait(), func(data types.EventData) { + timeoutChan <- data.(*types.EventDataRoundState) + }) + evsw.AddListenerForEvent("tester", types.EventStringVote(), func(data types.EventData) { + vote := data.(*types.EventDataVote) + // we only fire for our own votes + if bytes.Equal(cs1.privValidator.Address, vote.Address) { + voteChan <- vote + } + }) + cs1.SetFireable(evsw) + + // everything done from perspective of cs1 + + /* + Round1 (cs1, B) // B B B B// B nil B nil + + eg. cs2 and cs4 didn't see the 2/3 prevotes + */ + + // start round and wait for propose and prevote + cs1.EnterNewRound(cs1.Height, 0, false) + _, _, _ = <-cs1.NewStepCh(), <-voteChan, <-cs1.NewStepCh() + + theBlockHash := cs1.ProposalBlock.Hash() + + // wait to finish precommit after prevotes done + // we do this in a go routine with another channel since otherwise + // we may get deadlock with EnterPrecommit waiting to send on newStepCh and the final + // signAddVoteToFrom waiting for the cs.mtx.Lock + donePrecommit := make(chan struct{}) + go func() { + <-voteChan + <-cs1.NewStepCh() + donePrecommit <- struct{}{} + }() + signAddVoteToFromMany(types.VoteTypePrevote, cs1, cs1.ProposalBlock.Hash(), cs1.ProposalBlockParts.Header(), cs2, cs3, cs4) + <-donePrecommit + + // the proposed block should now be locked and our precommit added + validatePrecommit(t, cs1, 0, 0, privVals[0], theBlockHash, theBlockHash) + + donePrecommitWait := make(chan struct{}) + go func() { + // (note we're entering precommit for a second time this round) + // but with invalid args. then we EnterPrecommitWait, twice (?) + <-cs1.NewStepCh() + donePrecommitWait <- struct{}{} + }() + // add precommits from the rest + signAddVoteToFromMany(types.VoteTypePrecommit, cs1, nil, types.PartSetHeader{}, cs2, cs4) + signAddVoteToFrom(types.VoteTypePrecommit, cs1, cs3, cs1.ProposalBlock.Hash(), cs1.ProposalBlockParts.Header()) + <-donePrecommitWait + + // before we time out into new round, set next proposer + // and next proposal block + _, v1 := cs1.Validators.GetByAddress(privVals[0].Address) + v1.VotingPower = 1 + if updated := cs1.Validators.Update(v1); !updated { + t.Fatal("failed to update validator") + } + + cs2.decideProposal(cs2.Height, cs2.Round+1) + prop, propBlock := cs2.Proposal, cs2.ProposalBlock + if prop == nil || propBlock == nil { + t.Fatal("Failed to create proposal block with cs2") + } + + incrementRound(cs2, cs3, cs4) + + // timeout to new round + te := <-timeoutChan + if te.Step != RoundStepPrecommitWait.String() { + t.Fatalf("expected to timeout of precommit into new round. got %v", te.Step) + } + + log.Info("### ONTO ROUND 2") + + /* + Round2 (cs2, C) // B C C C // C C C _) + + cs1 changes lock! + */ + + // now we're on a new round and not the proposer + <-cs1.NewStepCh() + cs1.mtx.Lock() + // so set the proposal block + propBlockHash, propBlockParts := propBlock.Hash(), propBlock.MakePartSet() + cs1.Proposal, cs1.ProposalBlock, cs1.ProposalBlockParts = prop, propBlock, propBlockParts + cs1.mtx.Unlock() + // and wait for timeout + te = <-timeoutChan + if te.Step != RoundStepPropose.String() { + t.Fatalf("expected to timeout of propose. got %v", te.Step) + } + // go to prevote, prevote for locked block (not proposal), move on + _, _ = <-voteChan, <-cs1.NewStepCh() + validatePrevote(t, cs1, 0, privVals[0], theBlockHash) + + donePrecommit = make(chan struct{}) + go func() { + // we need this go routine because if we go into PrevoteWait it has to pull on newStepCh + // before the final vote will get added (because it holds the mutex). + select { + case <-cs1.NewStepCh(): // we're in PrevoteWait, go to Precommit + <-voteChan + case <-voteChan: // we went straight to Precommit + } + donePrecommit <- struct{}{} + }() + // now lets add prevotes from everyone else for the new block + signAddVoteToFromMany(types.VoteTypePrevote, cs1, propBlockHash, propBlockParts.Header(), cs2, cs3, cs4) + <-donePrecommit + + // we should have unlocked and locked on the new block + validatePrecommit(t, cs1, 1, 1, privVals[0], propBlockHash, propBlockHash) + + donePrecommitWait = make(chan struct{}) + go func() { + // (note we're entering precommit for a second time this round) + // but with invalid args. then we EnterPrecommitWait, + <-cs1.NewStepCh() + donePrecommitWait <- struct{}{} + }() + signAddVoteToFromMany(types.VoteTypePrecommit, cs1, propBlockHash, propBlockParts.Header(), cs2, cs3) + <-donePrecommitWait + + <-cs1.NewStepCh() + rs := <-cs1.NewStepCh() + if rs.Height != 2 { + t.Fatal("Expected height to increment") + } + + if hash, _, ok := rs.LastCommit.TwoThirdsMajority(); !ok || !bytes.Equal(hash, propBlockHash) { + t.Fatal("Expected block to get committed") + } +} + +// 4 vals, one precommits, other 3 polka at next round, so we unlock and precomit the polka +func TestLockPOLUnlock(t *testing.T) { + css, privVals := simpleConsensusState(4) + cs1, cs2, cs3, cs4 := css[0], css[1], css[2], css[3] + cs1.newStepCh = make(chan *RoundState) // so it blocks - cs.EnterPropose(1, 0) - rs := cs.GetRoundState() + timeoutChan := make(chan *types.EventDataRoundState) + voteChan := make(chan *types.EventDataVote) + evsw := events.NewEventSwitch() + evsw.OnStart() + evsw.AddListenerForEvent("tester", types.EventStringTimeoutPropose(), func(data types.EventData) { + timeoutChan <- data.(*types.EventDataRoundState) + }) + evsw.AddListenerForEvent("tester", types.EventStringTimeoutWait(), func(data types.EventData) { + timeoutChan <- data.(*types.EventDataRoundState) + }) + evsw.AddListenerForEvent("tester", types.EventStringVote(), func(data types.EventData) { + vote := data.(*types.EventDataVote) + // we only fire for our own votes + if bytes.Equal(cs1.privValidator.Address, vote.Address) { + voteChan <- vote + } + }) + cs1.SetFireable(evsw) - // Check that Proposal, ProposalBlock, ProposalBlockParts are set. - if rs.Proposal == nil { - t.Error("rs.Proposal should be set") + // everything done from perspective of cs1 + + /* + Round1 (cs1, B) // B B B B // B nil B nil + + eg. didn't see the 2/3 prevotes + */ + + // start round and wait for propose and prevote + cs1.EnterNewRound(cs1.Height, 0, false) + _, _, _ = <-cs1.NewStepCh(), <-voteChan, <-cs1.NewStepCh() + + theBlockHash := cs1.ProposalBlock.Hash() + + donePrecommit := make(chan struct{}) + go func() { + <-voteChan + <-cs1.NewStepCh() + donePrecommit <- struct{}{} + }() + signAddVoteToFromMany(types.VoteTypePrevote, cs1, cs1.ProposalBlock.Hash(), cs1.ProposalBlockParts.Header(), cs2, cs3, cs4) + <-donePrecommit + + // the proposed block should now be locked and our precommit added + validatePrecommit(t, cs1, 0, 0, privVals[0], theBlockHash, theBlockHash) + + donePrecommitWait := make(chan struct{}) + go func() { + <-cs1.NewStepCh() + donePrecommitWait <- struct{}{} + }() + // add precommits from the rest + signAddVoteToFromMany(types.VoteTypePrecommit, cs1, nil, types.PartSetHeader{}, cs2, cs4) + signAddVoteToFrom(types.VoteTypePrecommit, cs1, cs3, cs1.ProposalBlock.Hash(), cs1.ProposalBlockParts.Header()) + <-donePrecommitWait + + // before we time out into new round, set next proposer + // and next proposal block + _, v1 := cs1.Validators.GetByAddress(privVals[0].Address) + v1.VotingPower = 1 + if updated := cs1.Validators.Update(v1); !updated { + t.Fatal("failed to update validator") } - if rs.ProposalBlock == nil { - t.Error("rs.ProposalBlock should be set") + + cs2.decideProposal(cs2.Height, cs2.Round+1) + prop, propBlock := cs2.Proposal, cs2.ProposalBlock + if prop == nil || propBlock == nil { + t.Fatal("Failed to create proposal block with cs2") + } + + incrementRound(cs2, cs3, cs4) + + // timeout to new round + <-timeoutChan + + log.Info("#### ONTO ROUND 2") + /* + Round2 (cs2, C) // B nil nil nil // nil nil nil _ + + cs1 unlocks! + */ + + // now we're on a new round and not the proposer, + <-cs1.NewStepCh() + cs1.mtx.Lock() + // so set the proposal block + cs1.Proposal, cs1.ProposalBlock, cs1.ProposalBlockParts = prop, propBlock, propBlock.MakePartSet() + lockedBlockHash := cs1.LockedBlock.Hash() + cs1.mtx.Unlock() + // and wait for timeout + <-timeoutChan + + // go to prevote, prevote for locked block (not proposal) + _, _ = <-voteChan, <-cs1.NewStepCh() + validatePrevote(t, cs1, 0, privVals[0], lockedBlockHash) + + donePrecommit = make(chan struct{}) + go func() { + select { + case <-cs1.NewStepCh(): // we're in PrevoteWait, go to Precommit + <-voteChan + case <-voteChan: // we went straight to Precommit + } + donePrecommit <- struct{}{} + }() + // now lets add prevotes from everyone else for the new block + signAddVoteToFromMany(types.VoteTypePrevote, cs1, nil, types.PartSetHeader{}, cs2, cs3, cs4) + <-donePrecommit + + // we should have unlocked + // NOTE: we don't lock on nil, so LockedRound is still 0 + validatePrecommit(t, cs1, 1, 0, privVals[0], nil, nil) + + donePrecommitWait = make(chan struct{}) + go func() { + // the votes will bring us to new round right away + // we should timeout of it + _, _, _ = <-cs1.NewStepCh(), <-cs1.NewStepCh(), <-timeoutChan + donePrecommitWait <- struct{}{} + }() + signAddVoteToFromMany(types.VoteTypePrecommit, cs1, nil, types.PartSetHeader{}, cs2, cs3) + <-donePrecommitWait +} + +// 4 vals +// a polka at round 1 but we miss it +// then a polka at round 2 that we lock on +// then we see the polka from round 1 but shouldn't unlock +func TestLockPOLSafety1(t *testing.T) { + css, privVals := simpleConsensusState(4) + cs1, cs2, cs3, cs4 := css[0], css[1], css[2], css[3] + cs1.newStepCh = make(chan *RoundState) // so it blocks + + timeoutChan := make(chan *types.EventDataRoundState) + voteChan := make(chan *types.EventDataVote) + evsw := events.NewEventSwitch() + evsw.OnStart() + evsw.AddListenerForEvent("tester", types.EventStringTimeoutPropose(), func(data types.EventData) { + timeoutChan <- data.(*types.EventDataRoundState) + }) + evsw.AddListenerForEvent("tester", types.EventStringTimeoutWait(), func(data types.EventData) { + timeoutChan <- data.(*types.EventDataRoundState) + }) + evsw.AddListenerForEvent("tester", types.EventStringVote(), func(data types.EventData) { + vote := data.(*types.EventDataVote) + // we only fire for our own votes + if bytes.Equal(cs1.privValidator.Address, vote.Address) { + voteChan <- vote + } + }) + cs1.SetFireable(evsw) + + // start round and wait for propose and prevote + cs1.EnterNewRound(cs1.Height, 0, false) + _, _, _ = <-cs1.NewStepCh(), <-voteChan, <-cs1.NewStepCh() + + propBlock := cs1.ProposalBlock + + validatePrevote(t, cs1, 0, privVals[0], cs1.ProposalBlock.Hash()) + + // the others sign a polka but we don't see it + prevotes := signVoteMany(types.VoteTypePrevote, propBlock.Hash(), propBlock.MakePartSet().Header(), cs2, cs3, cs4) + + // before we time out into new round, set next proposer + // and next proposal block + _, v1 := cs1.Validators.GetByAddress(privVals[0].Address) + v1.VotingPower = 1 + if updated := cs1.Validators.Update(v1); !updated { + t.Fatal("failed to update validator") + } + + log.Warn("old prop", "hash", fmt.Sprintf("%X", propBlock.Hash())) + + // we do see them precommit nil + signAddVoteToFromMany(types.VoteTypePrecommit, cs1, nil, types.PartSetHeader{}, cs2, cs3, cs4) + + cs2.decideProposal(cs2.Height, cs2.Round+1) + prop, propBlock := cs2.Proposal, cs2.ProposalBlock + if prop == nil || propBlock == nil { + t.Fatal("Failed to create proposal block with cs2") } - if rs.ProposalBlockParts.Total() == 0 { - t.Error("rs.ProposalBlockParts should be set") + + incrementRound(cs2, cs3, cs4) + + log.Info("### ONTO ROUND 2") + /*Round2 + // we timeout and prevote our lock + // a polka happened but we didn't see it! + */ + + // now we're on a new round and not the proposer, + <-cs1.NewStepCh() + // so set proposal + cs1.mtx.Lock() + propBlockHash, propBlockParts := propBlock.Hash(), propBlock.MakePartSet() + cs1.Proposal, cs1.ProposalBlock, cs1.ProposalBlockParts = prop, propBlock, propBlockParts + cs1.mtx.Unlock() + // and wait for timeout + <-timeoutChan + if cs1.LockedBlock != nil { + t.Fatal("we should not be locked!") } + log.Warn("new prop", "hash", fmt.Sprintf("%X", propBlockHash)) + // go to prevote, prevote for proposal block + _, _ = <-voteChan, <-cs1.NewStepCh() + validatePrevote(t, cs1, 1, privVals[0], propBlockHash) + + // now we see the others prevote for it, so we should lock on it + donePrecommit := make(chan struct{}) + go func() { + select { + case <-cs1.NewStepCh(): // we're in PrevoteWait, go to Precommit + <-voteChan + case <-voteChan: // we went straight to Precommit + } + <-cs1.NewStepCh() + donePrecommit <- struct{}{} + }() + // now lets add prevotes from everyone else for nil + signAddVoteToFromMany(types.VoteTypePrevote, cs1, propBlockHash, propBlockParts.Header(), cs2, cs3, cs4) + <-donePrecommit + + // we should have precommitted + validatePrecommit(t, cs1, 1, 1, privVals[0], propBlockHash, propBlockHash) + + // now we see precommits for nil + donePrecommitWait := make(chan struct{}) + go func() { + // the votes will bring us to new round + // we should timeut of it and go to prevote + <-cs1.NewStepCh() + <-timeoutChan + donePrecommitWait <- struct{}{} + }() + signAddVoteToFromMany(types.VoteTypePrecommit, cs1, nil, types.PartSetHeader{}, cs2, cs3) + <-donePrecommitWait + + incrementRound(cs2, cs3, cs4) + + log.Info("### ONTO ROUND 3") + /*Round3 + we see the polka from round 1 but we shouldn't unlock! + */ + + // timeout of propose + _, _ = <-cs1.NewStepCh(), <-timeoutChan + + // finish prevote + _, _ = <-voteChan, <-cs1.NewStepCh() + + // we should prevote what we're locked on + validatePrevote(t, cs1, 2, privVals[0], propBlockHash) + + // add prevotes from the earlier round + addVoteToFromMany(cs1, prevotes, cs2, cs3, cs4) + + log.Warn("Done adding prevotes!") + + ensureNoNewStep(t, cs1) } -// TODO write better consensus state tests +// 4 vals. +// polka P1 at R1, P2 at R2, and P3 at R3, +// we lock on P1 at R1, don't see P2, and unlock using P3 at R3 +// then we should make sure we don't lock using P2 +func TestLockPOLSafety2(t *testing.T) { + css, privVals := simpleConsensusState(4) + cs1, cs2, cs3, cs4 := css[0], css[1], css[2], css[3] + cs1.newStepCh = make(chan *RoundState) // so it blocks + + timeoutChan := make(chan *types.EventDataRoundState) + voteChan := make(chan *types.EventDataVote) + evsw := events.NewEventSwitch() + evsw.OnStart() + evsw.AddListenerForEvent("tester", types.EventStringTimeoutPropose(), func(data types.EventData) { + timeoutChan <- data.(*types.EventDataRoundState) + }) + evsw.AddListenerForEvent("tester", types.EventStringTimeoutWait(), func(data types.EventData) { + timeoutChan <- data.(*types.EventDataRoundState) + }) + evsw.AddListenerForEvent("tester", types.EventStringVote(), func(data types.EventData) { + vote := data.(*types.EventDataVote) + // we only fire for our own votes + if bytes.Equal(cs1.privValidator.Address, vote.Address) { + voteChan <- vote + } + }) + cs1.SetFireable(evsw) + + // start round and wait for propose and prevote + cs1.EnterNewRound(cs1.Height, 0, false) + _, _, _ = <-cs1.NewStepCh(), <-voteChan, <-cs1.NewStepCh() + + theBlockHash := cs1.ProposalBlock.Hash() + + donePrecommit := make(chan struct{}) + go func() { + <-voteChan + <-cs1.NewStepCh() + donePrecommit <- struct{}{} + }() + signAddVoteToFromMany(types.VoteTypePrevote, cs1, cs1.ProposalBlock.Hash(), cs1.ProposalBlockParts.Header(), cs2, cs3, cs4) + <-donePrecommit + + // the proposed block should now be locked and our precommit added + validatePrecommit(t, cs1, 0, 0, privVals[0], theBlockHash, theBlockHash) + + donePrecommitWait := make(chan struct{}) + go func() { + <-cs1.NewStepCh() + donePrecommitWait <- struct{}{} + }() + // add precommits from the rest + signAddVoteToFromMany(types.VoteTypePrecommit, cs1, nil, types.PartSetHeader{}, cs2, cs4) + signAddVoteToFrom(types.VoteTypePrecommit, cs1, cs3, cs1.ProposalBlock.Hash(), cs1.ProposalBlockParts.Header()) + <-donePrecommitWait + + // before we time out into new round, set next proposer + // and next proposal block + _, v1 := cs1.Validators.GetByAddress(privVals[0].Address) + v1.VotingPower = 1 + if updated := cs1.Validators.Update(v1); !updated { + t.Fatal("failed to update validator") + } + + cs2.decideProposal(cs2.Height, cs2.Round+1) + prop, propBlock := cs2.Proposal, cs2.ProposalBlock + if prop == nil || propBlock == nil { + t.Fatal("Failed to create proposal block with cs2") + } + + incrementRound(cs2, cs3, cs4) + + // timeout to new round + <-timeoutChan + + log.Info("### ONTO Round 2") + /*Round2 + // we timeout and prevote our lock + // a polka happened but we didn't see it! + */ + + // now we're on a new round and not the proposer, so wait for timeout + _, _ = <-cs1.NewStepCh(), <-timeoutChan + // go to prevote, prevote for locked block + _, _ = <-voteChan, <-cs1.NewStepCh() + validatePrevote(t, cs1, 0, privVals[0], cs1.LockedBlock.Hash()) + + // the others sign a polka but we don't see it + prevotes := signVoteMany(types.VoteTypePrevote, propBlock.Hash(), propBlock.MakePartSet().Header(), cs2, cs3, cs4) + + // once we see prevotes for the next round we'll skip ahead + + incrementRound(cs2, cs3, cs4) + + log.Info("### ONTO Round 3") + /*Round3 + a polka for nil causes us to unlock + */ + + // these prevotes will send us straight to precommit at the higher round + donePrecommit = make(chan struct{}) + go func() { + select { + case <-cs1.NewStepCh(): // we're in PrevoteWait, go to Precommit + <-voteChan + case <-voteChan: // we went straight to Precommit + } + <-cs1.NewStepCh() + donePrecommit <- struct{}{} + }() + // now lets add prevotes from everyone else for nil + signAddVoteToFromMany(types.VoteTypePrevote, cs1, nil, types.PartSetHeader{}, cs2, cs3, cs4) + <-donePrecommit + + // we should have unlocked + // NOTE: we don't lock on nil, so LockedRound is still 0 + validatePrecommit(t, cs1, 2, 0, privVals[0], nil, nil) + + donePrecommitWait = make(chan struct{}) + go func() { + // the votes will bring us to new round right away + // we should timeut of it and go to prevote + <-cs1.NewStepCh() + // set the proposal block to be that which got a polka in R2 + cs1.mtx.Lock() + cs1.Proposal, cs1.ProposalBlock, cs1.ProposalBlockParts = prop, propBlock, propBlock.MakePartSet() + cs1.mtx.Unlock() + // timeout into prevote, finish prevote + _, _, _ = <-timeoutChan, <-voteChan, <-cs1.NewStepCh() + donePrecommitWait <- struct{}{} + }() + signAddVoteToFromMany(types.VoteTypePrecommit, cs1, nil, types.PartSetHeader{}, cs2, cs3) + <-donePrecommitWait + + log.Info("### ONTO ROUND 4") + /*Round4 + we see the polka from R2 + make sure we don't lock because of it! + */ + // new round and not proposer + // (we already timed out and stepped into prevote) + + log.Warn("adding prevotes from round 2") + + addVoteToFromMany(cs1, prevotes, cs2, cs3, cs4) + + log.Warn("Done adding prevotes!") + + // we should prevote it now + validatePrevote(t, cs1, 3, privVals[0], cs1.ProposalBlock.Hash()) + + // but we shouldn't precommit it + precommits := cs1.Votes.Precommits(3) + vote := precommits.GetByIndex(0) + if vote != nil { + t.Fatal("validator precommitted at round 4 based on an old polka") + } +} + +//------------------------------------------------------------------------------------------ +// SlashingSuite + +func TestSlashingPrevotes(t *testing.T) { + css, _ := simpleConsensusState(2) + cs1, cs2 := css[0], css[1] + cs1.newStepCh = make(chan *RoundState) // so it blocks + + // start round and wait for propose and prevote + cs1.EnterNewRound(cs1.Height, 0, false) + _, _ = <-cs1.NewStepCh(), <-cs1.NewStepCh() + + // we should now be stuck in limbo forever, waiting for more prevotes + // add one for a different block should cause us to go into prevote wait + hash := cs1.ProposalBlock.Hash() + hash[0] = byte(hash[0]+1) % 255 + signAddVoteToFrom(types.VoteTypePrevote, cs1, cs2, hash, cs1.ProposalBlockParts.Header()) + + // pass prevote wait + <-cs1.NewStepCh() + + // NOTE: we have to send the vote for different block first so we don't just go into precommit round right + // away and ignore more prevotes (and thus fail to slash!) + + // add the conflicting vote + signAddVoteToFrom(types.VoteTypePrevote, cs1, cs2, cs1.ProposalBlock.Hash(), cs1.ProposalBlockParts.Header()) + + // conflicting vote should cause us to broadcast dupeout tx on mempool + txs := cs1.mempoolReactor.Mempool.GetProposalTxs() + if len(txs) != 1 { + t.Fatal("expected to find a transaction in the mempool after double signing") + } + dupeoutTx, ok := txs[0].(*types.DupeoutTx) + if !ok { + t.Fatal("expected to find DupeoutTx in mempool after double signing") + } + + if !bytes.Equal(dupeoutTx.Address, cs2.privValidator.Address) { + t.Fatalf("expected DupeoutTx for %X, got %X", cs2.privValidator.Address, dupeoutTx.Address) + } + + // TODO: validate the sig +} + +func TestSlashingPrecommits(t *testing.T) { + css, _ := simpleConsensusState(2) + cs1, cs2 := css[0], css[1] + cs1.newStepCh = make(chan *RoundState) // so it blocks + + // start round and wait for propose and prevote + cs1.EnterNewRound(cs1.Height, 0, false) + _, _ = <-cs1.NewStepCh(), <-cs1.NewStepCh() + + // add prevote from cs2 + signAddVoteToFrom(types.VoteTypePrevote, cs1, cs2, cs1.ProposalBlock.Hash(), cs1.ProposalBlockParts.Header()) + + // wait to finish precommit + <-cs1.NewStepCh() + + // we should now be stuck in limbo forever, waiting for more prevotes + // add one for a different block should cause us to go into prevote wait + hash := cs1.ProposalBlock.Hash() + hash[0] = byte(hash[0]+1) % 255 + signAddVoteToFrom(types.VoteTypePrecommit, cs1, cs2, hash, cs1.ProposalBlockParts.Header()) + + // pass prevote wait + <-cs1.NewStepCh() + + // NOTE: we have to send the vote for different block first so we don't just go into precommit round right + // away and ignore more prevotes (and thus fail to slash!) + + // add precommit from cs2 + signAddVoteToFrom(types.VoteTypePrecommit, cs1, cs2, cs1.ProposalBlock.Hash(), cs1.ProposalBlockParts.Header()) + + // conflicting vote should cause us to broadcast dupeout tx on mempool + txs := cs1.mempoolReactor.Mempool.GetProposalTxs() + if len(txs) != 1 { + t.Fatal("expected to find a transaction in the mempool after double signing") + } + dupeoutTx, ok := txs[0].(*types.DupeoutTx) + if !ok { + t.Fatal("expected to find DupeoutTx in mempool after double signing") + } + + if !bytes.Equal(dupeoutTx.Address, cs2.privValidator.Address) { + t.Fatalf("expected DupeoutTx for %X, got %X", cs2.privValidator.Address, dupeoutTx.Address) + } + + // TODO: validate the sig + +} + +//------------------------------------------------------------------------------------------ +// CatchupSuite + +//------------------------------------------------------------------------------------------ +// HaltSuite + +// 4 vals. +// we receive a final precommit after going into next round, but others might have gone to commit already! +func TestHalt1(t *testing.T) { + css, privVals := simpleConsensusState(4) + cs1, cs2, cs3, cs4 := css[0], css[1], css[2], css[3] + cs1.newStepCh = make(chan *RoundState) // so it blocks + + timeoutChan := make(chan struct{}) + evsw := events.NewEventSwitch() + evsw.OnStart() + evsw.AddListenerForEvent("tester", types.EventStringTimeoutWait(), func(data types.EventData) { + timeoutChan <- struct{}{} + }) + cs1.SetFireable(evsw) + + // start round and wait for propose and prevote + cs1.EnterNewRound(cs1.Height, 0, false) + _, _ = <-cs1.NewStepCh(), <-cs1.NewStepCh() + + theBlockHash := cs1.ProposalBlock.Hash() + + donePrecommit := make(chan struct{}) + go func() { + <-cs1.NewStepCh() + donePrecommit <- struct{}{} + }() + signAddVoteToFromMany(types.VoteTypePrevote, cs1, cs1.ProposalBlock.Hash(), cs1.ProposalBlockParts.Header(), cs3, cs4) + <-donePrecommit + + // the proposed block should now be locked and our precommit added + validatePrecommit(t, cs1, 0, 0, privVals[0], theBlockHash, theBlockHash) + + donePrecommitWait := make(chan struct{}) + go func() { + <-cs1.NewStepCh() + donePrecommitWait <- struct{}{} + }() + // add precommits from the rest + signAddVoteToFrom(types.VoteTypePrecommit, cs1, cs2, nil, types.PartSetHeader{}) // didnt receive proposal + signAddVoteToFrom(types.VoteTypePrecommit, cs1, cs3, cs1.ProposalBlock.Hash(), cs1.ProposalBlockParts.Header()) + // we receive this later, but cs3 might receive it earlier and with ours will go to commit! + precommit4 := signVote(cs4, types.VoteTypePrecommit, cs1.ProposalBlock.Hash(), cs1.ProposalBlockParts.Header()) + <-donePrecommitWait + + incrementRound(cs2, cs3, cs4) + + // timeout to new round + <-timeoutChan + + log.Info("### ONTO ROUND 2") + /*Round2 + // we timeout and prevote our lock + // a polka happened but we didn't see it! + */ + + // go to prevote, prevote for locked block + _, _ = <-cs1.NewStepCh(), <-cs1.NewStepCh() + validatePrevote(t, cs1, 0, privVals[0], cs1.LockedBlock.Hash()) + + // now we receive the precommit from the previous round + addVoteToFrom(cs1, cs4, precommit4) + + // receiving that precommit should take us straight to commit + ensureNewStep(t, cs1) + log.Warn("done enter commit!") + + // update to state + ensureNewStep(t, cs1) + + if cs1.Height != 2 { + t.Fatal("expected height to increment") + } +} diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/consensus/test.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/consensus/test.go index 684c7b7737510e7615e840939a1011fb66b350e2..eb5ac9391afa748238672187cccd1df2d81e6aba 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/consensus/test.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/consensus/test.go @@ -1,15 +1,221 @@ package consensus import ( - "sort" + "bytes" + "fmt" + "testing" + "time" bc "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/blockchain" dbm "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/db" mempl "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/mempool" + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/p2p" sm "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/state" + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/types" ) -func randConsensusState() (*ConsensusState, []*sm.PrivValidator) { +//------------------------------------------------------------------------------- +// utils + +func changeProposer(t *testing.T, perspectiveOf, newProposer *ConsensusState) *types.Block { + _, v1 := perspectiveOf.Validators.GetByAddress(perspectiveOf.privValidator.Address) + v1.Accum, v1.VotingPower = 0, 0 + if updated := perspectiveOf.Validators.Update(v1); !updated { + t.Fatal("failed to update validator") + } + _, v2 := perspectiveOf.Validators.GetByAddress(newProposer.privValidator.Address) + v2.Accum, v2.VotingPower = 100, 100 + if updated := perspectiveOf.Validators.Update(v2); !updated { + t.Fatal("failed to update validator") + } + + // make the proposal + propBlock, _ := newProposer.createProposalBlock() + if propBlock == nil { + t.Fatal("Failed to create proposal block with cs2") + } + return propBlock +} + +func fixVotingPower(t *testing.T, cs1 *ConsensusState, addr2 []byte) { + _, v1 := cs1.Validators.GetByAddress(cs1.privValidator.Address) + _, v2 := cs1.Validators.GetByAddress(addr2) + v1.Accum, v1.VotingPower = v2.Accum, v2.VotingPower + if updated := cs1.Validators.Update(v1); !updated { + t.Fatal("failed to update validator") + } +} + +func addVoteToFromMany(to *ConsensusState, votes []*types.Vote, froms ...*ConsensusState) { + if len(votes) != len(froms) { + panic("len(votes) and len(froms) must match") + } + for i, from := range froms { + addVoteToFrom(to, from, votes[i]) + } +} + +func addVoteToFrom(to, from *ConsensusState, vote *types.Vote) { + valIndex, _ := to.Validators.GetByAddress(from.privValidator.Address) + added, err := to.TryAddVote(valIndex, vote, "") + if _, ok := err.(*types.ErrVoteConflictingSignature); ok { + // let it fly + } else if !added { + panic("Failed to add vote") + } else if err != nil { + panic(fmt.Sprintln("Failed to add vote:", err)) + } +} + +func signVote(from *ConsensusState, voteType byte, hash []byte, header types.PartSetHeader) *types.Vote { + vote, err := from.signVote(voteType, hash, header) + if err != nil { + panic(fmt.Sprintln("Failed to sign vote", err)) + } + return vote +} + +func signVoteMany(voteType byte, hash []byte, header types.PartSetHeader, css ...*ConsensusState) []*types.Vote { + votes := make([]*types.Vote, len(css)) + for i, cs := range css { + votes[i] = signVote(cs, voteType, hash, header) + } + return votes +} + +// add vote to one cs from another +func signAddVoteToFromMany(voteType byte, to *ConsensusState, hash []byte, header types.PartSetHeader, froms ...*ConsensusState) { + for _, from := range froms { + vote := signVote(from, voteType, hash, header) + addVoteToFrom(to, from, vote) + } +} + +func signAddVoteToFrom(voteType byte, to, from *ConsensusState, hash []byte, header types.PartSetHeader) *types.Vote { + vote := signVote(from, voteType, hash, header) + addVoteToFrom(to, from, vote) + return vote +} + +func ensureNoNewStep(t *testing.T, cs *ConsensusState) { + timeout := time.NewTicker(2 * time.Second) + select { + case <-timeout.C: + break + case <-cs.NewStepCh(): + panic("We should be stuck waiting for more votes, not moving to the next step") + } +} + +func ensureNewStep(t *testing.T, cs *ConsensusState) { + timeout := time.NewTicker(2 * time.Second) + select { + case <-timeout.C: + panic("We should have gone to the next step, not be stuck waiting") + case <-cs.NewStepCh(): + break + } +} + +func validatePrevote(t *testing.T, cs *ConsensusState, round int, privVal *types.PrivValidator, blockHash []byte) { + prevotes := cs.Votes.Prevotes(round) + var vote *types.Vote + if vote = prevotes.GetByAddress(privVal.Address); vote == nil { + panic("Failed to find prevote from validator") + } + if blockHash == nil { + if vote.BlockHash != nil { + panic(fmt.Sprintf("Expected prevote to be for nil, got %X", vote.BlockHash)) + } + } else { + if !bytes.Equal(vote.BlockHash, blockHash) { + panic(fmt.Sprintf("Expected prevote to be for %X, got %X", blockHash, vote.BlockHash)) + } + } +} + +func incrementRound(css ...*ConsensusState) { + for _, cs := range css { + cs.Round += 1 + } +} + +func validatePrecommit(t *testing.T, cs *ConsensusState, thisRound, lockRound int, privVal *types.PrivValidator, votedBlockHash, lockedBlockHash []byte) { + precommits := cs.Votes.Precommits(thisRound) + var vote *types.Vote + if vote = precommits.GetByAddress(privVal.Address); vote == nil { + panic("Failed to find precommit from validator") + } + + if votedBlockHash == nil { + if vote.BlockHash != nil { + panic("Expected precommit to be for nil") + } + } else { + if !bytes.Equal(vote.BlockHash, votedBlockHash) { + panic("Expected precommit to be for proposal block") + } + } + + if lockedBlockHash == nil { + if cs.LockedRound != lockRound || cs.LockedBlock != nil { + panic(fmt.Sprintf("Expected to be locked on nil at round %d. Got locked at round %d with block %v", lockRound, cs.LockedRound, cs.LockedBlock)) + } + } else { + if cs.LockedRound != lockRound || !bytes.Equal(cs.LockedBlock.Hash(), lockedBlockHash) { + panic(fmt.Sprintf("Expected block to be locked on round %d, got %d. Got locked block %X, expected %X", lockRound, cs.LockedRound, cs.LockedBlock.Hash(), lockedBlockHash)) + } + } + +} + +func validatePrevoteAndPrecommit(t *testing.T, cs *ConsensusState, thisRound, lockRound int, privVal *types.PrivValidator, votedBlockHash, lockedBlockHash []byte, f func()) { + // verify the prevote + validatePrevote(t, cs, thisRound, privVal, votedBlockHash) + if f != nil { + f() + } + // wait to finish precommit + <-cs.NewStepCh() + // verify precommit + cs.mtx.Lock() + validatePrecommit(t, cs, thisRound, lockRound, privVal, votedBlockHash, lockedBlockHash) + cs.mtx.Unlock() +} + +func simpleConsensusState(nValidators int) ([]*ConsensusState, []*types.PrivValidator) { + // Get State + state, privAccs, privVals := sm.RandGenesisState(10, true, 1000, nValidators, false, 10) + _, _ = privAccs, privVals + + fmt.Println(state.BondedValidators) + + css := make([]*ConsensusState, nValidators) + for i := 0; i < nValidators; i++ { + // Get BlockStore + blockDB := dbm.NewMemDB() + blockStore := bc.NewBlockStore(blockDB) + + // Make MempoolReactor + mempool := mempl.NewMempool(state.Copy()) + mempoolReactor := mempl.NewMempoolReactor(mempool) + + mempoolReactor.SetSwitch(p2p.NewSwitch()) + + // Make ConsensusReactor + cs := NewConsensusState(state, blockStore, mempoolReactor) + cs.SetPrivValidator(privVals[i]) + + // read off the NewHeightStep + <-cs.NewStepCh() + + css[i] = cs + } + + return css, privVals +} + +func randConsensusState() (*ConsensusState, []*types.PrivValidator) { state, _, privValidators := sm.RandGenesisState(20, false, 1000, 10, false, 1000) blockStore := bc.NewBlockStore(dbm.NewMemDB()) mempool := mempl.NewMempool(state) @@ -17,16 +223,3 @@ func randConsensusState() (*ConsensusState, []*sm.PrivValidator) { cs := NewConsensusState(state, blockStore, mempoolReactor) return cs, privValidators } - -func randVoteSet(height int, round int, type_ byte, numValidators int, votingPower int64) (*VoteSet, *sm.ValidatorSet, []*sm.PrivValidator) { - vals := make([]*sm.Validator, numValidators) - privValidators := make([]*sm.PrivValidator, numValidators) - for i := 0; i < numValidators; i++ { - _, val, privValidator := sm.RandValidator(false, votingPower) - vals[i] = val - privValidators[i] = privValidator - } - valSet := sm.NewValidatorSet(vals) - sort.Sort(sm.PrivValidatorsByAddress(privValidators)) - return NewVoteSet(height, round, type_, valSet), valSet, privValidators -} diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/db/level_db.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/db/level_db.go index 66cf9190a9f773a6b432bd379ab9ddcaead54415..587c3ee3f0c70306225280c0c8ae12d5ce771409 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/db/level_db.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/db/level_db.go @@ -2,9 +2,9 @@ package db import ( "fmt" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/errors" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt" + "github.com/syndtr/goleveldb/leveldb" + "github.com/syndtr/goleveldb/leveldb/errors" + "github.com/syndtr/goleveldb/leveldb/opt" "path" . "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/common" diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/events/event_cache.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/events/event_cache.go index 3231fe0d41006b77d8476689f022925643ee1124..c37793f95a8a3796c00ccba2b0a7fc343cea5897 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/events/event_cache.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/events/event_cache.go @@ -1,5 +1,9 @@ package events +import ( + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/types" +) + const ( eventsBufferSize = 1000 ) @@ -22,20 +26,20 @@ func NewEventCache(evsw Fireable) *EventCache { // a cached event type eventInfo struct { event string - msg interface{} + data types.EventData } // Cache an event to be fired upon finality. -func (evc *EventCache) FireEvent(event string, msg interface{}) { +func (evc *EventCache) FireEvent(event string, data types.EventData) { // append to list - evc.events = append(evc.events, eventInfo{event, msg}) + evc.events = append(evc.events, eventInfo{event, data}) } // Fire events by running evsw.FireEvent on all cached events. Blocks. // Clears cached events func (evc *EventCache) Flush() { for _, ei := range evc.events { - evc.evsw.FireEvent(ei.event, ei.msg) + evc.evsw.FireEvent(ei.event, ei.data) } evc.events = make([]eventInfo, eventsBufferSize) } diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/events/events.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/events/events.go index 07ef12b9711f78bcad5fd717577b40baa331ee36..1b9f08f96569e95dbe0f1cc1f8ea77bfc1b757ab 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/events/events.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/events/events.go @@ -4,6 +4,7 @@ import ( "sync" . "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/common" + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/types" ) // reactors and other modules should export @@ -14,7 +15,7 @@ type Eventable interface { // an event switch or cache implements fireable type Fireable interface { - FireEvent(event string, msg interface{}) + FireEvent(event string, data types.EventData) } type EventSwitch struct { @@ -31,10 +32,11 @@ func NewEventSwitch() *EventSwitch { return evsw } -func (evsw *EventSwitch) OnStart() { +func (evsw *EventSwitch) OnStart() error { evsw.BaseService.OnStart() evsw.eventCells = make(map[string]*eventCell) evsw.listeners = make(map[string]*eventListener) + return nil } func (evsw *EventSwitch) OnStop() { @@ -43,7 +45,7 @@ func (evsw *EventSwitch) OnStop() { evsw.listeners = nil } -func (evsw *EventSwitch) AddListenerForEvent(listenerId, event string, cb eventCallback) { +func (evsw *EventSwitch) AddListenerForEvent(listenerID, event string, cb eventCallback) { // Get/Create eventCell and listener evsw.mtx.Lock() eventCell := evsw.eventCells[event] @@ -51,23 +53,23 @@ func (evsw *EventSwitch) AddListenerForEvent(listenerId, event string, cb eventC eventCell = newEventCell() evsw.eventCells[event] = eventCell } - listener := evsw.listeners[listenerId] + listener := evsw.listeners[listenerID] if listener == nil { - listener = newEventListener(listenerId) - evsw.listeners[listenerId] = listener + listener = newEventListener(listenerID) + evsw.listeners[listenerID] = listener } evsw.mtx.Unlock() // Add event and listener - eventCell.AddListener(listenerId, cb) + eventCell.AddListener(listenerID, cb) listener.AddEvent(event) } -func (evsw *EventSwitch) RemoveListener(listenerId string) { +func (evsw *EventSwitch) RemoveListener(listenerID string) { // Get and remove listener evsw.mtx.RLock() - listener := evsw.listeners[listenerId] - delete(evsw.listeners, listenerId) + listener := evsw.listeners[listenerID] + delete(evsw.listeners, listenerID) evsw.mtx.RUnlock() if listener == nil { @@ -77,11 +79,11 @@ func (evsw *EventSwitch) RemoveListener(listenerId string) { // Remove callback for each event. listener.SetRemoved() for _, event := range listener.GetEvents() { - evsw.RemoveListenerForEvent(event, listenerId) + evsw.RemoveListenerForEvent(event, listenerID) } } -func (evsw *EventSwitch) RemoveListenerForEvent(event string, listenerId string) { +func (evsw *EventSwitch) RemoveListenerForEvent(event string, listenerID string) { // Get eventCell evsw.mtx.Lock() eventCell := evsw.eventCells[event] @@ -91,8 +93,8 @@ func (evsw *EventSwitch) RemoveListenerForEvent(event string, listenerId string) return } - // Remove listenerId from eventCell - numListeners := eventCell.RemoveListener(listenerId) + // Remove listenerID from eventCell + numListeners := eventCell.RemoveListener(listenerID) // Maybe garbage collect eventCell. if numListeners == 0 { @@ -107,7 +109,7 @@ func (evsw *EventSwitch) RemoveListenerForEvent(event string, listenerId string) } } -func (evsw *EventSwitch) FireEvent(event string, msg interface{}) { +func (evsw *EventSwitch) FireEvent(event string, data types.EventData) { // Get the eventCell evsw.mtx.RLock() eventCell := evsw.eventCells[event] @@ -118,7 +120,7 @@ func (evsw *EventSwitch) FireEvent(event string, msg interface{}) { } // Fire event for all listeners in eventCell - eventCell.FireEvent(msg) + eventCell.FireEvent(data) } //----------------------------------------------------------------------------- @@ -135,31 +137,31 @@ func newEventCell() *eventCell { } } -func (cell *eventCell) AddListener(listenerId string, cb eventCallback) { +func (cell *eventCell) AddListener(listenerID string, cb eventCallback) { cell.mtx.Lock() - cell.listeners[listenerId] = cb + cell.listeners[listenerID] = cb cell.mtx.Unlock() } -func (cell *eventCell) RemoveListener(listenerId string) int { +func (cell *eventCell) RemoveListener(listenerID string) int { cell.mtx.Lock() - delete(cell.listeners, listenerId) + delete(cell.listeners, listenerID) numListeners := len(cell.listeners) cell.mtx.Unlock() return numListeners } -func (cell *eventCell) FireEvent(msg interface{}) { +func (cell *eventCell) FireEvent(data types.EventData) { cell.mtx.RLock() for _, listener := range cell.listeners { - listener(msg) + listener(data) } cell.mtx.RUnlock() } //----------------------------------------------------------------------------- -type eventCallback func(msg interface{}) +type eventCallback func(data types.EventData) type eventListener struct { id string diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/consensus/types/config.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/mempool/config.go similarity index 92% rename from Godeps/_workspace/src/github.com/tendermint/tendermint/consensus/types/config.go rename to Godeps/_workspace/src/github.com/tendermint/tendermint/mempool/config.go index a9f0e602e3812fe9dd8315354bc68eddec41ccd0..233bb88c2de02d6e4b61e803a9950893c5769d18 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/consensus/types/config.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/mempool/config.go @@ -1,4 +1,4 @@ -package consensus +package mempool import ( cfg "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/config" diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/mempool/mempool_test.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/mempool/mempool_test.go new file mode 100644 index 0000000000000000000000000000000000000000..ab6e4e993dc27275b67a201fa6295c1a908986a2 --- /dev/null +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/mempool/mempool_test.go @@ -0,0 +1,273 @@ +package mempool + +import ( + "fmt" + "sync" + "testing" + "time" + + acm "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/account" + _ "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/config/tendermint_test" + sm "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/state" + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/types" +) + +var someAddr = []byte("ABCDEFGHIJABCDEFGHIJ") + +// number of txs +var nTxs = 100 + +// what the ResetInfo should look like after ResetForBlockAndState +var TestResetInfoData = ResetInfo{ + Included: []Range{ + Range{0, 5}, + Range{10, 10}, + Range{30, 5}, + }, + Invalid: []Range{ + Range{5, 5}, + Range{20, 8}, // let 28 and 29 be valid + Range{35, 64}, // let 99 be valid + }, +} + +// inverse of the ResetInfo +var notInvalidNotIncluded = map[int]struct{}{ + 28: struct{}{}, + 29: struct{}{}, + 99: struct{}{}, +} + +func newSendTx(t *testing.T, mempool *Mempool, from *acm.PrivAccount, to []byte, amt int64) types.Tx { + tx := types.NewSendTx() + tx.AddInput(mempool.GetCache(), from.PubKey, amt) + tx.AddOutput(to, amt) + tx.SignInput(config.GetString("chain_id"), 0, from) + if err := mempool.AddTx(tx); err != nil { + t.Fatal(err) + } + return tx +} + +func addTxs(t *testing.T, mempool *Mempool, lastAcc *acm.PrivAccount, privAccs []*acm.PrivAccount) []types.Tx { + txs := make([]types.Tx, nTxs) + for i := 0; i < nTxs; i++ { + if _, ok := notInvalidNotIncluded[i]; ok { + txs[i] = newSendTx(t, mempool, lastAcc, someAddr, 10) + } else { + txs[i] = newSendTx(t, mempool, privAccs[i%len(privAccs)], privAccs[(i+1)%len(privAccs)].Address, 5) + } + } + return txs +} + +func makeBlock(mempool *Mempool) *types.Block { + txs := mempool.GetProposalTxs() + var includedTxs []types.Tx + for _, rid := range TestResetInfoData.Included { + includedTxs = append(includedTxs, txs[rid.Start:rid.Start+rid.Length]...) + } + + mempool.mtx.Lock() + state := mempool.state + state.LastBlockHeight += 1 + mempool.mtx.Unlock() + return &types.Block{ + Header: &types.Header{ + ChainID: state.ChainID, + Height: state.LastBlockHeight, + NumTxs: len(includedTxs), + }, + Data: &types.Data{ + Txs: includedTxs, + }, + } +} + +// Add txs. Grab chunks to put in block. All the others become invalid because of nonce errors except those in notInvalidNotIncluded +func TestResetInfo(t *testing.T) { + amtPerAccount := int64(100000) + state, privAccs, _ := sm.RandGenesisState(6, false, amtPerAccount, 1, true, 100) + + mempool := NewMempool(state) + + lastAcc := privAccs[5] // we save him (his tx wont become invalid) + privAccs = privAccs[:5] + + txs := addTxs(t, mempool, lastAcc, privAccs) + + // its actually an invalid block since we're skipping nonces + // but all we care about is how the mempool responds after + block := makeBlock(mempool) + + ri := mempool.ResetForBlockAndState(block, state) + + if len(ri.Included) != len(TestResetInfoData.Included) { + t.Fatalf("invalid number of included ranges. Got %d, expected %d\n", len(ri.Included), len(TestResetInfoData.Included)) + } + + if len(ri.Invalid) != len(TestResetInfoData.Invalid) { + t.Fatalf("invalid number of invalid ranges. Got %d, expected %d\n", len(ri.Invalid), len(TestResetInfoData.Invalid)) + } + + for i, rid := range ri.Included { + inc := TestResetInfoData.Included[i] + if rid.Start != inc.Start { + t.Fatalf("Invalid start of range. Got %d, expected %d\n", inc.Start, rid.Start) + } + if rid.Length != inc.Length { + t.Fatalf("Invalid length of range. Got %d, expected %d\n", inc.Length, rid.Length) + } + } + + txs = mempool.GetProposalTxs() + if len(txs) != len(notInvalidNotIncluded) { + t.Fatalf("Expected %d txs left in mempool. Got %d", len(notInvalidNotIncluded), len(txs)) + } +} + +//------------------------------------------------------------------------------------------ + +type TestPeer struct { + sync.Mutex + running bool + height int + + t *testing.T + + received int + txs map[string]int + + timeoutFail int + + done chan int +} + +func newPeer(t *testing.T, state *sm.State) *TestPeer { + return &TestPeer{ + running: true, + height: state.LastBlockHeight, + t: t, + txs: make(map[string]int), + done: make(chan int), + } +} + +func (tp *TestPeer) IsRunning() bool { + tp.Lock() + defer tp.Unlock() + return tp.running +} + +func (tp *TestPeer) SetRunning(running bool) { + tp.Lock() + defer tp.Unlock() + tp.running = running +} + +func (tp *TestPeer) Send(chID byte, msg interface{}) bool { + if tp.timeoutFail > 0 { + time.Sleep(time.Second * time.Duration(tp.timeoutFail)) + return false + } + tx := msg.(*TxMessage).Tx + id := types.TxID(config.GetString("chain_id"), tx) + if _, ok := tp.txs[string(id)]; ok { + tp.t.Fatal("received the same tx twice!") + } + tp.txs[string(id)] = tp.received + tp.received += 1 + tp.done <- tp.received + return true +} + +func (tp *TestPeer) Get(key string) interface{} { + return tp +} + +func (tp *TestPeer) GetHeight() int { + return tp.height +} + +func TestBroadcast(t *testing.T) { + state, privAccs, _ := sm.RandGenesisState(6, false, 10000, 1, true, 100) + mempool := NewMempool(state) + reactor := NewMempoolReactor(mempool) + reactor.Start() + + lastAcc := privAccs[5] // we save him (his tx wont become invalid) + privAccs = privAccs[:5] + + peer := newPeer(t, state) + newBlockChan := make(chan ResetInfo) + tickerChan := make(chan time.Time) + go reactor.broadcastTxRoutine(tickerChan, newBlockChan, peer) + + // we don't broadcast any before updating + fmt.Println("dont broadcast any") + addTxs(t, mempool, lastAcc, privAccs) + block := makeBlock(mempool) + ri := mempool.ResetForBlockAndState(block, state) + newBlockChan <- ri + peer.height = ri.Height + tickerChan <- time.Now() + pullTxs(t, peer, len(mempool.txs)) // should have sent whatever txs are left (3) + + toBroadcast := []int{1, 3, 7, 9, 11, 12, 18, 20, 21, 28, 29, 30, 31, 34, 35, 36, 50, 90, 99, 100} + for _, N := range toBroadcast { + peer = resetPeer(t, reactor, mempool, state, tickerChan, newBlockChan, peer) + + // we broadcast N txs before updating + fmt.Println("broadcast", N) + addTxs(t, mempool, lastAcc, privAccs) + txsToSendPerCheck = N + tickerChan <- time.Now() + pullTxs(t, peer, txsToSendPerCheck) // should have sent N txs + block = makeBlock(mempool) + ri := mempool.ResetForBlockAndState(block, state) + newBlockChan <- ri + peer.height = ri.Height + txsToSendPerCheck = 100 + tickerChan <- time.Now() + left := len(mempool.txs) + if N > 99 { + left -= 3 + } else if N > 29 { + left -= 2 + } else if N > 28 { + left -= 1 + } + pullTxs(t, peer, left) // should have sent whatever txs are left that havent been sent + } +} + +func pullTxs(t *testing.T, peer *TestPeer, N int) { + timer := time.NewTicker(time.Second * 2) + for i := 0; i < N; i++ { + select { + case <-peer.done: + case <-timer.C: + panic(fmt.Sprintf("invalid number of received messages. Got %d, expected %d\n", i, N)) + } + } + + if N == 0 { + select { + case <-peer.done: + t.Fatalf("should not have sent any more txs") + case <-timer.C: + } + } +} + +func resetPeer(t *testing.T, reactor *MempoolReactor, mempool *Mempool, state *sm.State, tickerChan chan time.Time, newBlockChan chan ResetInfo, peer *TestPeer) *TestPeer { + // reset peer + mempool.txs = []types.Tx{} + mempool.state = state + mempool.cache = sm.NewBlockCache(state) + peer.SetRunning(false) + tickerChan <- time.Now() + peer = newPeer(t, state) + go reactor.broadcastTxRoutine(tickerChan, newBlockChan, peer) + return peer +} diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/mempool/reactor.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/mempool/reactor.go index 6db4053986472d39c354c732da20d1f142e88639..fb3ff7d74cb6b7eaa235a5868fc0c527a2884b6c 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/mempool/reactor.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/mempool/reactor.go @@ -20,7 +20,6 @@ var ( type MempoolReactor struct { p2p.BaseReactor - sw *p2p.Switch Mempool *Mempool evsw events.Fireable @@ -34,15 +33,11 @@ func NewMempoolReactor(mempool *Mempool) *MempoolReactor { return memR } -// func (memR *MempoolReactor) OnStart() { memR.BaseReactor.OnStart() } - -// func (memR *MempoolReactor) OnStop() { memR.BaseReactor.OnStop() } - // Implements Reactor func (memR *MempoolReactor) GetChannels() []*p2p.ChannelDescriptor { return []*p2p.ChannelDescriptor{ &p2p.ChannelDescriptor{ - Id: MempoolChannel, + ID: MempoolChannel, Priority: 5, }, } @@ -57,7 +52,7 @@ func (pexR *MempoolReactor) RemovePeer(peer *p2p.Peer, reason interface{}) { } // Implements Reactor -func (memR *MempoolReactor) Receive(chId byte, src *p2p.Peer, msgBytes []byte) { +func (memR *MempoolReactor) Receive(chID byte, src *p2p.Peer, msgBytes []byte) { _, msg, err := DecodeMessage(msgBytes) if err != nil { log.Warn("Error decoding message", "error", err) diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/merkle/simple_tree.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/merkle/simple_tree.go index be2837c8bbd7748362cd973e7919c52ab3f977d7..31ad41c16da56bf83acae10c1742803f2ec9f30b 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/merkle/simple_tree.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/merkle/simple_tree.go @@ -27,6 +27,7 @@ package merkle import ( "bytes" "fmt" + "sort" "github.com/eris-ltd/eris-db/Godeps/_workspace/src/code.google.com/p/go.crypto/ripemd160" @@ -89,6 +90,58 @@ func SimpleHashFromHashables(items []Hashable) []byte { return SimpleHashFromHashes(hashes) } +// Convenience for SimpleHashFromHashes. +func SimpleHashFromMap(m map[string]interface{}) []byte { + kpPairsH := MakeSortedKVPairs(m) + return SimpleHashFromHashables(kpPairsH) +} + +//-------------------------------------------------------------------------------- + +/* Convenience struct for key-value pairs. +A list of KVPairs is hashed via `SimpleHashFromHashables`. +NOTE: Each `Value` is encoded for hashing without extra type information, +so the user is presumed to be aware of the Value types. +*/ +type KVPair struct { + Key string + Value interface{} +} + +func (kv KVPair) Hash() []byte { + hasher, n, err := ripemd160.New(), new(int64), new(error) + wire.WriteString(kv.Key, hasher, n, err) + if kvH, ok := kv.Value.(Hashable); ok { + wire.WriteByteSlice(kvH.Hash(), hasher, n, err) + } else { + wire.WriteBinary(kv.Value, hasher, n, err) + } + if *err != nil { + PanicSanity(*err) + } + return hasher.Sum(nil) +} + +type KVPairs []KVPair + +func (kvps KVPairs) Len() int { return len(kvps) } +func (kvps KVPairs) Less(i, j int) bool { return kvps[i].Key < kvps[j].Key } +func (kvps KVPairs) Swap(i, j int) { kvps[i], kvps[j] = kvps[j], kvps[i] } +func (kvps KVPairs) Sort() { sort.Sort(kvps) } + +func MakeSortedKVPairs(m map[string]interface{}) []Hashable { + kvPairs := []KVPair{} + for k, v := range m { + kvPairs = append(kvPairs, KVPair{k, v}) + } + KVPairs(kvPairs).Sort() + kvPairsH := []Hashable{} + for _, kvp := range kvPairs { + kvPairsH = append(kvPairsH, kvp) + } + return kvPairsH +} + //-------------------------------------------------------------------------------- type SimpleProof struct { diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/merkle/simple_tree_test.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/merkle/simple_tree_test.go index 6b47479d5af81797ca35f8bac76d76833be99065..1b673cc8f4cbc00896da3b7703dba36fc6338b27 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/merkle/simple_tree_test.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/merkle/simple_tree_test.go @@ -1,9 +1,12 @@ package merkle import ( + "bytes" + . "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/common" . "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/common/test" + "fmt" "testing" ) @@ -81,3 +84,36 @@ func TestSimpleProof(t *testing.T) { } } } + +func TestKVPairs(t *testing.T) { + // NOTE: in alphabetical order for convenience. + m := map[string]interface{}{} + m["bytez"] = []byte("hizz") // 0 + m["light"] = "shadow" // 1 + m["one"] = 1 // 2 + m["one_u64"] = uint64(1) // 3 + m["struct"] = struct { // 4 + A int + B int + }{0, 1} + + kvPairsH := MakeSortedKVPairs(m) + // rootHash := SimpleHashFromHashables(kvPairsH) + proofs := SimpleProofsFromHashables(kvPairsH) + + // Some manual tests + if !bytes.Equal(proofs[1].LeafHash, KVPair{"light", "shadow"}.Hash()) { + t.Errorf("\"light\": proof failed") + fmt.Printf("%v\n%X", proofs[0], KVPair{"light", "shadow"}.Hash()) + } + if !bytes.Equal(proofs[2].LeafHash, KVPair{"one", 1}.Hash()) { + t.Errorf("\"one\": proof failed") + } + if !bytes.Equal(proofs[4].LeafHash, KVPair{"struct", struct { + A int + B int + }{0, 1}}.Hash()) { + t.Errorf("\"struct\": proof failed") + } + +} diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/node/node.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/node/node.go index 246a214b1e5028628529cea0eddef12886b49c6d..c30a958ce03dbcf8b1912a8c3b17693dd0f64f9e 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/node/node.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/node/node.go @@ -18,9 +18,11 @@ import ( "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/events" mempl "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/mempool" "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/p2p" + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc" "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core" "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/server" sm "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/state" + stypes "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/state/types" "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/types" "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/wire" ) @@ -37,8 +39,8 @@ type Node struct { mempoolReactor *mempl.MempoolReactor consensusState *consensus.ConsensusState consensusReactor *consensus.ConsensusReactor - privValidator *sm.PrivValidator - genDoc *sm.GenesisDoc + privValidator *types.PrivValidator + genDoc *stypes.GenesisDoc privKey acm.PrivKeyEd25519 } @@ -50,39 +52,37 @@ func NewNode() *Node { // Get State stateDB := dbm.GetDB("state") state := sm.LoadState(stateDB) - var genDoc *sm.GenesisDoc + var genDoc *stypes.GenesisDoc if state == nil { genDoc, state = sm.MakeGenesisStateFromFile(stateDB, config.GetString("genesis_file")) state.Save() // write the gendoc to db buf, n, err := new(bytes.Buffer), new(int64), new(error) wire.WriteJSON(genDoc, buf, n, err) - stateDB.Set(sm.GenDocKey, buf.Bytes()) + stateDB.Set(stypes.GenDocKey, buf.Bytes()) if *err != nil { - log.Error("Unable to write gendoc to db", "error", err) - os.Exit(1) + Exit(Fmt("Unable to write gendoc to db: %v", err)) } } else { - genDocBytes := stateDB.Get(sm.GenDocKey) + genDocBytes := stateDB.Get(stypes.GenDocKey) err := new(error) wire.ReadJSONPtr(&genDoc, genDocBytes, err) if *err != nil { - log.Error("Unable to read gendoc from db", "error", err) - os.Exit(1) + Exit(Fmt("Unable to read gendoc from db: %v", err)) } } // add the chainid to the global config config.Set("chain_id", state.ChainID) // Get PrivValidator - var privValidator *sm.PrivValidator + var privValidator *types.PrivValidator privValidatorFile := config.GetString("priv_validator_file") if _, err := os.Stat(privValidatorFile); err == nil { - privValidator = sm.LoadPrivValidator(privValidatorFile) + privValidator = types.LoadPrivValidator(privValidatorFile) log.Notice("Loaded PrivValidator", "file", privValidatorFile, "privValidator", privValidator) } else { - privValidator = sm.GenPrivValidator() + privValidator = types.GenPrivValidator() privValidator.SetFile(privValidatorFile) privValidator.Save() log.Notice("Generated PrivValidator", "file", privValidatorFile) @@ -93,7 +93,10 @@ func NewNode() *Node { // Make event switch eventSwitch := events.NewEventSwitch() - eventSwitch.Start() + _, err := eventSwitch.Start() + if err != nil { + Exit(Fmt("Failed to start switch: %v", err)) + } // Make PEXReactor book := p2p.NewAddrBook(config.GetString("addrbook_file")) @@ -141,11 +144,12 @@ func NewNode() *Node { } // Call Start() after adding the listeners. -func (n *Node) Start() { +func (n *Node) Start() error { n.book.Start() n.sw.SetNodeInfo(makeNodeInfo(n.sw, n.privKey)) n.sw.SetNodePrivKey(n.privKey) - n.sw.Start() + _, err := n.sw.Start() + return err } func (n *Node) Stop() { @@ -243,12 +247,17 @@ func makeNodeInfo(sw *p2p.Switch, privKey acm.PrivKeyEd25519) *types.NodeInfo { PubKey: privKey.PubKey().(acm.PubKeyEd25519), Moniker: config.GetString("moniker"), ChainID: config.GetString("chain_id"), - Version: config.GetString("version"), + Version: types.Versions{ + Tendermint: Version, + P2P: p2p.Version, + RPC: rpc.Version, + Wire: wire.Version, + }, } // include git hash in the nodeInfo if available if rev, err := ReadFile(config.GetString("revisions_file")); err == nil { - nodeInfo.Revision = string(rev) + nodeInfo.Version.Revision = string(rev) } if !sw.IsListening() { @@ -279,9 +288,12 @@ func makeNodeInfo(sw *p2p.Switch, privKey acm.PrivKeyEd25519) *types.NodeInfo { func RunNode() { // Create & start node n := NewNode() - l := p2p.NewDefaultListener("tcp", config.GetString("node_laddr"), false) + l := p2p.NewDefaultListener("tcp", config.GetString("node_laddr")) n.AddListener(l) - n.Start() + err := n.Start() + if err != nil { + Exit(Fmt("Failed to start node: %v", err)) + } log.Notice("Started node", "nodeInfo", n.sw.NodeInfo()) diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/node/node_test.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/node/node_test.go index aa30a96be112e4ab9db5df9ef788bee32efdaf26..01f601cf1a4a29288d1a3ba115acd5ec7340b5b3 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/node/node_test.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/node/node_test.go @@ -11,7 +11,7 @@ import ( func TestNodeStartStop(t *testing.T) { // Create & start node n := NewNode() - l := p2p.NewDefaultListener("tcp", config.GetString("node_laddr"), false) + l := p2p.NewDefaultListener("tcp", config.GetString("node_laddr")) n.AddListener(l) n.Start() log.Notice("Started node", "nodeInfo", n.sw.NodeInfo()) diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/node/version.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/node/version.go new file mode 100644 index 0000000000000000000000000000000000000000..6b981175a23d402253c111c6f7eb09f239eb23a2 --- /dev/null +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/node/version.go @@ -0,0 +1,6 @@ +package node + +// Major: alpha +// Minor: encrypted p2p! +// Patch: New block pool logic +const Version = "0.5.2" diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/p2p/README.md b/Godeps/_workspace/src/github.com/tendermint/tendermint/p2p/README.md index a7324b71405b62c6e2f855dd4334f263019a042f..6149d9c0ffad26c4e2435b0612a36bb6dd777085 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/p2p/README.md +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/p2p/README.md @@ -16,15 +16,15 @@ initialization of the connection. There are two methods for sending messages: ```go -func (m MConnection) Send(chId byte, msg interface{}) bool {} -func (m MConnection) TrySend(chId byte, msg interface{}) bool {} +func (m MConnection) Send(chID byte, msg interface{}) bool {} +func (m MConnection) TrySend(chID byte, msg interface{}) bool {} ``` -`Send(chId, msg)` is a blocking call that waits until `msg` is successfully queued -for the channel with the given id byte `chId`. The message `msg` is serialized +`Send(chID, msg)` is a blocking call that waits until `msg` is successfully queued +for the channel with the given id byte `chID`. The message `msg` is serialized using the `tendermint/wire` submodule's `WriteBinary()` reflection routine. -`TrySend(chId, msg)` is a nonblocking call that returns false if the channel's +`TrySend(chID, msg)` is a nonblocking call that returns false if the channel's queue is full. `Send()` and `TrySend()` are also exposed for each `Peer`. @@ -37,14 +37,14 @@ or more `Channels`. So while sending outgoing messages is typically performed o incoming messages are received on the reactor. ```go -// Declare a MyReactor reactor that handles messages on MyChannelId. +// Declare a MyReactor reactor that handles messages on MyChannelID. type MyReactor struct{} func (reactor MyReactor) GetChannels() []*ChannelDescriptor { - return []*ChannelDescriptor{ChannelDescriptor{Id:MyChannelId, Priority: 1}} + return []*ChannelDescriptor{ChannelDescriptor{ID:MyChannelID, Priority: 1}} } -func (reactor MyReactor) Receive(chId byte, peer *Peer, msgBytes []byte) { +func (reactor MyReactor) Receive(chID byte, peer *Peer, msgBytes []byte) { r, n, err := bytes.NewBuffer(msgBytes), new(int64), new(error) msgString := ReadString(r, n, err) fmt.Println(msgString) @@ -60,7 +60,7 @@ switch := NewSwitch([]Reactor{MyReactor{}}) // Send a random message to all outbound connections for _, peer := range switch.Peers().List() { if peer.IsOutbound() { - peer.Send(MyChannelId, "Here's a random message") + peer.Send(MyChannelID, "Here's a random message") } } ``` diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/p2p/addrbook.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/p2p/addrbook.go index bd6b410d084488a6b0a071b1342a4d134b279662..33ec57fce086ffee562e8bae2ec0e81ce5bdf5da 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/p2p/addrbook.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/p2p/addrbook.go @@ -121,11 +121,12 @@ func (a *AddrBook) init() { } } -func (a *AddrBook) OnStart() { +func (a *AddrBook) OnStart() error { a.QuitService.OnStart() a.loadFromFile(a.filePath) a.wg.Add(1) go a.saveRoutine() + return nil } func (a *AddrBook) OnStop() { diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/p2p/config.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/p2p/config.go new file mode 100644 index 0000000000000000000000000000000000000000..95bf4a7c4a3b4448f0daabc5af843861b260648e --- /dev/null +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/p2p/config.go @@ -0,0 +1,13 @@ +package p2p + +import ( + cfg "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/config" +) + +var config cfg.Config = nil + +func init() { + cfg.OnConfig(func(newConfig cfg.Config) { + config = newConfig + }) +} diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/p2p/connection.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/p2p/connection.go index fdcb092de6313ac35a24a544bc5393b02f1111f7..812196794db5d70ae408aad4230422b641022f77 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/p2p/connection.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/p2p/connection.go @@ -19,18 +19,18 @@ const ( numBatchMsgPackets = 10 minReadBufferSize = 1024 minWriteBufferSize = 1024 - flushThrottleMS = 50 idleTimeoutMinutes = 5 updateStatsSeconds = 2 pingTimeoutSeconds = 40 - defaultSendRate = 51200 // 5Kb/s - defaultRecvRate = 51200 // 5Kb/s + defaultSendRate = 51200 // 50Kb/s + defaultRecvRate = 51200 // 50Kb/s + flushThrottleMS = 100 defaultSendQueueCapacity = 1 defaultRecvBufferCapacity = 4096 defaultSendTimeoutSeconds = 10 ) -type receiveCbFunc func(chId byte, msgBytes []byte) +type receiveCbFunc func(chID byte, msgBytes []byte) type errorCbFunc func(interface{}) /* @@ -45,15 +45,15 @@ The byte id and the relative priorities of each `Channel` are configured upon initialization of the connection. There are two methods for sending messages: - func (m MConnection) Send(chId byte, msg interface{}) bool {} - func (m MConnection) TrySend(chId byte, msg interface{}) bool {} + func (m MConnection) Send(chID byte, msg interface{}) bool {} + func (m MConnection) TrySend(chID byte, msg interface{}) bool {} -`Send(chId, msg)` is a blocking call that waits until `msg` is successfully queued -for the channel with the given id byte `chId`, or until the request times out. +`Send(chID, msg)` is a blocking call that waits until `msg` is successfully queued +for the channel with the given id byte `chID`, or until the request times out. The message `msg` is serialized using the `tendermint/wire` submodule's `WriteBinary()` reflection routine. -`TrySend(chId, msg)` is a nonblocking call that returns false if the channel's +`TrySend(chID, msg)` is a nonblocking call that returns false if the channel's queue is full. Inbound message bytes are handled with an onReceive callback function. @@ -127,7 +127,7 @@ func NewMConnection(conn net.Conn, chDescs []*ChannelDescriptor, onReceive recei return mconn } -func (c *MConnection) OnStart() { +func (c *MConnection) OnStart() error { c.BaseService.OnStart() c.quit = make(chan struct{}) c.flushTimer = NewThrottleTimer("flush", flushThrottleMS*time.Millisecond) @@ -135,6 +135,7 @@ func (c *MConnection) OnStart() { c.chStatsTimer = NewRepeatTimer("chStats", updateStatsSeconds*time.Second) go c.sendRoutine() go c.recvRoutine() + return nil } func (c *MConnection) OnStop() { @@ -184,17 +185,17 @@ func (c *MConnection) stopForError(r interface{}) { } // Queues a message to be sent to channel. -func (c *MConnection) Send(chId byte, msg interface{}) bool { +func (c *MConnection) Send(chID byte, msg interface{}) bool { if !c.IsRunning() { return false } - log.Info("Send", "channel", chId, "conn", c, "msg", msg) //, "bytes", wire.BinaryBytes(msg)) + log.Info("Send", "channel", chID, "conn", c, "msg", msg) //, "bytes", wire.BinaryBytes(msg)) // Send message to channel. - channel, ok := c.channelsIdx[chId] + channel, ok := c.channelsIdx[chID] if !ok { - log.Error(Fmt("Cannot send bytes, unknown channel %X", chId)) + log.Error(Fmt("Cannot send bytes, unknown channel %X", chID)) return false } @@ -206,24 +207,24 @@ func (c *MConnection) Send(chId byte, msg interface{}) bool { default: } } else { - log.Warn("Send failed", "channel", chId, "conn", c, "msg", msg) + log.Warn("Send failed", "channel", chID, "conn", c, "msg", msg) } return success } // Queues a message to be sent to channel. // Nonblocking, returns true if successful. -func (c *MConnection) TrySend(chId byte, msg interface{}) bool { +func (c *MConnection) TrySend(chID byte, msg interface{}) bool { if !c.IsRunning() { return false } - log.Info("TrySend", "channel", chId, "conn", c, "msg", msg) + log.Info("TrySend", "channel", chID, "conn", c, "msg", msg) // Send message to channel. - channel, ok := c.channelsIdx[chId] + channel, ok := c.channelsIdx[chID] if !ok { - log.Error(Fmt("Cannot send bytes, unknown channel %X", chId)) + log.Error(Fmt("Cannot send bytes, unknown channel %X", chID)) return false } @@ -239,14 +240,14 @@ func (c *MConnection) TrySend(chId byte, msg interface{}) bool { return ok } -func (c *MConnection) CanSend(chId byte) bool { +func (c *MConnection) CanSend(chID byte) bool { if !c.IsRunning() { return false } - channel, ok := c.channelsIdx[chId] + channel, ok := c.channelsIdx[chID] if !ok { - log.Error(Fmt("Unknown channel %X", chId)) + log.Error(Fmt("Unknown channel %X", chID)) return false } return channel.canSend() @@ -420,9 +421,9 @@ FOR_LOOP: } break FOR_LOOP } - channel, ok := c.channelsIdx[pkt.ChannelId] + channel, ok := c.channelsIdx[pkt.ChannelID] if !ok || channel == nil { - PanicQ(Fmt("Unknown channel %X", pkt.ChannelId)) + PanicQ(Fmt("Unknown channel %X", pkt.ChannelID)) } msgBytes, err := channel.recvMsgPacket(pkt) if err != nil { @@ -433,8 +434,8 @@ FOR_LOOP: break FOR_LOOP } if msgBytes != nil { - log.Debug("Received bytes", "chId", pkt.ChannelId, "msgBytes", msgBytes) - c.onReceive(pkt.ChannelId, msgBytes) + log.Debug("Received bytes", "chID", pkt.ChannelID, "msgBytes", msgBytes) + c.onReceive(pkt.ChannelID, msgBytes) } default: PanicSanity(Fmt("Unknown message type %X", pktType)) @@ -455,7 +456,7 @@ FOR_LOOP: //----------------------------------------------------------------------------- type ChannelDescriptor struct { - Id byte + ID byte Priority int SendQueueCapacity int RecvBufferCapacity int @@ -492,7 +493,7 @@ func newChannel(conn *MConnection, desc *ChannelDescriptor) *Channel { return &Channel{ conn: conn, desc: desc, - id: desc.Id, + id: desc.ID, sendQueue: make(chan []byte, desc.SendQueueCapacity), recving: make([]byte, 0, desc.RecvBufferCapacity), priority: desc.Priority, @@ -555,7 +556,7 @@ func (ch *Channel) isSendPending() bool { // Not goroutine-safe func (ch *Channel) nextMsgPacket() msgPacket { packet := msgPacket{} - packet.ChannelId = byte(ch.id) + packet.ChannelID = byte(ch.id) packet.Bytes = ch.sending[:MinInt(maxMsgPacketSize, len(ch.sending))] if len(ch.sending) <= maxMsgPacketSize { packet.EOF = byte(0x01) @@ -584,7 +585,7 @@ func (ch *Channel) writeMsgPacketTo(w io.Writer) (n int64, err error) { // Handles incoming msgPackets. Returns a msg bytes if msg is complete. // Not goroutine-safe func (ch *Channel) recvMsgPacket(packet msgPacket) ([]byte, error) { - log.Debug("Read Msg Packet", "conn", ch.conn, "packet", packet) + // log.Debug("Read Msg Packet", "conn", ch.conn, "packet", packet) if wire.MaxBinaryReadSize < len(ch.recving)+len(packet.Bytes) { return nil, wire.ErrBinaryReadSizeOverflow } @@ -616,13 +617,13 @@ const ( // Messages in channels are chopped into smaller msgPackets for multiplexing. type msgPacket struct { - ChannelId byte + ChannelID byte EOF byte // 1 means message ends here. Bytes []byte } func (p msgPacket) String() string { - return fmt.Sprintf("MsgPacket{%X:%X T:%X}", p.ChannelId, p.Bytes, p.EOF) + return fmt.Sprintf("MsgPacket{%X:%X T:%X}", p.ChannelID, p.Bytes, p.EOF) } //----------------------------------------------------------------------------- diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/p2p/listener.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/p2p/listener.go index 26ecf24aa9c6895786bcdf09cc523c08235f007d..a3ab5513865306978ae9fbd3a3d159c0c76a6bf8 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/p2p/listener.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/p2p/listener.go @@ -46,7 +46,7 @@ func splitHostPort(addr string) (host string, port int) { return host, port } -func NewDefaultListener(protocol string, lAddr string, requireUPNPHairpin bool) Listener { +func NewDefaultListener(protocol string, lAddr string) Listener { // Local listen IP & port lAddrIP, lAddrPort := splitHostPort(lAddr) @@ -73,22 +73,12 @@ func NewDefaultListener(protocol string, lAddr string, requireUPNPHairpin bool) // Determine external address... var extAddr *NetAddress - // If the lAddrIP is INADDR_ANY, try UPnP - if lAddrIP == "" || lAddrIP == "0.0.0.0" { - if requireUPNPHairpin { - upnpCapabilities, err := upnp.Probe() - if err != nil { - log.Warn("Failed to probe UPNP", "error", err) - goto SKIP_UPNP - } - if !upnpCapabilities.Hairpin { - goto SKIP_UPNP - } + if !config.GetBool("skip_upnp") { + // If the lAddrIP is INADDR_ANY, try UPnP + if lAddrIP == "" || lAddrIP == "0.0.0.0" { + extAddr = getUPNPExternalAddress(lAddrPort, listenerPort) } - extAddr = getUPNPExternalAddress(lAddrPort, listenerPort) } -SKIP_UPNP: - // Otherwise just use the local address... if extAddr == nil { extAddr = getNaiveExternalAddress(listenerPort) @@ -108,9 +98,10 @@ SKIP_UPNP: return dl } -func (l *DefaultListener) OnStart() { +func (l *DefaultListener) OnStart() error { l.BaseService.OnStart() go l.listenRoutine() + return nil } func (l *DefaultListener) OnStop() { diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/p2p/peer.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/p2p/peer.go index 8b0819e5eb7a51dc9136352d6f7a92657a7d1093..82ff986b917618ac1f9b5c5e74a27e522d3e2570 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/p2p/peer.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/p2p/peer.go @@ -49,12 +49,12 @@ func peerHandshake(conn net.Conn, ourNodeInfo *types.NodeInfo) (*types.NodeInfo, // NOTE: call peerHandshake on conn before calling newPeer(). func newPeer(conn net.Conn, peerNodeInfo *types.NodeInfo, outbound bool, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor, onPeerError func(*Peer, interface{})) *Peer { var p *Peer - onReceive := func(chId byte, msgBytes []byte) { - reactor := reactorsByCh[chId] + onReceive := func(chID byte, msgBytes []byte) { + reactor := reactorsByCh[chID] if reactor == nil { - PanicSanity(Fmt("Unknown channel %X", chId)) + PanicSanity(Fmt("Unknown channel %X", chID)) } - reactor.Receive(chId, p, msgBytes) + reactor.Receive(chID, p, msgBytes) } onError := func(r interface{}) { p.Stop() @@ -72,9 +72,10 @@ func newPeer(conn net.Conn, peerNodeInfo *types.NodeInfo, outbound bool, reactor return p } -func (p *Peer) OnStart() { +func (p *Peer) OnStart() error { p.BaseService.OnStart() - p.mconn.Start() + _, err := p.mconn.Start() + return err } func (p *Peer) OnStop() { @@ -90,25 +91,25 @@ func (p *Peer) IsOutbound() bool { return p.outbound } -func (p *Peer) Send(chId byte, msg interface{}) bool { +func (p *Peer) Send(chID byte, msg interface{}) bool { if !p.IsRunning() { return false } - return p.mconn.Send(chId, msg) + return p.mconn.Send(chID, msg) } -func (p *Peer) TrySend(chId byte, msg interface{}) bool { +func (p *Peer) TrySend(chID byte, msg interface{}) bool { if !p.IsRunning() { return false } - return p.mconn.TrySend(chId, msg) + return p.mconn.TrySend(chID, msg) } -func (p *Peer) CanSend(chId byte) bool { +func (p *Peer) CanSend(chID byte) bool { if !p.IsRunning() { return false } - return p.mconn.CanSend(chId) + return p.mconn.CanSend(chID) } func (p *Peer) WriteTo(w io.Writer) (n int64, err error) { @@ -118,9 +119,9 @@ func (p *Peer) WriteTo(w io.Writer) (n int64, err error) { func (p *Peer) String() string { if p.outbound { - return fmt.Sprintf("Peer{->%v}", p.mconn) + return fmt.Sprintf("Peer{%v %v out}", p.mconn, p.Key[:12]) } else { - return fmt.Sprintf("Peer{%v->}", p.mconn) + return fmt.Sprintf("Peer{%v %v in}", p.mconn, p.Key[:12]) } } diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/p2p/peer_set_test.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/p2p/peer_set_test.go index cad66b35308dc18792cd97cf46210dad491e947d..75301e043a81c01aa35cd88287d13495c6a36af8 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/p2p/peer_set_test.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/p2p/peer_set_test.go @@ -73,11 +73,9 @@ func newPeerInIPRange(ipBytes ...string) *Peer { for i, ipByte := range ipBytes { ips[i] = ipByte } - for i := len(ipBytes); i < 4; i++ { ips[i] = Fmt("%v", rand.Int()%256) } - ipS := strings.Join(ips, ".") return &Peer{ Key: RandStr(12), @@ -92,19 +90,19 @@ func TestIPRanges(t *testing.T) { // test /8 maxPeersPerIPRange = [4]int{2, 2, 2, 2} - peer := newPeerInIPRange("54") + peer := newPeerInIPRange("54", "1") if err := peerSet.Add(peer); err != nil { t.Errorf("Failed to add new peer") } - peer = newPeerInIPRange("54") + peer = newPeerInIPRange("54", "2") if err := peerSet.Add(peer); err != nil { t.Errorf("Failed to add new peer") } - peer = newPeerInIPRange("54") + peer = newPeerInIPRange("54", "3") if err := peerSet.Add(peer); err == nil { t.Errorf("Added peer when we shouldn't have") } - peer = newPeerInIPRange("55") + peer = newPeerInIPRange("55", "1") if err := peerSet.Add(peer); err != nil { t.Errorf("Failed to add new peer") } @@ -112,19 +110,19 @@ func TestIPRanges(t *testing.T) { // test /16 peerSet = NewPeerSet() maxPeersPerIPRange = [4]int{3, 2, 1, 1} - peer = newPeerInIPRange("54", "112") + peer = newPeerInIPRange("54", "112", "1") if err := peerSet.Add(peer); err != nil { t.Errorf("Failed to add new peer") } - peer = newPeerInIPRange("54", "112") + peer = newPeerInIPRange("54", "112", "2") if err := peerSet.Add(peer); err != nil { t.Errorf("Failed to add new peer") } - peer = newPeerInIPRange("54", "112") + peer = newPeerInIPRange("54", "112", "3") if err := peerSet.Add(peer); err == nil { t.Errorf("Added peer when we shouldn't have") } - peer = newPeerInIPRange("54", "113") + peer = newPeerInIPRange("54", "113", "1") if err := peerSet.Add(peer); err != nil { t.Errorf("Failed to add new peer") } @@ -132,19 +130,19 @@ func TestIPRanges(t *testing.T) { // test /24 peerSet = NewPeerSet() maxPeersPerIPRange = [4]int{5, 3, 2, 1} - peer = newPeerInIPRange("54", "112", "11") + peer = newPeerInIPRange("54", "112", "11", "1") if err := peerSet.Add(peer); err != nil { t.Errorf("Failed to add new peer") } - peer = newPeerInIPRange("54", "112", "11") + peer = newPeerInIPRange("54", "112", "11", "2") if err := peerSet.Add(peer); err != nil { t.Errorf("Failed to add new peer") } - peer = newPeerInIPRange("54", "112", "11") + peer = newPeerInIPRange("54", "112", "11", "3") if err := peerSet.Add(peer); err == nil { t.Errorf("Added peer when we shouldn't have") } - peer = newPeerInIPRange("54", "112", "12") + peer = newPeerInIPRange("54", "112", "12", "1") if err := peerSet.Add(peer); err != nil { t.Errorf("Failed to add new peer") } diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/p2p/pex_reactor.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/p2p/pex_reactor.go index f678a662b4748dd508f63a8396859fc84f2d66aa..2c77db13f037c052ed64398155374861ff50f30c 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/p2p/pex_reactor.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/p2p/pex_reactor.go @@ -41,9 +41,10 @@ func NewPEXReactor(book *AddrBook) *PEXReactor { return pexR } -func (pexR *PEXReactor) OnStart() { +func (pexR *PEXReactor) OnStart() error { pexR.BaseReactor.OnStart() go pexR.ensurePeersRoutine() + return nil } func (pexR *PEXReactor) OnStop() { @@ -54,7 +55,7 @@ func (pexR *PEXReactor) OnStop() { func (pexR *PEXReactor) GetChannels() []*ChannelDescriptor { return []*ChannelDescriptor{ &ChannelDescriptor{ - Id: PexChannel, + ID: PexChannel, Priority: 1, SendQueueCapacity: 10, }, @@ -83,7 +84,7 @@ func (pexR *PEXReactor) RemovePeer(peer *Peer, reason interface{}) { // Implements Reactor // Handles incoming PEX messages. -func (pexR *PEXReactor) Receive(chId byte, src *Peer, msgBytes []byte) { +func (pexR *PEXReactor) Receive(chID byte, src *Peer, msgBytes []byte) { // decode message _, msg, err := DecodeMessage(msgBytes) diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/p2p/switch.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/p2p/switch.go index 3491319a8275dcbb46c0f051ea9e047eb0f0166a..661aee12ea3210aceda64f9a190cf2a2ad8331cd 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/p2p/switch.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/p2p/switch.go @@ -20,7 +20,7 @@ type Reactor interface { GetChannels() []*ChannelDescriptor AddPeer(peer *Peer) RemovePeer(peer *Peer, reason interface{}) - Receive(chId byte, peer *Peer, msgBytes []byte) + Receive(chID byte, peer *Peer, msgBytes []byte) } //-------------------------------------- @@ -43,7 +43,7 @@ func (br *BaseReactor) SetSwitch(sw *Switch) { func (_ *BaseReactor) GetChannels() []*ChannelDescriptor { return nil } func (_ *BaseReactor) AddPeer(peer *Peer) {} func (_ *BaseReactor) RemovePeer(peer *Peer, reason interface{}) {} -func (_ *BaseReactor) Receive(chId byte, peer *Peer, msgBytes []byte) {} +func (_ *BaseReactor) Receive(chID byte, peer *Peer, msgBytes []byte) {} //----------------------------------------------------------------------------- @@ -96,12 +96,12 @@ func (sw *Switch) AddReactor(name string, reactor Reactor) Reactor { // No two reactors can share the same channel. reactorChannels := reactor.GetChannels() for _, chDesc := range reactorChannels { - chId := chDesc.Id - if sw.reactorsByCh[chId] != nil { - PanicSanity(fmt.Sprintf("Channel %X has multiple reactors %v & %v", chId, sw.reactorsByCh[chId], reactor)) + chID := chDesc.ID + if sw.reactorsByCh[chID] != nil { + PanicSanity(fmt.Sprintf("Channel %X has multiple reactors %v & %v", chID, sw.reactorsByCh[chID], reactor)) } sw.chDescs = append(sw.chDescs, chDesc) - sw.reactorsByCh[chId] = reactor + sw.reactorsByCh[chID] = reactor } sw.reactors[name] = reactor reactor.SetSwitch(sw) @@ -153,11 +153,14 @@ func (sw *Switch) SetNodePrivKey(nodePrivKey acm.PrivKeyEd25519) { } // Switch.Start() starts all the reactors, peers, and listeners. -func (sw *Switch) OnStart() { +func (sw *Switch) OnStart() error { sw.BaseService.OnStart() // Start reactors for _, reactor := range sw.reactors { - reactor.Start() + _, err := reactor.Start() + if err != nil { + return err + } } // Start peers for _, peer := range sw.peers.List() { @@ -167,6 +170,7 @@ func (sw *Switch) OnStart() { for _, listener := range sw.listeners { go sw.listenerRoutine(listener) } + return nil } func (sw *Switch) OnStop() { @@ -281,17 +285,16 @@ func (sw *Switch) IsDialing(addr *NetAddress) bool { // Broadcast runs a go routine for each attempted send, which will block // trying to send for defaultSendTimeoutSeconds. Returns a channel // which receives success values for each attempted send (false if times out) -func (sw *Switch) Broadcast(chId byte, msg interface{}) chan bool { +func (sw *Switch) Broadcast(chID byte, msg interface{}) chan bool { successChan := make(chan bool, len(sw.peers.List())) - log.Debug("Broadcast", "channel", chId, "msg", msg) + log.Info("Broadcast", "channel", chID, "msg", msg) for _, peer := range sw.peers.List() { go func(peer *Peer) { - success := peer.Send(chId, msg) + success := peer.Send(chID, msg) successChan <- success }(peer) } return successChan - } // Returns the count of outbound/inbound and outbound-dialing peers. diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/p2p/switch_test.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/p2p/switch_test.go index d770a778facc639f70e926ce52067c306c4f4ef5..3be0386d0cf8628b67f392e318f801fd2180ead7 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/p2p/switch_test.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/p2p/switch_test.go @@ -8,6 +8,7 @@ import ( acm "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/account" . "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/common" + _ "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/config/tendermint_test" "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/types" "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/wire" ) @@ -56,12 +57,12 @@ func (tr *TestReactor) RemovePeer(peer *Peer, reason interface{}) { tr.peersRemoved = append(tr.peersRemoved, peer) } -func (tr *TestReactor) Receive(chId byte, peer *Peer, msgBytes []byte) { +func (tr *TestReactor) Receive(chID byte, peer *Peer, msgBytes []byte) { if tr.logMessages { tr.mtx.Lock() defer tr.mtx.Unlock() - //fmt.Printf("Received: %X, %X\n", chId, msgBytes) - tr.msgsReceived[chId] = append(tr.msgsReceived[chId], PeerMessage{peer.Key, msgBytes, tr.msgsCounter}) + //fmt.Printf("Received: %X, %X\n", chID, msgBytes) + tr.msgsReceived[chID] = append(tr.msgsReceived[chID], PeerMessage{peer.Key, msgBytes, tr.msgsCounter}) tr.msgsCounter++ } } @@ -80,7 +81,7 @@ func makeSwitchPair(t testing.TB, initSwitch func(*Switch) *Switch) (*Switch, *S PubKey: s1PrivKey.PubKey().(acm.PubKeyEd25519), Moniker: "switch1", ChainID: "testing", - Version: "123.123.123", + Version: types.Versions{Tendermint: "123.123.123"}, }) s1.SetNodePrivKey(s1PrivKey) s2 := initSwitch(NewSwitch()) @@ -88,7 +89,7 @@ func makeSwitchPair(t testing.TB, initSwitch func(*Switch) *Switch) (*Switch, *S PubKey: s2PrivKey.PubKey().(acm.PubKeyEd25519), Moniker: "switch2", ChainID: "testing", - Version: "123.123.123", + Version: types.Versions{Tendermint: "123.123.123"}, }) s2.SetNodePrivKey(s2PrivKey) @@ -97,7 +98,7 @@ func makeSwitchPair(t testing.TB, initSwitch func(*Switch) *Switch) (*Switch, *S s2.Start() // Create a listener for s1 - l := NewDefaultListener("tcp", ":8001", true) + l := NewDefaultListener("tcp", ":8001") // Dial the listener & add the connection to s2. lAddr := l.ExternalAddress() @@ -128,12 +129,12 @@ func TestSwitches(t *testing.T) { s1, s2 := makeSwitchPair(t, func(sw *Switch) *Switch { // Make two reactors of two channels each sw.AddReactor("foo", NewTestReactor([]*ChannelDescriptor{ - &ChannelDescriptor{Id: byte(0x00), Priority: 10}, - &ChannelDescriptor{Id: byte(0x01), Priority: 10}, + &ChannelDescriptor{ID: byte(0x00), Priority: 10}, + &ChannelDescriptor{ID: byte(0x01), Priority: 10}, }, true)) sw.AddReactor("bar", NewTestReactor([]*ChannelDescriptor{ - &ChannelDescriptor{Id: byte(0x02), Priority: 10}, - &ChannelDescriptor{Id: byte(0x03), Priority: 10}, + &ChannelDescriptor{ID: byte(0x02), Priority: 10}, + &ChannelDescriptor{ID: byte(0x03), Priority: 10}, }, true)) return sw }) @@ -195,12 +196,12 @@ func BenchmarkSwitches(b *testing.B) { s1, s2 := makeSwitchPair(b, func(sw *Switch) *Switch { // Make bar reactors of bar channels each sw.AddReactor("foo", NewTestReactor([]*ChannelDescriptor{ - &ChannelDescriptor{Id: byte(0x00), Priority: 10}, - &ChannelDescriptor{Id: byte(0x01), Priority: 10}, + &ChannelDescriptor{ID: byte(0x00), Priority: 10}, + &ChannelDescriptor{ID: byte(0x01), Priority: 10}, }, false)) sw.AddReactor("bar", NewTestReactor([]*ChannelDescriptor{ - &ChannelDescriptor{Id: byte(0x02), Priority: 10}, - &ChannelDescriptor{Id: byte(0x03), Priority: 10}, + &ChannelDescriptor{ID: byte(0x02), Priority: 10}, + &ChannelDescriptor{ID: byte(0x03), Priority: 10}, }, false)) return sw }) @@ -215,8 +216,8 @@ func BenchmarkSwitches(b *testing.B) { // Send random message from foo channel to another for i := 0; i < b.N; i++ { - chId := byte(i % 4) - successChan := s1.Broadcast(chId, "test data") + chID := byte(i % 4) + successChan := s1.Broadcast(chID, "test data") for s := range successChan { if s { numSuccess += 1 diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/p2p/version.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/p2p/version.go new file mode 100644 index 0000000000000000000000000000000000000000..7e51463dccb48cc8d22770ce41e9bbe1410a1b82 --- /dev/null +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/p2p/version.go @@ -0,0 +1,3 @@ +package p2p + +const Version = "0.3.0" diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/client/client.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/client/client.go new file mode 100644 index 0000000000000000000000000000000000000000..a6b41cfae45636382b8f53f16c76d58d88ec9fb5 --- /dev/null +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/client/client.go @@ -0,0 +1,51 @@ +package rpcclient + +import ( + "bytes" + "encoding/json" + "errors" + "io/ioutil" + "net/http" + + . "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/common" + . "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/types" + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/wire" +) + +func Call(remote string, method string, params []interface{}, dest interface{}) (interface{}, error) { + // Make request and get responseBytes + request := RPCRequest{ + JSONRPC: "2.0", + Method: method, + Params: params, + ID: "", + } + requestBytes := wire.JSONBytes(request) + requestBuf := bytes.NewBuffer(requestBytes) + log.Info(Fmt("RPC request to %v: %v", remote, string(requestBytes))) + httpResponse, err := http.Post(remote, "text/json", requestBuf) + if err != nil { + return dest, err + } + defer httpResponse.Body.Close() + responseBytes, err := ioutil.ReadAll(httpResponse.Body) + if err != nil { + return dest, err + } + log.Info(Fmt("RPC response: %v", string(responseBytes))) + + // Parse response into JSONResponse + response := RPCResponse{} + err = json.Unmarshal(responseBytes, &response) + if err != nil { + return dest, err + } + // Parse response into dest + resultJSONObject := response.Result + errorStr := response.Error + if errorStr != "" { + return dest, errors.New(errorStr) + } + dest = wire.ReadJSONObject(dest, resultJSONObject, &err) + return dest, err +} diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/client/log.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/client/log.go new file mode 100644 index 0000000000000000000000000000000000000000..bfebc78dba1d3338bcb1ab663561822184cbd0ed --- /dev/null +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/client/log.go @@ -0,0 +1,7 @@ +package rpcclient + +import ( + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/log15" +) + +var log = log15.New("module", "rpcclient") diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core/accounts.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core/accounts.go index 5ebb4d65b6a2366fcf822ebfa1ed5bd853a40feb..6918d8325a978ff699e9ddc75e6d83f9f80edbb9 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core/accounts.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core/accounts.go @@ -7,21 +7,21 @@ import ( ctypes "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core/types" ) -func GenPrivAccount() (*acm.PrivAccount, error) { - return acm.GenPrivAccount(), nil +func GenPrivAccount() (*ctypes.ResultGenPrivAccount, error) { + return &ctypes.ResultGenPrivAccount{acm.GenPrivAccount()}, nil } // If the account is not known, returns nil, nil. -func GetAccount(address []byte) (*acm.Account, error) { +func GetAccount(address []byte) (*ctypes.ResultGetAccount, error) { cache := mempoolReactor.Mempool.GetCache() account := cache.GetAccount(address) if account == nil { return nil, nil } - return account, nil + return &ctypes.ResultGetAccount{account}, nil } -func GetStorage(address, key []byte) (*ctypes.ResponseGetStorage, error) { +func GetStorage(address, key []byte) (*ctypes.ResultGetStorage, error) { state := consensusState.GetState() account := state.GetAccount(address) if account == nil { @@ -32,12 +32,12 @@ func GetStorage(address, key []byte) (*ctypes.ResponseGetStorage, error) { _, value := storageTree.Get(LeftPadWord256(key).Bytes()) if value == nil { - return &ctypes.ResponseGetStorage{key, nil}, nil + return &ctypes.ResultGetStorage{key, nil}, nil } - return &ctypes.ResponseGetStorage{key, value.([]byte)}, nil + return &ctypes.ResultGetStorage{key, value.([]byte)}, nil } -func ListAccounts() (*ctypes.ResponseListAccounts, error) { +func ListAccounts() (*ctypes.ResultListAccounts, error) { var blockHeight int var accounts []*acm.Account state := consensusState.GetState() @@ -46,10 +46,10 @@ func ListAccounts() (*ctypes.ResponseListAccounts, error) { accounts = append(accounts, value.(*acm.Account)) return false }) - return &ctypes.ResponseListAccounts{blockHeight, accounts}, nil + return &ctypes.ResultListAccounts{blockHeight, accounts}, nil } -func DumpStorage(address []byte) (*ctypes.ResponseDumpStorage, error) { +func DumpStorage(address []byte) (*ctypes.ResultDumpStorage, error) { state := consensusState.GetState() account := state.GetAccount(address) if account == nil { @@ -63,5 +63,5 @@ func DumpStorage(address []byte) (*ctypes.ResponseDumpStorage, error) { key.([]byte), value.([]byte)}) return false }) - return &ctypes.ResponseDumpStorage{storageRoot, storageItems}, nil + return &ctypes.ResultDumpStorage{storageRoot, storageItems}, nil } diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core/blocks.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core/blocks.go index 0e109e6cd8e7b324a948c264436622a8c3172b28..fffe358d594be4ccfe6a7383fe520b4649182241 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core/blocks.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core/blocks.go @@ -9,7 +9,7 @@ import ( //----------------------------------------------------------------------------- -func BlockchainInfo(minHeight, maxHeight int) (*ctypes.ResponseBlockchainInfo, error) { +func BlockchainInfo(minHeight, maxHeight int) (*ctypes.ResultBlockchainInfo, error) { if maxHeight == 0 { maxHeight = blockStore.Height() } else { @@ -26,12 +26,12 @@ func BlockchainInfo(minHeight, maxHeight int) (*ctypes.ResponseBlockchainInfo, e blockMetas = append(blockMetas, blockMeta) } - return &ctypes.ResponseBlockchainInfo{blockStore.Height(), blockMetas}, nil + return &ctypes.ResultBlockchainInfo{blockStore.Height(), blockMetas}, nil } //----------------------------------------------------------------------------- -func GetBlock(height int) (*ctypes.ResponseGetBlock, error) { +func GetBlock(height int) (*ctypes.ResultGetBlock, error) { if height == 0 { return nil, fmt.Errorf("Height must be greater than 0") } @@ -41,5 +41,5 @@ func GetBlock(height int) (*ctypes.ResponseGetBlock, error) { blockMeta := blockStore.LoadBlockMeta(height) block := blockStore.LoadBlock(height) - return &ctypes.ResponseGetBlock{blockMeta, block}, nil + return &ctypes.ResultGetBlock{blockMeta, block}, nil } diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core/consensus.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core/consensus.go index 4840dbca080f25d035d71b287d5e90dbcc344ea1..d0f3a71e52bd4e7d1aac6f6a68769331137014c4 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core/consensus.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core/consensus.go @@ -3,30 +3,30 @@ package core import ( cm "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/consensus" ctypes "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core/types" - sm "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/state" + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/types" "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/wire" ) -func ListValidators() (*ctypes.ResponseListValidators, error) { +func ListValidators() (*ctypes.ResultListValidators, error) { var blockHeight int - var bondedValidators []*sm.Validator - var unbondingValidators []*sm.Validator + var bondedValidators []*types.Validator + var unbondingValidators []*types.Validator state := consensusState.GetState() blockHeight = state.LastBlockHeight - state.BondedValidators.Iterate(func(index int, val *sm.Validator) bool { + state.BondedValidators.Iterate(func(index int, val *types.Validator) bool { bondedValidators = append(bondedValidators, val) return false }) - state.UnbondingValidators.Iterate(func(index int, val *sm.Validator) bool { + state.UnbondingValidators.Iterate(func(index int, val *types.Validator) bool { unbondingValidators = append(unbondingValidators, val) return false }) - return &ctypes.ResponseListValidators{blockHeight, bondedValidators, unbondingValidators}, nil + return &ctypes.ResultListValidators{blockHeight, bondedValidators, unbondingValidators}, nil } -func DumpConsensusState() (*ctypes.ResponseDumpConsensusState, error) { +func DumpConsensusState() (*ctypes.ResultDumpConsensusState, error) { roundState := consensusState.GetRoundState() peerRoundStates := []string{} for _, peer := range p2pSwitch.Peers().List() { @@ -36,5 +36,5 @@ func DumpConsensusState() (*ctypes.ResponseDumpConsensusState, error) { peerRoundStateStr := peer.Key + ":" + string(wire.JSONBytes(peerRoundState)) peerRoundStates = append(peerRoundStates, peerRoundStateStr) } - return &ctypes.ResponseDumpConsensusState{roundState.String(), peerRoundStates}, nil + return &ctypes.ResultDumpConsensusState{roundState.String(), peerRoundStates}, nil } diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core/mempool.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core/mempool.go index 47f2f543ac874349ac01fdfa86cad2c3f3039578..61cd4b95ed0e592c09531515e7370db77e9c0039 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core/mempool.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core/mempool.go @@ -10,7 +10,7 @@ import ( //----------------------------------------------------------------------------- // Note: tx must be signed -func BroadcastTx(tx types.Tx) (*ctypes.Receipt, error) { +func BroadcastTx(tx types.Tx) (*ctypes.ResultBroadcastTx, error) { err := mempoolReactor.BroadcastTx(tx) if err != nil { return nil, fmt.Errorf("Error broadcasting transaction: %v", err) @@ -26,9 +26,9 @@ func BroadcastTx(tx types.Tx) (*ctypes.Receipt, error) { contractAddr = state.NewContractAddress(callTx.Input.Address, callTx.Input.Sequence) } } - return &ctypes.Receipt{txHash, createsContract, contractAddr}, nil + return &ctypes.ResultBroadcastTx{ctypes.Receipt{txHash, createsContract, contractAddr}}, nil } -func ListUnconfirmedTxs() ([]types.Tx, error) { - return mempoolReactor.Mempool.GetProposalTxs(), nil +func ListUnconfirmedTxs() (*ctypes.ResultListUnconfirmedTxs, error) { + return &ctypes.ResultListUnconfirmedTxs{mempoolReactor.Mempool.GetProposalTxs()}, nil } diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core/names.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core/names.go index 9dabe36933100aff59231e8de486cc774e8411b5..b7a3dc6a619572d7bd30789073751e9348f981f7 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core/names.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core/names.go @@ -7,16 +7,16 @@ import ( "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/types" ) -func GetName(name string) (*types.NameRegEntry, error) { +func GetName(name string) (*ctypes.ResultGetName, error) { st := consensusState.GetState() // performs a copy entry := st.GetNameRegEntry(name) if entry == nil { return nil, fmt.Errorf("Name %s not found", name) } - return entry, nil + return &ctypes.ResultGetName{entry}, nil } -func ListNames() (*ctypes.ResponseListNames, error) { +func ListNames() (*ctypes.ResultListNames, error) { var blockHeight int var names []*types.NameRegEntry state := consensusState.GetState() @@ -25,5 +25,5 @@ func ListNames() (*ctypes.ResponseListNames, error) { names = append(names, value.(*types.NameRegEntry)) return false }) - return &ctypes.ResponseListNames{blockHeight, names}, nil + return &ctypes.ResultListNames{blockHeight, names}, nil } diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core/net.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core/net.go index 6de69f39f6d13422cab18e2d1cdc6fdb07b8b429..248600b059e5728cbab758059f7ddb47f31a4b35 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core/net.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core/net.go @@ -12,7 +12,7 @@ import ( // cache the genesis state var genesisState *sm.State -func Status() (*ctypes.ResponseStatus, error) { +func Status() (*ctypes.ResultStatus, error) { db := dbm.NewMemDB() if genesisState == nil { genesisState = sm.MakeGenesisState(db, genDoc) @@ -30,7 +30,7 @@ func Status() (*ctypes.ResponseStatus, error) { latestBlockTime = latestBlockMeta.Header.Time.UnixNano() } - return &ctypes.ResponseStatus{ + return &ctypes.ResultStatus{ NodeInfo: p2pSwitch.NodeInfo(), GenesisHash: genesisHash, PubKey: privValidator.PubKey, @@ -41,7 +41,7 @@ func Status() (*ctypes.ResponseStatus, error) { //----------------------------------------------------------------------------- -func NetInfo() (*ctypes.ResponseNetInfo, error) { +func NetInfo() (*ctypes.ResultNetInfo, error) { listening := p2pSwitch.IsListening() listeners := []string{} for _, listener := range p2pSwitch.Listeners() { @@ -54,7 +54,7 @@ func NetInfo() (*ctypes.ResponseNetInfo, error) { IsOutbound: peer.IsOutbound(), }) } - return &ctypes.ResponseNetInfo{ + return &ctypes.ResultNetInfo{ Listening: listening, Listeners: listeners, Peers: peers, @@ -63,6 +63,6 @@ func NetInfo() (*ctypes.ResponseNetInfo, error) { //----------------------------------------------------------------------------- -func Genesis() (*sm.GenesisDoc, error) { - return genDoc, nil +func Genesis() (*ctypes.ResultGenesis, error) { + return &ctypes.ResultGenesis{genDoc}, nil } diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core/pipe.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core/pipe.go index 92a50dc10a6add3620493c8a69231ce8580c79cb..c2250cf1d614e6f020dbd2b216e16f7eaea85d63 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core/pipe.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core/pipe.go @@ -5,7 +5,8 @@ import ( "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/consensus" mempl "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/mempool" "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/p2p" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/state" + stypes "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/state/types" + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/types" ) var blockStore *bc.BlockStore @@ -13,8 +14,8 @@ var consensusState *consensus.ConsensusState var consensusReactor *consensus.ConsensusReactor var mempoolReactor *mempl.MempoolReactor var p2pSwitch *p2p.Switch -var privValidator *state.PrivValidator -var genDoc *state.GenesisDoc // cache the genesis structure +var privValidator *types.PrivValidator +var genDoc *stypes.GenesisDoc // cache the genesis structure func SetBlockStore(bs *bc.BlockStore) { blockStore = bs @@ -36,10 +37,10 @@ func SetSwitch(sw *p2p.Switch) { p2pSwitch = sw } -func SetPrivValidator(pv *state.PrivValidator) { +func SetPrivValidator(pv *types.PrivValidator) { privValidator = pv } -func SetGenDoc(doc *state.GenesisDoc) { +func SetGenDoc(doc *stypes.GenesisDoc) { genDoc = doc } diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core/txs.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core/txs.go index 266bc6d11296e49737f23efe2b194c91425a1163..9e775e0adbba95b5b181847a143b7b8b4283d4b8 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core/txs.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core/txs.go @@ -24,7 +24,7 @@ func toVMAccount(acc *acm.Account) *vm.Account { // Run a contract's code on an isolated and unpersisted state // Cannot be used to create new contracts -func Call(fromAddress, toAddress, data []byte) (*ctypes.ResponseCall, error) { +func Call(fromAddress, toAddress, data []byte) (*ctypes.ResultCall, error) { st := consensusState.GetState() // performs a copy cache := state.NewBlockCache(st) outAcc := cache.GetAccount(toAddress) @@ -47,12 +47,12 @@ func Call(fromAddress, toAddress, data []byte) (*ctypes.ResponseCall, error) { if err != nil { return nil, err } - return &ctypes.ResponseCall{Return: ret}, nil + return &ctypes.ResultCall{Return: ret}, nil } // Run the given code on an isolated and unpersisted state // Cannot be used to create new contracts -func CallCode(fromAddress, code, data []byte) (*ctypes.ResponseCall, error) { +func CallCode(fromAddress, code, data []byte) (*ctypes.ResultCall, error) { st := consensusState.GetState() // performs a copy cache := mempoolReactor.Mempool.GetCache() @@ -72,12 +72,12 @@ func CallCode(fromAddress, code, data []byte) (*ctypes.ResponseCall, error) { if err != nil { return nil, err } - return &ctypes.ResponseCall{Return: ret}, nil + return &ctypes.ResultCall{Return: ret}, nil } //----------------------------------------------------------------------------- -func SignTx(tx types.Tx, privAccounts []*acm.PrivAccount) (types.Tx, error) { +func SignTx(tx types.Tx, privAccounts []*acm.PrivAccount) (*ctypes.ResultSignTx, error) { // more checks? for i, privAccount := range privAccounts { @@ -112,5 +112,5 @@ func SignTx(tx types.Tx, privAccounts []*acm.PrivAccount) (types.Tx, error) { rebondTx := tx.(*types.RebondTx) rebondTx.Signature = privAccounts[0].Sign(config.GetString("chain_id"), rebondTx).(acm.SignatureEd25519) } - return tx, nil + return &ctypes.ResultSignTx{tx}, nil } diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core/types/responses.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core/types/responses.go index cc0363bdbf170026b59860d52ad5705eb6d4132c..bfc35523094de0ec21731046fac236a28fc845d3 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core/types/responses.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core/types/responses.go @@ -2,53 +2,48 @@ package core_types import ( acm "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/account" - sm "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/state" + stypes "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/state/types" "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/types" + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/wire" ) -type ResponseGetStorage struct { +type ResultGetStorage struct { Key []byte `json:"key"` Value []byte `json:"value"` } -type ResponseCall struct { +type ResultCall struct { Return []byte `json:"return"` GasUsed int64 `json:"gas_used"` // TODO ... } -type ResponseListAccounts struct { +type ResultListAccounts struct { BlockHeight int `json:"block_height"` Accounts []*acm.Account `json:"accounts"` } +type ResultDumpStorage struct { + StorageRoot []byte `json:"storage_root"` + StorageItems []StorageItem `json:"storage_items"` +} + type StorageItem struct { Key []byte `json:"key"` Value []byte `json:"value"` } -type ResponseDumpStorage struct { - StorageRoot []byte `json:"storage_root"` - StorageItems []StorageItem `json:"storage_items"` -} - -type ResponseBlockchainInfo struct { +type ResultBlockchainInfo struct { LastHeight int `json:"last_height"` BlockMetas []*types.BlockMeta `json:"block_metas"` } -type ResponseGetBlock struct { +type ResultGetBlock struct { BlockMeta *types.BlockMeta `json:"block_meta"` Block *types.Block `json:"block"` } -type Receipt struct { - TxHash []byte `json:"tx_hash"` - CreatesContract uint8 `json:"creates_contract"` - ContractAddr []byte `json:"contract_addr"` -} - -type ResponseStatus struct { +type ResultStatus struct { NodeInfo *types.NodeInfo `json:"node_info"` GenesisHash []byte `json:"genesis_hash"` PubKey acm.PubKey `json:"pub_key"` @@ -57,7 +52,7 @@ type ResponseStatus struct { LatestBlockTime int64 `json:"latest_block_time"` // nano } -type ResponseNetInfo struct { +type ResultNetInfo struct { Listening bool `json:"listening"` Listeners []string `json:"listeners"` Peers []Peer `json:"peers"` @@ -68,26 +63,115 @@ type Peer struct { IsOutbound bool `json:"is_outbound"` } -type ResponseListValidators struct { - BlockHeight int `json:"block_height"` - BondedValidators []*sm.Validator `json:"bonded_validators"` - UnbondingValidators []*sm.Validator `json:"unbonding_validators"` +type ResultListValidators struct { + BlockHeight int `json:"block_height"` + BondedValidators []*types.Validator `json:"bonded_validators"` + UnbondingValidators []*types.Validator `json:"unbonding_validators"` } -type ResponseDumpConsensusState struct { +type ResultDumpConsensusState struct { RoundState string `json:"round_state"` PeerRoundStates []string `json:"peer_round_states"` } -type ResponseListNames struct { +type ResultListNames struct { BlockHeight int `json:"block_height"` Names []*types.NameRegEntry `json:"names"` } +type ResultGenPrivAccount struct { + PrivAccount *acm.PrivAccount `json:"priv_account"` +} + +type ResultGetAccount struct { + Account *acm.Account `json:"account"` +} + +type ResultBroadcastTx struct { + Receipt Receipt `json:"receipt"` +} + +type Receipt struct { + TxHash []byte `json:"tx_hash"` + CreatesContract uint8 `json:"creates_contract"` + ContractAddr []byte `json:"contract_addr"` +} + +type ResultListUnconfirmedTxs struct { + Txs []types.Tx `json:"txs"` +} + +type ResultGetName struct { + Entry *types.NameRegEntry `json:"entry"` +} + +type ResultGenesis struct { + Genesis *stypes.GenesisDoc `json:"genesis"` +} + +type ResultSignTx struct { + Tx types.Tx `json:"tx"` +} + +type ResultEvent struct { + Event string `json:"event"` + Data types.EventData `json:"data"` +} + //---------------------------------------- -// event responses +// response & result types -type ResponseEvent struct { - Event string `json:"event"` - Data interface{} `json:"data"` +type Response struct { + JSONRPC string `json:"jsonrpc"` + ID string `json:"id"` + Result Result `json:"result"` + Error string `json:"error"` } + +const ( + ResultTypeGetStorage = byte(0x01) + ResultTypeCall = byte(0x02) + ResultTypeListAccounts = byte(0x03) + ResultTypeDumpStorage = byte(0x04) + ResultTypeBlockchainInfo = byte(0x05) + ResultTypeGetBlock = byte(0x06) + ResultTypeStatus = byte(0x07) + ResultTypeNetInfo = byte(0x08) + ResultTypeListValidators = byte(0x09) + ResultTypeDumpConsensusState = byte(0x0A) + ResultTypeListNames = byte(0x0B) + ResultTypeGenPrivAccount = byte(0x0C) + ResultTypeGetAccount = byte(0x0D) + ResultTypeBroadcastTx = byte(0x0E) + ResultTypeListUnconfirmedTxs = byte(0x0F) + ResultTypeGetName = byte(0x10) + ResultTypeGenesis = byte(0x11) + ResultTypeSignTx = byte(0x12) + ResultTypeEvent = byte(0x13) // so websockets can respond to rpc functions +) + +type Result interface{} + +// for wire.readReflect +var _ = wire.RegisterInterface( + struct{ Result }{}, + wire.ConcreteType{&ResultGetStorage{}, ResultTypeGetStorage}, + wire.ConcreteType{&ResultCall{}, ResultTypeCall}, + wire.ConcreteType{&ResultListAccounts{}, ResultTypeListAccounts}, + wire.ConcreteType{&ResultDumpStorage{}, ResultTypeDumpStorage}, + wire.ConcreteType{&ResultBlockchainInfo{}, ResultTypeBlockchainInfo}, + wire.ConcreteType{&ResultGetBlock{}, ResultTypeGetBlock}, + wire.ConcreteType{&ResultStatus{}, ResultTypeStatus}, + wire.ConcreteType{&ResultNetInfo{}, ResultTypeNetInfo}, + wire.ConcreteType{&ResultListValidators{}, ResultTypeListValidators}, + wire.ConcreteType{&ResultDumpConsensusState{}, ResultTypeDumpConsensusState}, + wire.ConcreteType{&ResultListNames{}, ResultTypeListNames}, + wire.ConcreteType{&ResultGenPrivAccount{}, ResultTypeGenPrivAccount}, + wire.ConcreteType{&ResultGetAccount{}, ResultTypeGetAccount}, + wire.ConcreteType{&ResultBroadcastTx{}, ResultTypeBroadcastTx}, + wire.ConcreteType{&ResultListUnconfirmedTxs{}, ResultTypeListUnconfirmedTxs}, + wire.ConcreteType{&ResultGetName{}, ResultTypeGetName}, + wire.ConcreteType{&ResultGenesis{}, ResultTypeGenesis}, + wire.ConcreteType{&ResultSignTx{}, ResultTypeSignTx}, + wire.ConcreteType{&ResultEvent{}, ResultTypeEvent}, +) diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core_client/client.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core_client/client.go new file mode 100644 index 0000000000000000000000000000000000000000..f8c76c5eddc7d8406c4ab53dc3618301de0a6c64 --- /dev/null +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core_client/client.go @@ -0,0 +1,236 @@ +package core_client + +import ( + "bytes" + "fmt" + ctypes "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core/types" + rpctypes "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/types" + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/wire" + "io/ioutil" + "net/http" + "net/url" + + //"reflect" + // Uncomment to use go:generate + // _ "github.com/tendermint/go-rpc-gen" +) + +// maps camel-case function names to lower case rpc version +var reverseFuncMap = map[string]string{ + "Status": "status", + "NetInfo": "net_info", + "BlockchainInfo": "blockchain", + "Genesis": "genesis", + "GetBlock": "get_block", + "GetAccount": "get_account", + "GetStorage": "get_storage", + "Call": "call", + "CallCode": "call_code", + "ListValidators": "list_validators", + "DumpConsensusState": "dump_consensus_state", + "DumpStorage": "dump_storage", + "BroadcastTx": "broadcast_tx", + "ListUnconfirmedTxs": "list_unconfirmed_txs", + "ListAccounts": "list_accounts", + "GetName": "get_name", + "ListNames": "list_names", + "GenPrivAccount": "unsafe/gen_priv_account", + "SignTx": "unsafe/sign_tx", +} + +/* +// fill the map from camelcase to lowercase +func fillReverseFuncMap() map[string]string { + fMap := make(map[string]string) + for name, f := range core.Routes { + camelName := runtime.FuncForPC(f.f.Pointer()).Name() + spl := strings.Split(camelName, ".") + if len(spl) > 1 { + camelName = spl[len(spl)-1] + } + fMap[camelName] = name + } + return fMap +} +*/ + +type Response struct { + Status string + Data interface{} + Error string +} + +//go:generate go-rpc-gen -interface Client -dir ../core -pkg core -type *ClientHTTP,*ClientJSON -exclude pipe.go -out-pkg core_client + +type ClientJSON struct { + addr string +} + +type ClientHTTP struct { + addr string +} + +func NewClient(addr, typ string) Client { + switch typ { + case "HTTP": + return &ClientHTTP{addr} + case "JSONRPC": + return &ClientJSON{addr} + default: + panic("Unknown client type " + typ + ". Select HTTP or JSONRPC") + } + return nil +} + +func argsToJson(args ...interface{}) ([]string, error) { + l := len(args) + jsons := make([]string, l) + n, err := new(int64), new(error) + for i, a := range args { + buf := new(bytes.Buffer) + wire.WriteJSON(a, buf, n, err) + if *err != nil { + return nil, *err + } + jsons[i] = string(buf.Bytes()) + } + return jsons, nil +} + +func (c *ClientJSON) RequestResponse(s rpctypes.RPCRequest) (b []byte, err error) { + b = wire.JSONBytes(s) + buf := bytes.NewBuffer(b) + resp, err := http.Post(c.addr, "text/json", buf) + if err != nil { + return nil, err + } + defer resp.Body.Close() + return ioutil.ReadAll(resp.Body) +} + +/* + What follows is used by `rpc-gen` when `go generate` is called + to populate the rpc client methods +*/ + +// first we define the base interface, which rpc-gen will further populate with generated methods + +/*rpc-gen:define-interface Client +type Client interface { + Address() string // returns the remote address +} +*/ + +// encoding functions + +func binaryWriter(args ...interface{}) ([]interface{}, error) { + list := []interface{}{} + for _, a := range args { + buf, n, err := new(bytes.Buffer), new(int64), new(error) + wire.WriteJSON(a, buf, n, err) + if *err != nil { + return nil, *err + } + list = append(list, buf.Bytes()) + + } + return list, nil +} + +func argsToURLValues(argNames []string, args ...interface{}) (url.Values, error) { + values := make(url.Values) + if len(argNames) == 0 { + return values, nil + } + if len(argNames) != len(args) { + return nil, fmt.Errorf("argNames and args have different lengths: %d, %d", len(argNames), len(args)) + } + slice, err := argsToJson(args...) + if err != nil { + return nil, err + } + for i, name := range argNames { + s := slice[i] + values.Set(name, s) // s[0] + /*for j := 1; j < len(s); j++ { + values.Add(name, s[j]) + }*/ + } + return values, nil +} + +func unmarshalCheckResponse(body []byte) (response *ctypes.Response, err error) { + response = new(ctypes.Response) + wire.ReadJSON(response, body, &err) + if err != nil { + return nil, err + } + if response.Error != "" { + return nil, fmt.Errorf(response.Error) + } + return response, nil +} + +// import statements we will need for the templates + +/*rpc-gen:imports: +rpctypes github.com/tendermint/tendermint/rpc/types +net/http +io/ioutil +fmt +*/ + +// Template functions to be filled in + +/*rpc-gen:template:*ClientJSON func (c *ClientJSON) {{name}}({{args.def}}) ({{response}}) { + request := rpctypes.RPCRequest{ + JSONRPC: "2.0", + Method: reverseFuncMap["{{name}}"], + Params: []interface{}{ {{args.ident}} }, + ID: "", + } + body, err := c.RequestResponse(request) + if err != nil{ + return nil, err + } + response, err := unmarshalCheckResponse(body) + if err != nil{ + return nil, err + } + if response.Result == nil { + return nil, nil + } + result, ok := response.Result.({{response.0}}) + if !ok{ + return nil, fmt.Errorf("response result was wrong type") + } + return result, nil +}*/ + +/*rpc-gen:template:*ClientHTTP func (c *ClientHTTP) {{name}}({{args.def}}) ({{response}}){ + values, err := argsToURLValues({{args.name}}, {{args.ident}}) + if err != nil{ + return nil, err + } + resp, err := http.PostForm(c.addr+reverseFuncMap["{{name}}"], values) + if err != nil { + return nil, err + } + defer resp.Body.Close() + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + return nil, err + } + response, err := unmarshalCheckResponse(body) + if err != nil{ + return nil, err + } + if response.Result == nil { + return nil, nil + } + result, ok := response.Result.({{response.0}}) + if !ok{ + return nil, fmt.Errorf("response result was wrong type") + } + return result, nil +}*/ diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core_client/client_methods.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core_client/client_methods.go new file mode 100644 index 0000000000000000000000000000000000000000..4d37cfcb1ffceb6b86b1bfc533cff249890632c4 --- /dev/null +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core_client/client_methods.go @@ -0,0 +1,1042 @@ +// File generated by github.com/ebuchman/rpc-gen + +package core_client + +import ( + "fmt" + acm "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/account" + ctypes "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core/types" + rpctypes "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/types" + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/types" + "io/ioutil" + "net/http" +) + +type Client interface { + BlockchainInfo(minHeight int, maxHeight int) (*ctypes.ResultBlockchainInfo, error) + BroadcastTx(tx types.Tx) (*ctypes.ResultBroadcastTx, error) + Call(fromAddress []byte, toAddress []byte, data []byte) (*ctypes.ResultCall, error) + CallCode(fromAddress []byte, code []byte, data []byte) (*ctypes.ResultCall, error) + DumpConsensusState() (*ctypes.ResultDumpConsensusState, error) + DumpStorage(address []byte) (*ctypes.ResultDumpStorage, error) + GenPrivAccount() (*ctypes.ResultGenPrivAccount, error) + Genesis() (*ctypes.ResultGenesis, error) + GetAccount(address []byte) (*ctypes.ResultGetAccount, error) + GetBlock(height int) (*ctypes.ResultGetBlock, error) + GetName(name string) (*ctypes.ResultGetName, error) + GetStorage(address []byte, key []byte) (*ctypes.ResultGetStorage, error) + ListAccounts() (*ctypes.ResultListAccounts, error) + ListNames() (*ctypes.ResultListNames, error) + ListUnconfirmedTxs() (*ctypes.ResultListUnconfirmedTxs, error) + ListValidators() (*ctypes.ResultListValidators, error) + NetInfo() (*ctypes.ResultNetInfo, error) + SignTx(tx types.Tx, privAccounts []*acm.PrivAccount) (*ctypes.ResultSignTx, error) + Status() (*ctypes.ResultStatus, error) +} + +func (c *ClientHTTP) BlockchainInfo(minHeight int, maxHeight int) (*ctypes.ResultBlockchainInfo, error) { + values, err := argsToURLValues([]string{"minHeight", "maxHeight"}, minHeight, maxHeight) + if err != nil { + return nil, err + } + resp, err := http.PostForm(c.addr+reverseFuncMap["BlockchainInfo"], values) + if err != nil { + return nil, err + } + defer resp.Body.Close() + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + return nil, err + } + response, err := unmarshalCheckResponse(body) + if err != nil { + return nil, err + } + if response.Result == nil { + return nil, nil + } + result, ok := response.Result.(*ctypes.ResultBlockchainInfo) + if !ok { + return nil, fmt.Errorf("response result was wrong type") + } + return result, nil +} + +func (c *ClientHTTP) BroadcastTx(tx types.Tx) (*ctypes.ResultBroadcastTx, error) { + values, err := argsToURLValues([]string{"tx"}, tx) + if err != nil { + return nil, err + } + resp, err := http.PostForm(c.addr+reverseFuncMap["BroadcastTx"], values) + if err != nil { + return nil, err + } + defer resp.Body.Close() + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + return nil, err + } + response, err := unmarshalCheckResponse(body) + if err != nil { + return nil, err + } + if response.Result == nil { + return nil, nil + } + result, ok := response.Result.(*ctypes.ResultBroadcastTx) + if !ok { + return nil, fmt.Errorf("response result was wrong type") + } + return result, nil +} + +func (c *ClientHTTP) Call(fromAddress []byte, toAddress []byte, data []byte) (*ctypes.ResultCall, error) { + values, err := argsToURLValues([]string{"fromAddress", "toAddress", "data"}, fromAddress, toAddress, data) + if err != nil { + return nil, err + } + resp, err := http.PostForm(c.addr+reverseFuncMap["Call"], values) + if err != nil { + return nil, err + } + defer resp.Body.Close() + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + return nil, err + } + response, err := unmarshalCheckResponse(body) + if err != nil { + return nil, err + } + if response.Result == nil { + return nil, nil + } + result, ok := response.Result.(*ctypes.ResultCall) + if !ok { + return nil, fmt.Errorf("response result was wrong type") + } + return result, nil +} + +func (c *ClientHTTP) CallCode(fromAddress []byte, code []byte, data []byte) (*ctypes.ResultCall, error) { + values, err := argsToURLValues([]string{"fromAddress", "code", "data"}, fromAddress, code, data) + if err != nil { + return nil, err + } + resp, err := http.PostForm(c.addr+reverseFuncMap["CallCode"], values) + if err != nil { + return nil, err + } + defer resp.Body.Close() + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + return nil, err + } + response, err := unmarshalCheckResponse(body) + if err != nil { + return nil, err + } + if response.Result == nil { + return nil, nil + } + result, ok := response.Result.(*ctypes.ResultCall) + if !ok { + return nil, fmt.Errorf("response result was wrong type") + } + return result, nil +} + +func (c *ClientHTTP) DumpConsensusState() (*ctypes.ResultDumpConsensusState, error) { + values, err := argsToURLValues(nil) + if err != nil { + return nil, err + } + resp, err := http.PostForm(c.addr+reverseFuncMap["DumpConsensusState"], values) + if err != nil { + return nil, err + } + defer resp.Body.Close() + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + return nil, err + } + response, err := unmarshalCheckResponse(body) + if err != nil { + return nil, err + } + if response.Result == nil { + return nil, nil + } + result, ok := response.Result.(*ctypes.ResultDumpConsensusState) + if !ok { + return nil, fmt.Errorf("response result was wrong type") + } + return result, nil +} + +func (c *ClientHTTP) DumpStorage(address []byte) (*ctypes.ResultDumpStorage, error) { + values, err := argsToURLValues([]string{"address"}, address) + if err != nil { + return nil, err + } + resp, err := http.PostForm(c.addr+reverseFuncMap["DumpStorage"], values) + if err != nil { + return nil, err + } + defer resp.Body.Close() + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + return nil, err + } + response, err := unmarshalCheckResponse(body) + if err != nil { + return nil, err + } + if response.Result == nil { + return nil, nil + } + result, ok := response.Result.(*ctypes.ResultDumpStorage) + if !ok { + return nil, fmt.Errorf("response result was wrong type") + } + return result, nil +} + +func (c *ClientHTTP) GenPrivAccount() (*ctypes.ResultGenPrivAccount, error) { + values, err := argsToURLValues(nil) + if err != nil { + return nil, err + } + resp, err := http.PostForm(c.addr+reverseFuncMap["GenPrivAccount"], values) + if err != nil { + return nil, err + } + defer resp.Body.Close() + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + return nil, err + } + response, err := unmarshalCheckResponse(body) + if err != nil { + return nil, err + } + if response.Result == nil { + return nil, nil + } + result, ok := response.Result.(*ctypes.ResultGenPrivAccount) + if !ok { + return nil, fmt.Errorf("response result was wrong type") + } + return result, nil +} + +func (c *ClientHTTP) Genesis() (*ctypes.ResultGenesis, error) { + values, err := argsToURLValues(nil) + if err != nil { + return nil, err + } + resp, err := http.PostForm(c.addr+reverseFuncMap["Genesis"], values) + if err != nil { + return nil, err + } + defer resp.Body.Close() + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + return nil, err + } + response, err := unmarshalCheckResponse(body) + if err != nil { + return nil, err + } + if response.Result == nil { + return nil, nil + } + result, ok := response.Result.(*ctypes.ResultGenesis) + if !ok { + return nil, fmt.Errorf("response result was wrong type") + } + return result, nil +} + +func (c *ClientHTTP) GetAccount(address []byte) (*ctypes.ResultGetAccount, error) { + values, err := argsToURLValues([]string{"address"}, address) + if err != nil { + return nil, err + } + resp, err := http.PostForm(c.addr+reverseFuncMap["GetAccount"], values) + if err != nil { + return nil, err + } + defer resp.Body.Close() + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + return nil, err + } + response, err := unmarshalCheckResponse(body) + if err != nil { + return nil, err + } + if response.Result == nil { + return nil, nil + } + result, ok := response.Result.(*ctypes.ResultGetAccount) + if !ok { + return nil, fmt.Errorf("response result was wrong type") + } + return result, nil +} + +func (c *ClientHTTP) GetBlock(height int) (*ctypes.ResultGetBlock, error) { + values, err := argsToURLValues([]string{"height"}, height) + if err != nil { + return nil, err + } + resp, err := http.PostForm(c.addr+reverseFuncMap["GetBlock"], values) + if err != nil { + return nil, err + } + defer resp.Body.Close() + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + return nil, err + } + response, err := unmarshalCheckResponse(body) + if err != nil { + return nil, err + } + if response.Result == nil { + return nil, nil + } + result, ok := response.Result.(*ctypes.ResultGetBlock) + if !ok { + return nil, fmt.Errorf("response result was wrong type") + } + return result, nil +} + +func (c *ClientHTTP) GetName(name string) (*ctypes.ResultGetName, error) { + values, err := argsToURLValues([]string{"name"}, name) + if err != nil { + return nil, err + } + resp, err := http.PostForm(c.addr+reverseFuncMap["GetName"], values) + if err != nil { + return nil, err + } + defer resp.Body.Close() + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + return nil, err + } + response, err := unmarshalCheckResponse(body) + if err != nil { + return nil, err + } + if response.Result == nil { + return nil, nil + } + result, ok := response.Result.(*ctypes.ResultGetName) + if !ok { + return nil, fmt.Errorf("response result was wrong type") + } + return result, nil +} + +func (c *ClientHTTP) GetStorage(address []byte, key []byte) (*ctypes.ResultGetStorage, error) { + values, err := argsToURLValues([]string{"address", "key"}, address, key) + if err != nil { + return nil, err + } + resp, err := http.PostForm(c.addr+reverseFuncMap["GetStorage"], values) + if err != nil { + return nil, err + } + defer resp.Body.Close() + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + return nil, err + } + response, err := unmarshalCheckResponse(body) + if err != nil { + return nil, err + } + if response.Result == nil { + return nil, nil + } + result, ok := response.Result.(*ctypes.ResultGetStorage) + if !ok { + return nil, fmt.Errorf("response result was wrong type") + } + return result, nil +} + +func (c *ClientHTTP) ListAccounts() (*ctypes.ResultListAccounts, error) { + values, err := argsToURLValues(nil) + if err != nil { + return nil, err + } + resp, err := http.PostForm(c.addr+reverseFuncMap["ListAccounts"], values) + if err != nil { + return nil, err + } + defer resp.Body.Close() + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + return nil, err + } + response, err := unmarshalCheckResponse(body) + if err != nil { + return nil, err + } + if response.Result == nil { + return nil, nil + } + result, ok := response.Result.(*ctypes.ResultListAccounts) + if !ok { + return nil, fmt.Errorf("response result was wrong type") + } + return result, nil +} + +func (c *ClientHTTP) ListNames() (*ctypes.ResultListNames, error) { + values, err := argsToURLValues(nil) + if err != nil { + return nil, err + } + resp, err := http.PostForm(c.addr+reverseFuncMap["ListNames"], values) + if err != nil { + return nil, err + } + defer resp.Body.Close() + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + return nil, err + } + response, err := unmarshalCheckResponse(body) + if err != nil { + return nil, err + } + if response.Result == nil { + return nil, nil + } + result, ok := response.Result.(*ctypes.ResultListNames) + if !ok { + return nil, fmt.Errorf("response result was wrong type") + } + return result, nil +} + +func (c *ClientHTTP) ListUnconfirmedTxs() (*ctypes.ResultListUnconfirmedTxs, error) { + values, err := argsToURLValues(nil) + if err != nil { + return nil, err + } + resp, err := http.PostForm(c.addr+reverseFuncMap["ListUnconfirmedTxs"], values) + if err != nil { + return nil, err + } + defer resp.Body.Close() + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + return nil, err + } + response, err := unmarshalCheckResponse(body) + if err != nil { + return nil, err + } + if response.Result == nil { + return nil, nil + } + result, ok := response.Result.(*ctypes.ResultListUnconfirmedTxs) + if !ok { + return nil, fmt.Errorf("response result was wrong type") + } + return result, nil +} + +func (c *ClientHTTP) ListValidators() (*ctypes.ResultListValidators, error) { + values, err := argsToURLValues(nil) + if err != nil { + return nil, err + } + resp, err := http.PostForm(c.addr+reverseFuncMap["ListValidators"], values) + if err != nil { + return nil, err + } + defer resp.Body.Close() + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + return nil, err + } + response, err := unmarshalCheckResponse(body) + if err != nil { + return nil, err + } + if response.Result == nil { + return nil, nil + } + result, ok := response.Result.(*ctypes.ResultListValidators) + if !ok { + return nil, fmt.Errorf("response result was wrong type") + } + return result, nil +} + +func (c *ClientHTTP) NetInfo() (*ctypes.ResultNetInfo, error) { + values, err := argsToURLValues(nil) + if err != nil { + return nil, err + } + resp, err := http.PostForm(c.addr+reverseFuncMap["NetInfo"], values) + if err != nil { + return nil, err + } + defer resp.Body.Close() + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + return nil, err + } + response, err := unmarshalCheckResponse(body) + if err != nil { + return nil, err + } + if response.Result == nil { + return nil, nil + } + result, ok := response.Result.(*ctypes.ResultNetInfo) + if !ok { + return nil, fmt.Errorf("response result was wrong type") + } + return result, nil +} + +func (c *ClientHTTP) SignTx(tx types.Tx, privAccounts []*acm.PrivAccount) (*ctypes.ResultSignTx, error) { + values, err := argsToURLValues([]string{"tx", "privAccounts"}, tx, privAccounts) + if err != nil { + return nil, err + } + resp, err := http.PostForm(c.addr+reverseFuncMap["SignTx"], values) + if err != nil { + return nil, err + } + defer resp.Body.Close() + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + return nil, err + } + response, err := unmarshalCheckResponse(body) + if err != nil { + return nil, err + } + if response.Result == nil { + return nil, nil + } + result, ok := response.Result.(*ctypes.ResultSignTx) + if !ok { + return nil, fmt.Errorf("response result was wrong type") + } + return result, nil +} + +func (c *ClientHTTP) Status() (*ctypes.ResultStatus, error) { + values, err := argsToURLValues(nil) + if err != nil { + return nil, err + } + resp, err := http.PostForm(c.addr+reverseFuncMap["Status"], values) + if err != nil { + return nil, err + } + defer resp.Body.Close() + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + return nil, err + } + response, err := unmarshalCheckResponse(body) + if err != nil { + return nil, err + } + if response.Result == nil { + return nil, nil + } + result, ok := response.Result.(*ctypes.ResultStatus) + if !ok { + return nil, fmt.Errorf("response result was wrong type") + } + return result, nil +} + +func (c *ClientJSON) BlockchainInfo(minHeight int, maxHeight int) (*ctypes.ResultBlockchainInfo, error) { + request := rpctypes.RPCRequest{ + JSONRPC: "2.0", + Method: reverseFuncMap["BlockchainInfo"], + Params: []interface{}{minHeight, maxHeight}, + ID: "", + } + body, err := c.RequestResponse(request) + if err != nil { + return nil, err + } + response, err := unmarshalCheckResponse(body) + if err != nil { + return nil, err + } + if response.Result == nil { + return nil, nil + } + result, ok := response.Result.(*ctypes.ResultBlockchainInfo) + if !ok { + return nil, fmt.Errorf("response result was wrong type") + } + return result, nil +} + +func (c *ClientJSON) BroadcastTx(tx types.Tx) (*ctypes.ResultBroadcastTx, error) { + request := rpctypes.RPCRequest{ + JSONRPC: "2.0", + Method: reverseFuncMap["BroadcastTx"], + Params: []interface{}{tx}, + ID: "", + } + body, err := c.RequestResponse(request) + if err != nil { + return nil, err + } + response, err := unmarshalCheckResponse(body) + if err != nil { + return nil, err + } + if response.Result == nil { + return nil, nil + } + result, ok := response.Result.(*ctypes.ResultBroadcastTx) + if !ok { + return nil, fmt.Errorf("response result was wrong type") + } + return result, nil +} + +func (c *ClientJSON) Call(fromAddress []byte, toAddress []byte, data []byte) (*ctypes.ResultCall, error) { + request := rpctypes.RPCRequest{ + JSONRPC: "2.0", + Method: reverseFuncMap["Call"], + Params: []interface{}{fromAddress, toAddress, data}, + ID: "", + } + body, err := c.RequestResponse(request) + if err != nil { + return nil, err + } + response, err := unmarshalCheckResponse(body) + if err != nil { + return nil, err + } + if response.Result == nil { + return nil, nil + } + result, ok := response.Result.(*ctypes.ResultCall) + if !ok { + return nil, fmt.Errorf("response result was wrong type") + } + return result, nil +} + +func (c *ClientJSON) CallCode(fromAddress []byte, code []byte, data []byte) (*ctypes.ResultCall, error) { + request := rpctypes.RPCRequest{ + JSONRPC: "2.0", + Method: reverseFuncMap["CallCode"], + Params: []interface{}{fromAddress, code, data}, + ID: "", + } + body, err := c.RequestResponse(request) + if err != nil { + return nil, err + } + response, err := unmarshalCheckResponse(body) + if err != nil { + return nil, err + } + if response.Result == nil { + return nil, nil + } + result, ok := response.Result.(*ctypes.ResultCall) + if !ok { + return nil, fmt.Errorf("response result was wrong type") + } + return result, nil +} + +func (c *ClientJSON) DumpConsensusState() (*ctypes.ResultDumpConsensusState, error) { + request := rpctypes.RPCRequest{ + JSONRPC: "2.0", + Method: reverseFuncMap["DumpConsensusState"], + Params: []interface{}{}, + ID: "", + } + body, err := c.RequestResponse(request) + if err != nil { + return nil, err + } + response, err := unmarshalCheckResponse(body) + if err != nil { + return nil, err + } + if response.Result == nil { + return nil, nil + } + result, ok := response.Result.(*ctypes.ResultDumpConsensusState) + if !ok { + return nil, fmt.Errorf("response result was wrong type") + } + return result, nil +} + +func (c *ClientJSON) DumpStorage(address []byte) (*ctypes.ResultDumpStorage, error) { + request := rpctypes.RPCRequest{ + JSONRPC: "2.0", + Method: reverseFuncMap["DumpStorage"], + Params: []interface{}{address}, + ID: "", + } + body, err := c.RequestResponse(request) + if err != nil { + return nil, err + } + response, err := unmarshalCheckResponse(body) + if err != nil { + return nil, err + } + if response.Result == nil { + return nil, nil + } + result, ok := response.Result.(*ctypes.ResultDumpStorage) + if !ok { + return nil, fmt.Errorf("response result was wrong type") + } + return result, nil +} + +func (c *ClientJSON) GenPrivAccount() (*ctypes.ResultGenPrivAccount, error) { + request := rpctypes.RPCRequest{ + JSONRPC: "2.0", + Method: reverseFuncMap["GenPrivAccount"], + Params: []interface{}{}, + ID: "", + } + body, err := c.RequestResponse(request) + if err != nil { + return nil, err + } + response, err := unmarshalCheckResponse(body) + if err != nil { + return nil, err + } + if response.Result == nil { + return nil, nil + } + result, ok := response.Result.(*ctypes.ResultGenPrivAccount) + if !ok { + return nil, fmt.Errorf("response result was wrong type") + } + return result, nil +} + +func (c *ClientJSON) Genesis() (*ctypes.ResultGenesis, error) { + request := rpctypes.RPCRequest{ + JSONRPC: "2.0", + Method: reverseFuncMap["Genesis"], + Params: []interface{}{}, + ID: "", + } + body, err := c.RequestResponse(request) + if err != nil { + return nil, err + } + response, err := unmarshalCheckResponse(body) + if err != nil { + return nil, err + } + if response.Result == nil { + return nil, nil + } + result, ok := response.Result.(*ctypes.ResultGenesis) + if !ok { + return nil, fmt.Errorf("response result was wrong type") + } + return result, nil +} + +func (c *ClientJSON) GetAccount(address []byte) (*ctypes.ResultGetAccount, error) { + request := rpctypes.RPCRequest{ + JSONRPC: "2.0", + Method: reverseFuncMap["GetAccount"], + Params: []interface{}{address}, + ID: "", + } + body, err := c.RequestResponse(request) + if err != nil { + return nil, err + } + response, err := unmarshalCheckResponse(body) + if err != nil { + return nil, err + } + if response.Result == nil { + return nil, nil + } + result, ok := response.Result.(*ctypes.ResultGetAccount) + if !ok { + return nil, fmt.Errorf("response result was wrong type") + } + return result, nil +} + +func (c *ClientJSON) GetBlock(height int) (*ctypes.ResultGetBlock, error) { + request := rpctypes.RPCRequest{ + JSONRPC: "2.0", + Method: reverseFuncMap["GetBlock"], + Params: []interface{}{height}, + ID: "", + } + body, err := c.RequestResponse(request) + if err != nil { + return nil, err + } + response, err := unmarshalCheckResponse(body) + if err != nil { + return nil, err + } + if response.Result == nil { + return nil, nil + } + result, ok := response.Result.(*ctypes.ResultGetBlock) + if !ok { + return nil, fmt.Errorf("response result was wrong type") + } + return result, nil +} + +func (c *ClientJSON) GetName(name string) (*ctypes.ResultGetName, error) { + request := rpctypes.RPCRequest{ + JSONRPC: "2.0", + Method: reverseFuncMap["GetName"], + Params: []interface{}{name}, + ID: "", + } + body, err := c.RequestResponse(request) + if err != nil { + return nil, err + } + response, err := unmarshalCheckResponse(body) + if err != nil { + return nil, err + } + if response.Result == nil { + return nil, nil + } + result, ok := response.Result.(*ctypes.ResultGetName) + if !ok { + return nil, fmt.Errorf("response result was wrong type") + } + return result, nil +} + +func (c *ClientJSON) GetStorage(address []byte, key []byte) (*ctypes.ResultGetStorage, error) { + request := rpctypes.RPCRequest{ + JSONRPC: "2.0", + Method: reverseFuncMap["GetStorage"], + Params: []interface{}{address, key}, + ID: "", + } + body, err := c.RequestResponse(request) + if err != nil { + return nil, err + } + response, err := unmarshalCheckResponse(body) + if err != nil { + return nil, err + } + if response.Result == nil { + return nil, nil + } + result, ok := response.Result.(*ctypes.ResultGetStorage) + if !ok { + return nil, fmt.Errorf("response result was wrong type") + } + return result, nil +} + +func (c *ClientJSON) ListAccounts() (*ctypes.ResultListAccounts, error) { + request := rpctypes.RPCRequest{ + JSONRPC: "2.0", + Method: reverseFuncMap["ListAccounts"], + Params: []interface{}{}, + ID: "", + } + body, err := c.RequestResponse(request) + if err != nil { + return nil, err + } + response, err := unmarshalCheckResponse(body) + if err != nil { + return nil, err + } + if response.Result == nil { + return nil, nil + } + result, ok := response.Result.(*ctypes.ResultListAccounts) + if !ok { + return nil, fmt.Errorf("response result was wrong type") + } + return result, nil +} + +func (c *ClientJSON) ListNames() (*ctypes.ResultListNames, error) { + request := rpctypes.RPCRequest{ + JSONRPC: "2.0", + Method: reverseFuncMap["ListNames"], + Params: []interface{}{}, + ID: "", + } + body, err := c.RequestResponse(request) + if err != nil { + return nil, err + } + response, err := unmarshalCheckResponse(body) + if err != nil { + return nil, err + } + if response.Result == nil { + return nil, nil + } + result, ok := response.Result.(*ctypes.ResultListNames) + if !ok { + return nil, fmt.Errorf("response result was wrong type") + } + return result, nil +} + +func (c *ClientJSON) ListUnconfirmedTxs() (*ctypes.ResultListUnconfirmedTxs, error) { + request := rpctypes.RPCRequest{ + JSONRPC: "2.0", + Method: reverseFuncMap["ListUnconfirmedTxs"], + Params: []interface{}{}, + ID: "", + } + body, err := c.RequestResponse(request) + if err != nil { + return nil, err + } + response, err := unmarshalCheckResponse(body) + if err != nil { + return nil, err + } + if response.Result == nil { + return nil, nil + } + result, ok := response.Result.(*ctypes.ResultListUnconfirmedTxs) + if !ok { + return nil, fmt.Errorf("response result was wrong type") + } + return result, nil +} + +func (c *ClientJSON) ListValidators() (*ctypes.ResultListValidators, error) { + request := rpctypes.RPCRequest{ + JSONRPC: "2.0", + Method: reverseFuncMap["ListValidators"], + Params: []interface{}{}, + ID: "", + } + body, err := c.RequestResponse(request) + if err != nil { + return nil, err + } + response, err := unmarshalCheckResponse(body) + if err != nil { + return nil, err + } + if response.Result == nil { + return nil, nil + } + result, ok := response.Result.(*ctypes.ResultListValidators) + if !ok { + return nil, fmt.Errorf("response result was wrong type") + } + return result, nil +} + +func (c *ClientJSON) NetInfo() (*ctypes.ResultNetInfo, error) { + request := rpctypes.RPCRequest{ + JSONRPC: "2.0", + Method: reverseFuncMap["NetInfo"], + Params: []interface{}{}, + ID: "", + } + body, err := c.RequestResponse(request) + if err != nil { + return nil, err + } + response, err := unmarshalCheckResponse(body) + if err != nil { + return nil, err + } + if response.Result == nil { + return nil, nil + } + result, ok := response.Result.(*ctypes.ResultNetInfo) + if !ok { + return nil, fmt.Errorf("response result was wrong type") + } + return result, nil +} + +func (c *ClientJSON) SignTx(tx types.Tx, privAccounts []*acm.PrivAccount) (*ctypes.ResultSignTx, error) { + request := rpctypes.RPCRequest{ + JSONRPC: "2.0", + Method: reverseFuncMap["SignTx"], + Params: []interface{}{tx, privAccounts}, + ID: "", + } + body, err := c.RequestResponse(request) + if err != nil { + return nil, err + } + response, err := unmarshalCheckResponse(body) + if err != nil { + return nil, err + } + if response.Result == nil { + return nil, nil + } + result, ok := response.Result.(*ctypes.ResultSignTx) + if !ok { + return nil, fmt.Errorf("response result was wrong type") + } + return result, nil +} + +func (c *ClientJSON) Status() (*ctypes.ResultStatus, error) { + request := rpctypes.RPCRequest{ + JSONRPC: "2.0", + Method: reverseFuncMap["Status"], + Params: []interface{}{}, + ID: "", + } + body, err := c.RequestResponse(request) + if err != nil { + return nil, err + } + response, err := unmarshalCheckResponse(body) + if err != nil { + return nil, err + } + if response.Result == nil { + return nil, nil + } + result, ok := response.Result.(*ctypes.ResultStatus) + if !ok { + return nil, fmt.Errorf("response result was wrong type") + } + return result, nil +} diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core_client/log.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core_client/log.go new file mode 100644 index 0000000000000000000000000000000000000000..91c5ec3b95994acb808d195da4647ffdc6f61cff --- /dev/null +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core_client/log.go @@ -0,0 +1,7 @@ +package core_client + +import ( + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/log15" +) + +var log = log15.New("module", "core_client") diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core_client/ws_client.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core_client/ws_client.go new file mode 100644 index 0000000000000000000000000000000000000000..2ca57bc7b9b8eaa4bbd6b3188f507861486b06bd --- /dev/null +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core_client/ws_client.go @@ -0,0 +1,119 @@ +package core_client + +import ( + "net/http" + "strings" + "time" + + . "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/common" + ctypes "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core/types" + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/types" + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/wire" + "github.com/gorilla/websocket" +) + +const ( + wsEventsChannelCapacity = 10 + wsResultsChannelCapacity = 10 + wsWriteTimeoutSeconds = 10 +) + +type WSClient struct { + QuitService + Address string + *websocket.Conn + EventsCh chan ctypes.ResultEvent + ResultsCh chan ctypes.Result +} + +// create a new connection +func NewWSClient(addr string) *WSClient { + wsClient := &WSClient{ + Address: addr, + Conn: nil, + EventsCh: make(chan ctypes.ResultEvent, wsEventsChannelCapacity), + ResultsCh: make(chan ctypes.Result, wsResultsChannelCapacity), + } + wsClient.QuitService = *NewQuitService(log, "WSClient", wsClient) + return wsClient +} + +func (wsc *WSClient) OnStart() error { + wsc.QuitService.OnStart() + err := wsc.dial() + if err != nil { + return err + } + go wsc.receiveEventsRoutine() + return nil +} + +func (wsc *WSClient) dial() error { + // Dial + dialer := websocket.DefaultDialer + rHeader := http.Header{} + con, _, err := dialer.Dial(wsc.Address, rHeader) + if err != nil { + return err + } + // Set the ping/pong handlers + con.SetPingHandler(func(m string) error { + con.WriteControl(websocket.PongMessage, []byte(m), time.Now().Add(time.Second*wsWriteTimeoutSeconds)) + return nil + }) + con.SetPongHandler(func(m string) error { + return nil + }) + wsc.Conn = con + return nil +} + +func (wsc *WSClient) OnStop() { + wsc.QuitService.OnStop() +} + +func (wsc *WSClient) receiveEventsRoutine() { + for { + _, data, err := wsc.ReadMessage() + if err != nil { + log.Info("WSClient failed to read message", "error", err, "data", string(data)) + wsc.Stop() + break + } else { + var response ctypes.Response + wire.ReadJSON(&response, data, &err) + if err != nil { + log.Info("WSClient failed to parse message", "error", err) + wsc.Stop() + break + } + if strings.HasSuffix(response.ID, "#event") { + wsc.EventsCh <- *response.Result.(*ctypes.ResultEvent) + } else { + wsc.ResultsCh <- response.Result + } + } + } +} + +// subscribe to an event +func (wsc *WSClient) Subscribe(eventid string) error { + err := wsc.WriteJSON(rpctypes.RPCRequest{ + JSONRPC: "2.0", + ID: "", + Method: "subscribe", + Params: []interface{}{eventid}, + }) + return err +} + +// unsubscribe from an event +func (wsc *WSClient) Unsubscribe(eventid string) error { + err := wsc.WriteJSON(rpctypes.RPCRequest{ + JSONRPC: "2.0", + ID: "", + Method: "unsubscribe", + Params: []interface{}{eventid}, + }) + return err +} diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/server/handlers.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/server/handlers.go index aca3addf548afd789a535c800876d46501b03b8b..51473b2def1705a142eb6d0fddc6ed0e26803d11 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/server/handlers.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/server/handlers.go @@ -11,11 +11,13 @@ import ( "sort" "time" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/gorilla/websocket" . "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/common" "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/events" + ctypes "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core/types" . "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/types" + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/types" "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/wire" + "github.com/gorilla/websocket" ) func RegisterRPCFuncs(mux *http.ServeMux, funcMap map[string]*RPCFunc) { @@ -53,22 +55,22 @@ func NewRPCFunc(f interface{}, args []string) *RPCFunc { func funcArgTypes(f interface{}) []reflect.Type { t := reflect.TypeOf(f) n := t.NumIn() - types := make([]reflect.Type, n) + typez := make([]reflect.Type, n) for i := 0; i < n; i++ { - types[i] = t.In(i) + typez[i] = t.In(i) } - return types + return typez } // return a function's return types func funcReturnTypes(f interface{}) []reflect.Type { t := reflect.TypeOf(f) n := t.NumOut() - types := make([]reflect.Type, n) + typez := make([]reflect.Type, n) for i := 0; i < n; i++ { - types[i] = t.Out(i) + typez[i] = t.Out(i) } - return types + return typez } // function introspection @@ -93,27 +95,27 @@ func makeJSONRPCHandler(funcMap map[string]*RPCFunc) http.HandlerFunc { return } if len(r.URL.Path) > 1 { - WriteRPCResponse(w, NewRPCResponse(request.Id, nil, fmt.Sprintf("Invalid JSONRPC endpoint %s", r.URL.Path))) + WriteRPCResponse(w, NewRPCResponse(request.ID, nil, fmt.Sprintf("Invalid JSONRPC endpoint %s", r.URL.Path))) return } rpcFunc := funcMap[request.Method] if rpcFunc == nil { - WriteRPCResponse(w, NewRPCResponse(request.Id, nil, "RPC method unknown: "+request.Method)) + WriteRPCResponse(w, NewRPCResponse(request.ID, nil, "RPC method unknown: "+request.Method)) return } args, err := jsonParamsToArgs(rpcFunc, request.Params) if err != nil { - WriteRPCResponse(w, NewRPCResponse(request.Id, nil, err.Error())) + WriteRPCResponse(w, NewRPCResponse(request.ID, nil, err.Error())) return } returns := rpcFunc.f.Call(args) log.Info("HTTPJSONRPC", "method", request.Method, "args", args, "returns", returns) result, err := unreflectResult(returns) if err != nil { - WriteRPCResponse(w, NewRPCResponse(request.Id, nil, err.Error())) + WriteRPCResponse(w, NewRPCResponse(request.ID, nil, err.Error())) return } - WriteRPCResponse(w, NewRPCResponse(request.Id, result, "")) + WriteRPCResponse(w, NewRPCResponse(request.ID, result, "")) } } @@ -205,8 +207,9 @@ func _jsonStringToArg(ty reflect.Type, arg string) (reflect.Value, error) { const ( writeChanCapacity = 20 - WSWriteTimeoutSeconds = 10 // exposed for tests - WSReadTimeoutSeconds = 10 // exposed for tests + wsWriteTimeoutSeconds = 30 // each write times out after this + wsReadTimeoutSeconds = 30 // connection times out if we haven't received *anything* in this long, not even pings. + wsPingTickerSeconds = 10 // send a ping every PingTickerSeconds. ) // a single websocket connection @@ -219,6 +222,7 @@ type WSConnection struct { baseConn *websocket.Conn writeChan chan RPCResponse readTimeout *time.Timer + pingTicker *time.Ticker funcMap map[string]*RPCFunc evsw *events.EventSwitch @@ -238,33 +242,36 @@ func NewWSConnection(baseConn *websocket.Conn, funcMap map[string]*RPCFunc, evsw } // wsc.Start() blocks until the connection closes. -func (wsc *WSConnection) OnStart() { +func (wsc *WSConnection) OnStart() error { wsc.QuitService.OnStart() // Read subscriptions/unsubscriptions to events go wsc.readRoutine() // Custom Ping handler to touch readTimeout - wsc.readTimeout = time.NewTimer(time.Second * WSReadTimeoutSeconds) + wsc.readTimeout = time.NewTimer(time.Second * wsReadTimeoutSeconds) + wsc.pingTicker = time.NewTicker(time.Second * wsPingTickerSeconds) wsc.baseConn.SetPingHandler(func(m string) error { - wsc.baseConn.WriteControl(websocket.PongMessage, []byte(m), time.Now().Add(time.Second*WSWriteTimeoutSeconds)) - wsc.readTimeout.Reset(time.Second * WSReadTimeoutSeconds) + wsc.baseConn.WriteControl(websocket.PongMessage, []byte(m), time.Now().Add(time.Second*wsWriteTimeoutSeconds)) + wsc.readTimeout.Reset(time.Second * wsReadTimeoutSeconds) return nil }) wsc.baseConn.SetPongHandler(func(m string) error { - wsc.readTimeout.Reset(time.Second * WSReadTimeoutSeconds) + wsc.readTimeout.Reset(time.Second * wsReadTimeoutSeconds) return nil }) go wsc.readTimeoutRoutine() // Write responses, BLOCKING. wsc.writeRoutine() + return nil } func (wsc *WSConnection) OnStop() { wsc.QuitService.OnStop() wsc.evsw.RemoveListener(wsc.id) wsc.readTimeout.Stop() + wsc.pingTicker.Stop() // The write loop closes the websocket connection // when it exits its loop, and the read loop // closes the writeChan @@ -302,7 +309,7 @@ func (wsc *WSConnection) readRoutine() { default: var in []byte // Do not set a deadline here like below: - // wsc.baseConn.SetReadDeadline(time.Now().Add(time.Second * WSReadTimeoutSeconds)) + // wsc.baseConn.SetReadDeadline(time.Now().Add(time.Second * wsReadTimeoutSeconds)) // The client may not send anything for a while. // We use `readTimeout` to handle read timeouts. _, in, err := wsc.baseConn.ReadMessage() @@ -317,22 +324,23 @@ func (wsc *WSConnection) readRoutine() { err = json.Unmarshal(in, &request) if err != nil { errStr := fmt.Sprintf("Error unmarshaling data: %s", err.Error()) - wsc.writeRPCResponse(NewRPCResponse(request.Id, nil, errStr)) + wsc.writeRPCResponse(NewRPCResponse(request.ID, nil, errStr)) continue } switch request.Method { case "subscribe": if len(request.Params) != 1 { - wsc.writeRPCResponse(NewRPCResponse(request.Id, nil, "subscribe takes 1 event parameter string")) + wsc.writeRPCResponse(NewRPCResponse(request.ID, nil, "subscribe takes 1 event parameter string")) continue } if event, ok := request.Params[0].(string); !ok { - wsc.writeRPCResponse(NewRPCResponse(request.Id, nil, "subscribe takes 1 event parameter string")) + wsc.writeRPCResponse(NewRPCResponse(request.ID, nil, "subscribe takes 1 event parameter string")) continue } else { log.Notice("Subscribe to event", "id", wsc.id, "event", event) - wsc.evsw.AddListenerForEvent(wsc.id, event, func(msg interface{}) { - wsc.writeRPCResponse(NewRPCResponse(request.Id, RPCEventResult{event, msg}, "")) + wsc.evsw.AddListenerForEvent(wsc.id, event, func(msg types.EventData) { + // NOTE: RPCResponses of subscribed events have id suffix "#event" + wsc.writeRPCResponse(NewRPCResponse(request.ID+"#event", ctypes.ResultEvent{event, msg}, "")) }) continue } @@ -340,39 +348,41 @@ func (wsc *WSConnection) readRoutine() { if len(request.Params) == 0 { log.Notice("Unsubscribe from all events", "id", wsc.id) wsc.evsw.RemoveListener(wsc.id) + wsc.writeRPCResponse(NewRPCResponse(request.ID, nil, "")) continue } else if len(request.Params) == 1 { if event, ok := request.Params[0].(string); !ok { - wsc.writeRPCResponse(NewRPCResponse(request.Id, nil, "unsubscribe takes 0 or 1 event parameter strings")) + wsc.writeRPCResponse(NewRPCResponse(request.ID, nil, "unsubscribe takes 0 or 1 event parameter strings")) continue } else { log.Notice("Unsubscribe from event", "id", wsc.id, "event", event) wsc.evsw.RemoveListenerForEvent(event, wsc.id) + wsc.writeRPCResponse(NewRPCResponse(request.ID, nil, "")) continue } } else { - wsc.writeRPCResponse(NewRPCResponse(request.Id, nil, "unsubscribe takes 0 or 1 event parameter strings")) + wsc.writeRPCResponse(NewRPCResponse(request.ID, nil, "unsubscribe takes 0 or 1 event parameter strings")) continue } default: rpcFunc := wsc.funcMap[request.Method] if rpcFunc == nil { - wsc.writeRPCResponse(NewRPCResponse(request.Id, nil, "RPC method unknown: "+request.Method)) + wsc.writeRPCResponse(NewRPCResponse(request.ID, nil, "RPC method unknown: "+request.Method)) continue } args, err := jsonParamsToArgs(rpcFunc, request.Params) if err != nil { - wsc.writeRPCResponse(NewRPCResponse(request.Id, nil, err.Error())) + wsc.writeRPCResponse(NewRPCResponse(request.ID, nil, err.Error())) continue } returns := rpcFunc.f.Call(args) log.Info("WSJSONRPC", "method", request.Method, "args", args, "returns", returns) result, err := unreflectResult(returns) if err != nil { - wsc.writeRPCResponse(NewRPCResponse(request.Id, nil, err.Error())) + wsc.writeRPCResponse(NewRPCResponse(request.ID, nil, err.Error())) continue } else { - wsc.writeRPCResponse(NewRPCResponse(request.Id, result, "")) + wsc.writeRPCResponse(NewRPCResponse(request.ID, result, "")) continue } } @@ -383,19 +393,26 @@ func (wsc *WSConnection) readRoutine() { // receives on a write channel and writes out on the socket func (wsc *WSConnection) writeRoutine() { defer wsc.baseConn.Close() - n, err := new(int64), new(error) + var n, err = int64(0), error(nil) for { select { case <-wsc.Quit: return + case <-wsc.pingTicker.C: + err := wsc.baseConn.WriteMessage(websocket.PingMessage, []byte{}) + if err != nil { + log.Error("Failed to write ping message on websocket", "error", err) + wsc.Stop() + return + } case msg := <-wsc.writeChan: buf := new(bytes.Buffer) - wire.WriteJSON(msg, buf, n, err) - if *err != nil { + wire.WriteJSON(msg, buf, &n, &err) + if err != nil { log.Error("Failed to marshal RPCResponse to JSON", "error", err) } else { - wsc.baseConn.SetWriteDeadline(time.Now().Add(time.Second * WSWriteTimeoutSeconds)) - if err := wsc.baseConn.WriteMessage(websocket.TextMessage, buf.Bytes()); err != nil { + wsc.baseConn.SetWriteDeadline(time.Now().Add(time.Second * wsWriteTimeoutSeconds)) + if err = wsc.baseConn.WriteMessage(websocket.TextMessage, buf.Bytes()); err != nil { log.Warn("Failed to write response on websocket", "error", err) wsc.Stop() return @@ -407,8 +424,9 @@ func (wsc *WSConnection) writeRoutine() { //---------------------------------------- -// main manager for all websocket connections -// holds the event switch +// Main manager for all websocket connections +// Holds the event switch +// NOTE: The websocket path is defined externally, e.g. in node/node.go type WebsocketManager struct { websocket.Upgrader funcMap map[string]*RPCFunc diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/server/http_server.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/server/http_server.go index b8d91fb3ed60ed2a2bedbebb08794f4ba3baf914..bf55baedb22cfd37c0e5a1b349565874df2df37b 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/server/http_server.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/server/http_server.go @@ -33,10 +33,10 @@ func StartHTTPServer(listenAddr string, handler http.Handler) (net.Listener, err } func WriteRPCResponse(w http.ResponseWriter, res RPCResponse) { - buf, n, err := new(bytes.Buffer), new(int64), new(error) - wire.WriteJSON(res, buf, n, err) - if *err != nil { - log.Warn("Failed to write RPC response", "error", err) + buf, n, err := new(bytes.Buffer), int64(0), error(nil) + wire.WriteJSON(res, buf, &n, &err) + if err != nil { + log.Error("Failed to write RPC response", "error", err, "res", res) } w.Header().Set("Content-Type", "application/json") diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/test/client_rpc_test.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/test/client_rpc_test.go new file mode 100644 index 0000000000000000000000000000000000000000..c773330c7f134cdb7e85a61ef48859dc29231140 --- /dev/null +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/test/client_rpc_test.go @@ -0,0 +1,129 @@ +package rpctest + +import ( + _ "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/config/tendermint_test" + "testing" +) + +// When run with `-test.short` we only run: +// TestHTTPStatus, TestHTTPBroadcast, TestJSONStatus, TestJSONBroadcast, TestWSConnect, TestWSSend + +//-------------------------------------------------------------------------------- +// Test the HTTP client + +func TestHTTPStatus(t *testing.T) { + testStatus(t, "HTTP") +} + +func TestHTTPGenPriv(t *testing.T) { + if testing.Short() { + t.Skip("skipping test in short mode.") + } + testGenPriv(t, "HTTP") +} + +func TestHTTPGetAccount(t *testing.T) { + if testing.Short() { + t.Skip("skipping test in short mode.") + } + testGetAccount(t, "HTTP") +} + +func TestHTTPSignedTx(t *testing.T) { + if testing.Short() { + t.Skip("skipping test in short mode.") + } + testSignedTx(t, "HTTP") +} + +func TestHTTPBroadcastTx(t *testing.T) { + testBroadcastTx(t, "HTTP") +} + +func TestHTTPGetStorage(t *testing.T) { + if testing.Short() { + t.Skip("skipping test in short mode.") + } + testGetStorage(t, "HTTP") +} + +func TestHTTPCallCode(t *testing.T) { + if testing.Short() { + t.Skip("skipping test in short mode.") + } + testCallCode(t, "HTTP") +} + +func TestHTTPCallContract(t *testing.T) { + if testing.Short() { + t.Skip("skipping test in short mode.") + } + testCall(t, "HTTP") +} + +func TestHTTPNameReg(t *testing.T) { + if testing.Short() { + t.Skip("skipping test in short mode.") + } + testNameReg(t, "HTTP") +} + +//-------------------------------------------------------------------------------- +// Test the JSONRPC client + +func TestJSONStatus(t *testing.T) { + testStatus(t, "JSONRPC") +} + +func TestJSONGenPriv(t *testing.T) { + if testing.Short() { + t.Skip("skipping test in short mode.") + } + testGenPriv(t, "JSONRPC") +} + +func TestJSONGetAccount(t *testing.T) { + if testing.Short() { + t.Skip("skipping test in short mode.") + } + testGetAccount(t, "JSONRPC") +} + +func TestJSONSignedTx(t *testing.T) { + if testing.Short() { + t.Skip("skipping test in short mode.") + } + testSignedTx(t, "JSONRPC") +} + +func TestJSONBroadcastTx(t *testing.T) { + testBroadcastTx(t, "JSONRPC") +} + +func TestJSONGetStorage(t *testing.T) { + if testing.Short() { + t.Skip("skipping test in short mode.") + } + testGetStorage(t, "JSONRPC") +} + +func TestJSONCallCode(t *testing.T) { + if testing.Short() { + t.Skip("skipping test in short mode.") + } + testCallCode(t, "JSONRPC") +} + +func TestJSONCallContract(t *testing.T) { + if testing.Short() { + t.Skip("skipping test in short mode.") + } + testCall(t, "JSONRPC") +} + +func TestJSONNameReg(t *testing.T) { + if testing.Short() { + t.Skip("skipping test in short mode.") + } + testNameReg(t, "JSONRPC") +} diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/test/client_ws_test.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/test/client_ws_test.go new file mode 100644 index 0000000000000000000000000000000000000000..7d8575eb3751d2d9d41767d38fa364bdf31dc02f --- /dev/null +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/test/client_ws_test.go @@ -0,0 +1,212 @@ +package rpctest + +import ( + "fmt" + "testing" + + _ "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/config/tendermint_test" + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/types" +) + +var wsTyp = "JSONRPC" + +//-------------------------------------------------------------------------------- +// Test the websocket service + +// make a simple connection to the server +func TestWSConnect(t *testing.T) { + con := newWSCon(t) + con.Close() +} + +// receive a new block message +func TestWSNewBlock(t *testing.T) { + con := newWSCon(t) + eid := types.EventStringNewBlock() + subscribe(t, con, eid) + defer func() { + unsubscribe(t, con, eid) + con.Close() + }() + waitForEvent(t, con, eid, true, func() {}, func(eid string, b []byte) error { + fmt.Println("Check:", string(b)) + return nil + }) +} + +// receive a few new block messages in a row, with increasing height +func TestWSBlockchainGrowth(t *testing.T) { + if testing.Short() { + t.Skip("skipping test in short mode.") + } + con := newWSCon(t) + eid := types.EventStringNewBlock() + subscribe(t, con, eid) + defer func() { + unsubscribe(t, con, eid) + con.Close() + }() + // listen for NewBlock, ensure height increases by 1 + unmarshalValidateBlockchain(t, con, eid) +} + +// send a transaction and validate the events from listening for both sender and receiver +func TestWSSend(t *testing.T) { + toAddr := user[1].Address + amt := int64(100) + + con := newWSCon(t) + eidInput := types.EventStringAccInput(user[0].Address) + eidOutput := types.EventStringAccOutput(toAddr) + subscribe(t, con, eidInput) + subscribe(t, con, eidOutput) + defer func() { + unsubscribe(t, con, eidInput) + unsubscribe(t, con, eidOutput) + con.Close() + }() + waitForEvent(t, con, eidInput, true, func() { + tx := makeDefaultSendTxSigned(t, wsTyp, toAddr, amt) + broadcastTx(t, wsTyp, tx) + }, unmarshalValidateSend(amt, toAddr)) + waitForEvent(t, con, eidOutput, true, func() {}, unmarshalValidateSend(amt, toAddr)) +} + +// ensure events are only fired once for a given transaction +func TestWSDoubleFire(t *testing.T) { + if testing.Short() { + t.Skip("skipping test in short mode.") + } + con := newWSCon(t) + eid := types.EventStringAccInput(user[0].Address) + subscribe(t, con, eid) + defer func() { + unsubscribe(t, con, eid) + con.Close() + }() + amt := int64(100) + toAddr := user[1].Address + // broadcast the transaction, wait to hear about it + waitForEvent(t, con, eid, true, func() { + tx := makeDefaultSendTxSigned(t, wsTyp, toAddr, amt) + broadcastTx(t, wsTyp, tx) + }, func(eid string, b []byte) error { + return nil + }) + // but make sure we don't hear about it twice + waitForEvent(t, con, eid, false, func() { + }, func(eid string, b []byte) error { + return nil + }) +} + +// create a contract, wait for the event, and send it a msg, validate the return +func TestWSCallWait(t *testing.T) { + if testing.Short() { + t.Skip("skipping test in short mode.") + } + con := newWSCon(t) + eid1 := types.EventStringAccInput(user[0].Address) + subscribe(t, con, eid1) + defer func() { + unsubscribe(t, con, eid1) + con.Close() + }() + amt, gasLim, fee := int64(10000), int64(1000), int64(1000) + code, returnCode, returnVal := simpleContract() + var contractAddr []byte + // wait for the contract to be created + waitForEvent(t, con, eid1, true, func() { + tx := makeDefaultCallTx(t, wsTyp, nil, code, amt, gasLim, fee) + receipt := broadcastTx(t, wsTyp, tx) + contractAddr = receipt.ContractAddr + }, unmarshalValidateTx(amt, returnCode)) + + // susbscribe to the new contract + amt = int64(10001) + eid2 := types.EventStringAccOutput(contractAddr) + subscribe(t, con, eid2) + defer func() { + unsubscribe(t, con, eid2) + }() + // get the return value from a call + data := []byte{0x1} + waitForEvent(t, con, eid2, true, func() { + tx := makeDefaultCallTx(t, wsTyp, contractAddr, data, amt, gasLim, fee) + receipt := broadcastTx(t, wsTyp, tx) + contractAddr = receipt.ContractAddr + }, unmarshalValidateTx(amt, returnVal)) +} + +// create a contract and send it a msg without waiting. wait for contract event +// and validate return +func TestWSCallNoWait(t *testing.T) { + if testing.Short() { + t.Skip("skipping test in short mode.") + } + con := newWSCon(t) + amt, gasLim, fee := int64(10000), int64(1000), int64(1000) + code, _, returnVal := simpleContract() + + tx := makeDefaultCallTx(t, wsTyp, nil, code, amt, gasLim, fee) + receipt := broadcastTx(t, wsTyp, tx) + contractAddr := receipt.ContractAddr + + // susbscribe to the new contract + amt = int64(10001) + eid := types.EventStringAccOutput(contractAddr) + subscribe(t, con, eid) + defer func() { + unsubscribe(t, con, eid) + con.Close() + }() + // get the return value from a call + data := []byte{0x1} + waitForEvent(t, con, eid, true, func() { + tx := makeDefaultCallTx(t, wsTyp, contractAddr, data, amt, gasLim, fee) + broadcastTx(t, wsTyp, tx) + }, unmarshalValidateTx(amt, returnVal)) +} + +// create two contracts, one of which calls the other +func TestWSCallCall(t *testing.T) { + if testing.Short() { + t.Skip("skipping test in short mode.") + } + con := newWSCon(t) + amt, gasLim, fee := int64(10000), int64(1000), int64(1000) + code, _, returnVal := simpleContract() + txid := new([]byte) + + // deploy the two contracts + tx := makeDefaultCallTx(t, wsTyp, nil, code, amt, gasLim, fee) + receipt := broadcastTx(t, wsTyp, tx) + contractAddr1 := receipt.ContractAddr + + code, _, _ = simpleCallContract(contractAddr1) + tx = makeDefaultCallTx(t, wsTyp, nil, code, amt, gasLim, fee) + receipt = broadcastTx(t, wsTyp, tx) + contractAddr2 := receipt.ContractAddr + + // susbscribe to the new contracts + amt = int64(10001) + eid1 := types.EventStringAccCall(contractAddr1) + subscribe(t, con, eid1) + defer func() { + unsubscribe(t, con, eid1) + con.Close() + }() + // call contract2, which should call contract1, and wait for ev1 + + // let the contract get created first + waitForEvent(t, con, eid1, true, func() { + }, func(eid string, b []byte) error { + return nil + }) + // call it + waitForEvent(t, con, eid1, true, func() { + tx := makeDefaultCallTx(t, wsTyp, contractAddr2, nil, amt, gasLim, fee) + broadcastTx(t, wsTyp, tx) + *txid = types.TxID(chainID, tx) + }, unmarshalValidateCall(user[0].Address, returnVal, txid)) +} diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/test/config.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/test/config.go new file mode 100644 index 0000000000000000000000000000000000000000..51c8f87c4e3fd2102d771149eea48103b181b9e2 --- /dev/null +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/test/config.go @@ -0,0 +1,13 @@ +package rpctest + +import ( + cfg "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/config" +) + +var config cfg.Config = nil + +func init() { + cfg.OnConfig(func(newConfig cfg.Config) { + config = newConfig + }) +} diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/test/helpers.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/test/helpers.go new file mode 100644 index 0000000000000000000000000000000000000000..53c69a9bfcfc11625f90d71575fc7ded3b0bb014 --- /dev/null +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/test/helpers.go @@ -0,0 +1,282 @@ +package rpctest + +import ( + "bytes" + "strconv" + "testing" + + acm "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/account" + . "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/common" + nm "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/node" + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/p2p" + ctypes "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core/types" + cclient "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core_client" + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/types" +) + +// global variables for use across all tests +var ( + rpcAddr = "127.0.0.1:36657" // Not 46657 + requestAddr = "http://" + rpcAddr + "/" + websocketAddr = "ws://" + rpcAddr + "/websocket" + + node *nm.Node + + mempoolCount = 0 + + // make keys + user = makeUsers(5) + + chainID string + + clients = map[string]cclient.Client{ + "JSONRPC": cclient.NewClient(requestAddr, "JSONRPC"), + "HTTP": cclient.NewClient(requestAddr, "HTTP"), + } +) + +// deterministic account generation, synced with genesis file in config/tendermint_test/config.go +func makeUsers(n int) []*acm.PrivAccount { + accounts := []*acm.PrivAccount{} + for i := 0; i < n; i++ { + secret := ("mysecret" + strconv.Itoa(i)) + user := acm.GenPrivAccountFromSecret(secret) + accounts = append(accounts, user) + } + return accounts +} + +// create a new node and sleep forever +func newNode(ready chan struct{}) { + // Create & start node + node = nm.NewNode() + l := p2p.NewDefaultListener("tcp", config.GetString("node_laddr")) + node.AddListener(l) + node.Start() + + // Run the RPC server. + node.StartRPC() + ready <- struct{}{} + + // Sleep forever + ch := make(chan struct{}) + <-ch +} + +// initialize config and create new node +func init() { + chainID = config.GetString("chain_id") + + // Save new priv_validator file. + priv := &types.PrivValidator{ + Address: user[0].Address, + PubKey: acm.PubKeyEd25519(user[0].PubKey.(acm.PubKeyEd25519)), + PrivKey: acm.PrivKeyEd25519(user[0].PrivKey.(acm.PrivKeyEd25519)), + } + priv.SetFile(config.GetString("priv_validator_file")) + priv.Save() + + // TODO: change consensus/state.go timeouts to be shorter + + // start a node + ready := make(chan struct{}) + go newNode(ready) + <-ready +} + +//------------------------------------------------------------------------------- +// some default transaction functions + +func makeDefaultSendTx(t *testing.T, typ string, addr []byte, amt int64) *types.SendTx { + nonce := getNonce(t, typ, user[0].Address) + tx := types.NewSendTx() + tx.AddInputWithNonce(user[0].PubKey, amt, nonce+1) + tx.AddOutput(addr, amt) + return tx +} + +func makeDefaultSendTxSigned(t *testing.T, typ string, addr []byte, amt int64) *types.SendTx { + tx := makeDefaultSendTx(t, typ, addr, amt) + tx.SignInput(chainID, 0, user[0]) + return tx +} + +func makeDefaultCallTx(t *testing.T, typ string, addr, code []byte, amt, gasLim, fee int64) *types.CallTx { + nonce := getNonce(t, typ, user[0].Address) + tx := types.NewCallTxWithNonce(user[0].PubKey, addr, code, amt, gasLim, fee, nonce+1) + tx.Sign(chainID, user[0]) + return tx +} + +func makeDefaultNameTx(t *testing.T, typ string, name, value string, amt, fee int64) *types.NameTx { + nonce := getNonce(t, typ, user[0].Address) + tx := types.NewNameTxWithNonce(user[0].PubKey, name, value, amt, fee, nonce+1) + tx.Sign(chainID, user[0]) + return tx +} + +//------------------------------------------------------------------------------- +// rpc call wrappers (fail on err) + +// get an account's nonce +func getNonce(t *testing.T, typ string, addr []byte) int { + client := clients[typ] + ac, err := client.GetAccount(addr) + if err != nil { + t.Fatal(err) + } + if ac.Account == nil { + return 0 + } + return ac.Account.Sequence +} + +// get the account +func getAccount(t *testing.T, typ string, addr []byte) *acm.Account { + client := clients[typ] + ac, err := client.GetAccount(addr) + if err != nil { + t.Fatal(err) + } + return ac.Account +} + +// sign transaction +func signTx(t *testing.T, typ string, tx types.Tx, privAcc *acm.PrivAccount) types.Tx { + client := clients[typ] + signedTx, err := client.SignTx(tx, []*acm.PrivAccount{privAcc}) + if err != nil { + t.Fatal(err) + } + return signedTx.Tx +} + +// broadcast transaction +func broadcastTx(t *testing.T, typ string, tx types.Tx) ctypes.Receipt { + client := clients[typ] + rec, err := client.BroadcastTx(tx) + if err != nil { + t.Fatal(err) + } + mempoolCount += 1 + return rec.Receipt +} + +// dump all storage for an account. currently unused +func dumpStorage(t *testing.T, addr []byte) ctypes.ResultDumpStorage { + client := clients["HTTP"] + resp, err := client.DumpStorage(addr) + if err != nil { + t.Fatal(err) + } + return *resp +} + +func getStorage(t *testing.T, typ string, addr, key []byte) []byte { + client := clients[typ] + resp, err := client.GetStorage(addr, key) + if err != nil { + t.Fatal(err) + } + return resp.Value +} + +func callCode(t *testing.T, client cclient.Client, fromAddress, code, data, expected []byte) { + resp, err := client.CallCode(fromAddress, code, data) + if err != nil { + t.Fatal(err) + } + ret := resp.Return + // NOTE: we don't flip memory when it comes out of RETURN (?!) + if bytes.Compare(ret, LeftPadWord256(expected).Bytes()) != 0 { + t.Fatalf("Conflicting return value. Got %x, expected %x", ret, expected) + } +} + +func callContract(t *testing.T, client cclient.Client, fromAddress, toAddress, data, expected []byte) { + resp, err := client.Call(fromAddress, toAddress, data) + if err != nil { + t.Fatal(err) + } + ret := resp.Return + // NOTE: we don't flip memory when it comes out of RETURN (?!) + if bytes.Compare(ret, LeftPadWord256(expected).Bytes()) != 0 { + t.Fatalf("Conflicting return value. Got %x, expected %x", ret, expected) + } +} + +// get the namereg entry +func getNameRegEntry(t *testing.T, typ string, name string) *types.NameRegEntry { + client := clients[typ] + entry, err := client.GetName(name) + if err != nil { + t.Fatal(err) + } + return entry.Entry +} + +//-------------------------------------------------------------------------------- +// utility verification function + +func checkTx(t *testing.T, fromAddr []byte, priv *acm.PrivAccount, tx *types.SendTx) { + if bytes.Compare(tx.Inputs[0].Address, fromAddr) != 0 { + t.Fatal("Tx input addresses don't match!") + } + + signBytes := acm.SignBytes(chainID, tx) + in := tx.Inputs[0] //(*types.SendTx).Inputs[0] + + if err := in.ValidateBasic(); err != nil { + t.Fatal(err) + } + // Check signatures + // acc := getAccount(t, byteAddr) + // NOTE: using the acc here instead of the in fails; it is nil. + if !in.PubKey.VerifyBytes(signBytes, in.Signature) { + t.Fatal(types.ErrTxInvalidSignature) + } +} + +// simple contract returns 5 + 6 = 0xb +func simpleContract() ([]byte, []byte, []byte) { + // this is the code we want to run when the contract is called + contractCode := []byte{0x60, 0x5, 0x60, 0x6, 0x1, 0x60, 0x0, 0x52, 0x60, 0x20, 0x60, 0x0, 0xf3} + // the is the code we need to return the contractCode when the contract is initialized + lenCode := len(contractCode) + // push code to the stack + //code := append([]byte{byte(0x60 + lenCode - 1)}, RightPadWord256(contractCode).Bytes()...) + code := append([]byte{0x7f}, RightPadWord256(contractCode).Bytes()...) + // store it in memory + code = append(code, []byte{0x60, 0x0, 0x52}...) + // return whats in memory + //code = append(code, []byte{0x60, byte(32 - lenCode), 0x60, byte(lenCode), 0xf3}...) + code = append(code, []byte{0x60, byte(lenCode), 0x60, 0x0, 0xf3}...) + // return init code, contract code, expected return + return code, contractCode, LeftPadBytes([]byte{0xb}, 32) +} + +// simple call contract calls another contract +func simpleCallContract(addr []byte) ([]byte, []byte, []byte) { + gas1, gas2 := byte(0x1), byte(0x1) + value := byte(0x1) + inOff, inSize := byte(0x0), byte(0x0) // no call data + retOff, retSize := byte(0x0), byte(0x20) + // this is the code we want to run (call a contract and return) + contractCode := []byte{0x60, retSize, 0x60, retOff, 0x60, inSize, 0x60, inOff, 0x60, value, 0x73} + contractCode = append(contractCode, addr...) + contractCode = append(contractCode, []byte{0x61, gas1, gas2, 0xf1, 0x60, 0x20, 0x60, 0x0, 0xf3}...) + + // the is the code we need to return; the contractCode when the contract is initialized + // it should copy the code from the input into memory + lenCode := len(contractCode) + memOff := byte(0x0) + inOff = byte(0xc) // length of code before codeContract + length := byte(lenCode) + + code := []byte{0x60, length, 0x60, inOff, 0x60, memOff, 0x37} + // return whats in memory + code = append(code, []byte{0x60, byte(lenCode), 0x60, 0x0, 0xf3}...) + code = append(code, contractCode...) + // return init code, contract code, expected return + return code, contractCode, LeftPadBytes([]byte{0xb}, 32) +} diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/test/tests.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/test/tests.go new file mode 100644 index 0000000000000000000000000000000000000000..f08bc6db349e138a49cea2e428fbad6388b00df9 --- /dev/null +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/test/tests.go @@ -0,0 +1,281 @@ +package rpctest + +import ( + "bytes" + "fmt" + . "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/common" + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/types" + "testing" +) + +var doNothing = func(eid string, b []byte) error { return nil } + +func testStatus(t *testing.T, typ string) { + client := clients[typ] + resp, err := client.Status() + if err != nil { + t.Fatal(err) + } + if resp.NodeInfo.ChainID != chainID { + t.Fatal(fmt.Errorf("ChainID mismatch: got %s expected %s", + resp.NodeInfo.ChainID, chainID)) + } +} + +func testGenPriv(t *testing.T, typ string) { + client := clients[typ] + privAcc, err := client.GenPrivAccount() + if err != nil { + t.Fatal(err) + } + if len(privAcc.PrivAccount.Address) == 0 { + t.Fatal("Failed to generate an address") + } +} + +func testGetAccount(t *testing.T, typ string) { + acc := getAccount(t, typ, user[0].Address) + if acc == nil { + t.Fatalf("Account was nil") + } + if bytes.Compare(acc.Address, user[0].Address) != 0 { + t.Fatalf("Failed to get correct account. Got %x, expected %x", acc.Address, user[0].Address) + } +} + +func testSignedTx(t *testing.T, typ string) { + amt := int64(100) + toAddr := user[1].Address + testOneSignTx(t, typ, toAddr, amt) + + toAddr = user[2].Address + testOneSignTx(t, typ, toAddr, amt) + + toAddr = user[3].Address + testOneSignTx(t, typ, toAddr, amt) +} + +func testOneSignTx(t *testing.T, typ string, addr []byte, amt int64) { + tx := makeDefaultSendTx(t, typ, addr, amt) + tx2 := signTx(t, typ, tx, user[0]) + tx2hash := types.TxID(chainID, tx2) + tx.SignInput(chainID, 0, user[0]) + txhash := types.TxID(chainID, tx) + if bytes.Compare(txhash, tx2hash) != 0 { + t.Fatal("Got different signatures for signing via rpc vs tx_utils") + } + + tx_ := signTx(t, typ, tx, user[0]) + tx = tx_.(*types.SendTx) + checkTx(t, user[0].Address, user[0], tx) +} + +func testBroadcastTx(t *testing.T, typ string) { + amt := int64(100) + toAddr := user[1].Address + tx := makeDefaultSendTxSigned(t, typ, toAddr, amt) + receipt := broadcastTx(t, typ, tx) + if receipt.CreatesContract > 0 { + t.Fatal("This tx does not create a contract") + } + if len(receipt.TxHash) == 0 { + t.Fatal("Failed to compute tx hash") + } + pool := node.MempoolReactor().Mempool + txs := pool.GetProposalTxs() + if len(txs) != mempoolCount { + t.Fatalf("The mem pool has %d txs. Expected %d", len(txs), mempoolCount) + } + tx2 := txs[mempoolCount-1].(*types.SendTx) + n, err := new(int64), new(error) + buf1, buf2 := new(bytes.Buffer), new(bytes.Buffer) + tx.WriteSignBytes(chainID, buf1, n, err) + tx2.WriteSignBytes(chainID, buf2, n, err) + if bytes.Compare(buf1.Bytes(), buf2.Bytes()) != 0 { + t.Fatal("inconsistent hashes for mempool tx and sent tx") + } +} + +func testGetStorage(t *testing.T, typ string) { + con := newWSCon(t) + eid := types.EventStringNewBlock() + subscribe(t, con, eid) + defer func() { + unsubscribe(t, con, eid) + con.Close() + }() + + amt, gasLim, fee := int64(1100), int64(1000), int64(1000) + code := []byte{0x60, 0x5, 0x60, 0x1, 0x55} + tx := makeDefaultCallTx(t, typ, nil, code, amt, gasLim, fee) + receipt := broadcastTx(t, typ, tx) + if receipt.CreatesContract == 0 { + t.Fatal("This tx creates a contract") + } + if len(receipt.TxHash) == 0 { + t.Fatal("Failed to compute tx hash") + } + contractAddr := receipt.ContractAddr + if len(contractAddr) == 0 { + t.Fatal("Creates contract but resulting address is empty") + } + + // allow it to get mined + waitForEvent(t, con, eid, true, func() {}, doNothing) + mempoolCount = 0 + + v := getStorage(t, typ, contractAddr, []byte{0x1}) + got := LeftPadWord256(v) + expected := LeftPadWord256([]byte{0x5}) + if got.Compare(expected) != 0 { + t.Fatalf("Wrong storage value. Got %x, expected %x", got.Bytes(), expected.Bytes()) + } +} + +func testCallCode(t *testing.T, typ string) { + client := clients[typ] + + // add two integers and return the result + code := []byte{0x60, 0x5, 0x60, 0x6, 0x1, 0x60, 0x0, 0x52, 0x60, 0x20, 0x60, 0x0, 0xf3} + data := []byte{} + expected := []byte{0xb} + callCode(t, client, user[0].PubKey.Address(), code, data, expected) + + // pass two ints as calldata, add, and return the result + code = []byte{0x60, 0x0, 0x35, 0x60, 0x20, 0x35, 0x1, 0x60, 0x0, 0x52, 0x60, 0x20, 0x60, 0x0, 0xf3} + data = append(LeftPadWord256([]byte{0x5}).Bytes(), LeftPadWord256([]byte{0x6}).Bytes()...) + expected = []byte{0xb} + callCode(t, client, user[0].PubKey.Address(), code, data, expected) +} + +func testCall(t *testing.T, typ string) { + con := newWSCon(t) + eid := types.EventStringNewBlock() + subscribe(t, con, eid) + defer func() { + unsubscribe(t, con, eid) + con.Close() + }() + + client := clients[typ] + + // create the contract + amt, gasLim, fee := int64(6969), int64(1000), int64(1000) + code, _, _ := simpleContract() + tx := makeDefaultCallTx(t, typ, nil, code, amt, gasLim, fee) + receipt := broadcastTx(t, typ, tx) + + if receipt.CreatesContract == 0 { + t.Fatal("This tx creates a contract") + } + if len(receipt.TxHash) == 0 { + t.Fatal("Failed to compute tx hash") + } + contractAddr := receipt.ContractAddr + if len(contractAddr) == 0 { + t.Fatal("Creates contract but resulting address is empty") + } + + // allow it to get mined + waitForEvent(t, con, eid, true, func() {}, doNothing) + mempoolCount = 0 + + // run a call through the contract + data := []byte{} + expected := []byte{0xb} + callContract(t, client, user[0].PubKey.Address(), contractAddr, data, expected) +} + +func testNameReg(t *testing.T, typ string) { + client := clients[typ] + con := newWSCon(t) + + types.MinNameRegistrationPeriod = 1 + + // register a new name, check if its there + // since entries ought to be unique and these run against different clients, we append the typ + name := "ye_old_domain_name_" + typ + data := "if not now, when" + fee := int64(1000) + numDesiredBlocks := int64(2) + amt := fee + numDesiredBlocks*types.NameByteCostMultiplier*types.NameBlockCostMultiplier*types.NameBaseCost(name, data) + + eid := types.EventStringNameReg(name) + subscribe(t, con, eid) + + tx := makeDefaultNameTx(t, typ, name, data, amt, fee) + broadcastTx(t, typ, tx) + // verify the name by both using the event and by checking get_name + waitForEvent(t, con, eid, true, func() {}, func(eid string, b []byte) error { + // TODO: unmarshal the response + tx, err := unmarshalResponseNameReg(b) + if err != nil { + return err + } + if tx.Name != name { + t.Fatal(fmt.Sprintf("Err on received event tx.Name: Got %s, expected %s", tx.Name, name)) + } + if tx.Data != data { + t.Fatal(fmt.Sprintf("Err on received event tx.Data: Got %s, expected %s", tx.Data, data)) + } + return nil + }) + mempoolCount = 0 + entry := getNameRegEntry(t, typ, name) + if entry.Data != data { + t.Fatal(fmt.Sprintf("Err on entry.Data: Got %s, expected %s", entry.Data, data)) + } + if bytes.Compare(entry.Owner, user[0].Address) != 0 { + t.Fatal(fmt.Sprintf("Err on entry.Owner: Got %s, expected %s", entry.Owner, user[0].Address)) + } + + unsubscribe(t, con, eid) + + // for the rest we just use new block event + // since we already tested the namereg event + eid = types.EventStringNewBlock() + subscribe(t, con, eid) + defer func() { + unsubscribe(t, con, eid) + con.Close() + }() + + // update the data as the owner, make sure still there + numDesiredBlocks = int64(2) + data = "these are amongst the things I wish to bestow upon the youth of generations come: a safe supply of honey, and a better money. For what else shall they need" + amt = fee + numDesiredBlocks*types.NameByteCostMultiplier*types.NameBlockCostMultiplier*types.NameBaseCost(name, data) + tx = makeDefaultNameTx(t, typ, name, data, amt, fee) + broadcastTx(t, typ, tx) + // commit block + waitForEvent(t, con, eid, true, func() {}, doNothing) + mempoolCount = 0 + entry = getNameRegEntry(t, typ, name) + if entry.Data != data { + t.Fatal(fmt.Sprintf("Err on entry.Data: Got %s, expected %s", entry.Data, data)) + } + + // try to update as non owner, should fail + nonce := getNonce(t, typ, user[1].Address) + data2 := "this is not my beautiful house" + tx = types.NewNameTxWithNonce(user[1].PubKey, name, data2, amt, fee, nonce+1) + tx.Sign(chainID, user[1]) + _, err := client.BroadcastTx(tx) + if err == nil { + t.Fatal("Expected error on NameTx") + } + + // commit block + waitForEvent(t, con, eid, true, func() {}, doNothing) + + // now the entry should be expired, so we can update as non owner + _, err = client.BroadcastTx(tx) + waitForEvent(t, con, eid, true, func() {}, doNothing) + mempoolCount = 0 + entry = getNameRegEntry(t, typ, name) + if entry.Data != data2 { + t.Fatal(fmt.Sprintf("Error on entry.Data: Got %s, expected %s", entry.Data, data2)) + } + if bytes.Compare(entry.Owner, user[1].Address) != 0 { + t.Fatal(fmt.Sprintf("Err on entry.Owner: Got %s, expected %s", entry.Owner, user[1].Address)) + } +} diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/test/ws_helpers.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/test/ws_helpers.go new file mode 100644 index 0000000000000000000000000000000000000000..fce8b1332b40cb1891dbde38ad84a32cd0196c09 --- /dev/null +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/test/ws_helpers.go @@ -0,0 +1,271 @@ +package rpctest + +import ( + "bytes" + "fmt" + "net/http" + "testing" + "time" + + _ "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/config/tendermint_test" + ctypes "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core/types" + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/types" + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/types" + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/wire" + "github.com/gorilla/websocket" +) + +//-------------------------------------------------------------------------------- +// Utilities for testing the websocket service + +// create a new connection +func newWSCon(t *testing.T) *websocket.Conn { + dialer := websocket.DefaultDialer + rHeader := http.Header{} + con, r, err := dialer.Dial(websocketAddr, rHeader) + fmt.Println("response", r) + if err != nil { + t.Fatal(err) + } + return con +} + +// subscribe to an event +func subscribe(t *testing.T, con *websocket.Conn, eventid string) { + err := con.WriteJSON(rpctypes.RPCRequest{ + JSONRPC: "2.0", + ID: "", + Method: "subscribe", + Params: []interface{}{eventid}, + }) + if err != nil { + t.Fatal(err) + } +} + +// unsubscribe from an event +func unsubscribe(t *testing.T, con *websocket.Conn, eventid string) { + err := con.WriteJSON(rpctypes.RPCRequest{ + JSONRPC: "2.0", + ID: "", + Method: "unsubscribe", + Params: []interface{}{eventid}, + }) + if err != nil { + t.Fatal(err) + } +} + +// wait for an event; do things that might trigger events, and check them when they are received +// the check function takes an event id and the byte slice read off the ws +func waitForEvent(t *testing.T, con *websocket.Conn, eventid string, dieOnTimeout bool, f func(), check func(string, []byte) error) { + // go routine to wait for webscoket msg + goodCh := make(chan []byte) + errCh := make(chan error) + quitCh := make(chan struct{}) + defer close(quitCh) + + // Read message + go func() { + for { + _, p, err := con.ReadMessage() + if err != nil { + errCh <- err + break + } else { + // if the event id isnt what we're waiting on + // ignore it + var response ctypes.Response + var err error + wire.ReadJSON(&response, p, &err) + if err != nil { + errCh <- err + break + } + event, ok := response.Result.(*ctypes.ResultEvent) + if ok && event.Event == eventid { + goodCh <- p + break + } + } + } + }() + + // do stuff (transactions) + f() + + // wait for an event or timeout + timeout := time.NewTimer(10 * time.Second) + select { + case <-timeout.C: + if dieOnTimeout { + con.Close() + t.Fatalf("%s event was not received in time", eventid) + } + // else that's great, we didn't hear the event + // and we shouldn't have + case p := <-goodCh: + if dieOnTimeout { + // message was received and expected + // run the check + err := check(eventid, p) + if err != nil { + t.Fatal(err) + panic(err) // Show the stack trace. + } + } else { + con.Close() + t.Fatalf("%s event was not expected", eventid) + } + case err := <-errCh: + t.Fatal(err) + panic(err) // Show the stack trace. + } +} + +//-------------------------------------------------------------------------------- + +func unmarshalResponseNewBlock(b []byte) (*types.Block, error) { + // unmarshall and assert somethings + var response ctypes.Response + var err error + wire.ReadJSON(&response, b, &err) + if err != nil { + return nil, err + } + if response.Error != "" { + return nil, fmt.Errorf(response.Error) + } + block := response.Result.(*ctypes.ResultEvent).Data.(types.EventDataNewBlock).Block + return block, nil +} + +func unmarshalResponseNameReg(b []byte) (*types.NameTx, error) { + // unmarshall and assert somethings + var response ctypes.Response + var err error + wire.ReadJSON(&response, b, &err) + if err != nil { + return nil, err + } + if response.Error != "" { + return nil, fmt.Errorf(response.Error) + } + tx := response.Result.(*ctypes.ResultEvent).Data.(types.EventDataTx).Tx.(*types.NameTx) + return tx, nil +} + +func unmarshalValidateBlockchain(t *testing.T, con *websocket.Conn, eid string) { + var initBlockN int + for i := 0; i < 2; i++ { + waitForEvent(t, con, eid, true, func() {}, func(eid string, b []byte) error { + block, err := unmarshalResponseNewBlock(b) + if err != nil { + return err + } + if i == 0 { + initBlockN = block.Header.Height + } else { + if block.Header.Height != initBlockN+i { + return fmt.Errorf("Expected block %d, got block %d", i, block.Header.Height) + } + } + + return nil + }) + } +} + +func unmarshalValidateSend(amt int64, toAddr []byte) func(string, []byte) error { + return func(eid string, b []byte) error { + // unmarshal and assert correctness + var response ctypes.Response + var err error + wire.ReadJSON(&response, b, &err) + if err != nil { + return err + } + if response.Error != "" { + return fmt.Errorf(response.Error) + } + if eid != response.Result.(*ctypes.ResultEvent).Event { + return fmt.Errorf("Eventid is not correct. Got %s, expected %s", response.Result.(*ctypes.ResultEvent).Event, eid) + } + tx := response.Result.(*ctypes.ResultEvent).Data.(types.EventDataTx).Tx.(*types.SendTx) + if !bytes.Equal(tx.Inputs[0].Address, user[0].Address) { + return fmt.Errorf("Senders do not match up! Got %x, expected %x", tx.Inputs[0].Address, user[0].Address) + } + if tx.Inputs[0].Amount != amt { + return fmt.Errorf("Amt does not match up! Got %d, expected %d", tx.Inputs[0].Amount, amt) + } + if !bytes.Equal(tx.Outputs[0].Address, toAddr) { + return fmt.Errorf("Receivers do not match up! Got %x, expected %x", tx.Outputs[0].Address, user[0].Address) + } + return nil + } +} + +func unmarshalValidateTx(amt int64, returnCode []byte) func(string, []byte) error { + return func(eid string, b []byte) error { + // unmarshall and assert somethings + var response ctypes.Response + var err error + wire.ReadJSON(&response, b, &err) + if err != nil { + return err + } + if response.Error != "" { + return fmt.Errorf(response.Error) + } + var data = response.Result.(*ctypes.ResultEvent).Data.(types.EventDataTx) + if data.Exception != "" { + return fmt.Errorf(data.Exception) + } + tx := data.Tx.(*types.CallTx) + if !bytes.Equal(tx.Input.Address, user[0].Address) { + return fmt.Errorf("Senders do not match up! Got %x, expected %x", + tx.Input.Address, user[0].Address) + } + if tx.Input.Amount != amt { + return fmt.Errorf("Amt does not match up! Got %d, expected %d", + tx.Input.Amount, amt) + } + ret := data.Return + if !bytes.Equal(ret, returnCode) { + return fmt.Errorf("Tx did not return correctly. Got %x, expected %x", ret, returnCode) + } + return nil + } +} + +func unmarshalValidateCall(origin, returnCode []byte, txid *[]byte) func(string, []byte) error { + return func(eid string, b []byte) error { + // unmarshall and assert somethings + var response ctypes.Response + var err error + wire.ReadJSON(&response, b, &err) + if err != nil { + return err + } + if response.Error != "" { + return fmt.Errorf(response.Error) + } + var data = response.Result.(*ctypes.ResultEvent).Data.(types.EventDataCall) + if data.Exception != "" { + return fmt.Errorf(data.Exception) + } + if !bytes.Equal(data.Origin, origin) { + return fmt.Errorf("Origin does not match up! Got %x, expected %x", + data.Origin, origin) + } + ret := data.Return + if !bytes.Equal(ret, returnCode) { + return fmt.Errorf("Call did not return correctly. Got %x, expected %x", ret, returnCode) + } + if !bytes.Equal(data.TxID, *txid) { + return fmt.Errorf("TxIDs do not match up! Got %x, expected %x", + data.TxID, *txid) + } + return nil + } +} diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/types/types.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/types/types.go index 47cea1c570986becc3eae3d7bc83a69389da2208..c93e6735babf6137032a1dfad8fe0d2e2e8fe19b 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/types/types.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/types/types.go @@ -2,32 +2,23 @@ package rpctypes type RPCRequest struct { JSONRPC string `json:"jsonrpc"` - Id string `json:"id"` + ID string `json:"id"` Method string `json:"method"` Params []interface{} `json:"params"` } type RPCResponse struct { JSONRPC string `json:"jsonrpc"` - Id string `json:"id"` + ID string `json:"id"` Result interface{} `json:"result"` Error string `json:"error"` } func NewRPCResponse(id string, res interface{}, err string) RPCResponse { - if res == nil { - res = struct{}{} - } return RPCResponse{ JSONRPC: "2.0", - Id: id, + ID: id, Result: res, Error: err, } } - -// Goes in the Result field of an RPCResponse. -type RPCEventResult struct { - Event string `json:"event"` - Data interface{} `json:"data"` -} diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/version.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/version.go new file mode 100644 index 0000000000000000000000000000000000000000..2982824dd963c5f1af0083f7990bf8af471d2588 --- /dev/null +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/version.go @@ -0,0 +1,3 @@ +package rpc + +const Version = "0.4.0" diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/state/execution.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/state/execution.go index 5a1e587a81338069de386acb22014e0aa156c997..bf9b0558dc6f7a110f87eed2fd6933491f0df96e 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/state/execution.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/state/execution.go @@ -101,8 +101,8 @@ func execBlock(s *State, block *types.Block, blockPartsHeader types.PartSetHeade // If any unbonding periods are over, // reward account with bonded coins. - toRelease := []*Validator{} - s.UnbondingValidators.Iterate(func(index int, val *Validator) bool { + toRelease := []*types.Validator{} + s.UnbondingValidators.Iterate(func(index int, val *types.Validator) bool { if val.UnbondHeight+unbondingPeriodBlocks < block.Height { toRelease = append(toRelease, val) } @@ -114,8 +114,8 @@ func execBlock(s *State, block *types.Block, blockPartsHeader types.PartSetHeade // If any validators haven't signed in a while, // unbond them, they have timed out. - toTimeout := []*Validator{} - s.BondedValidators.Iterate(func(index int, val *Validator) bool { + toTimeout := []*types.Validator{} + s.BondedValidators.Iterate(func(index int, val *types.Validator) bool { lastActivityHeight := MaxInt(val.BondHeight, val.LastCommitHeight) if lastActivityHeight+validatorTimeoutBlocks < block.Height { log.Notice("Validator timeout", "validator", val, "height", block.Height) @@ -337,11 +337,11 @@ func ExecTx(blockCache *BlockCache, tx types.Tx, runCall bool, evc events.Fireab // if the evc is nil, nothing will happen if evc != nil { for _, i := range tx.Inputs { - evc.FireEvent(types.EventStringAccInput(i.Address), tx) + evc.FireEvent(types.EventStringAccInput(i.Address), types.EventDataTx{tx, nil, ""}) } for _, o := range tx.Outputs { - evc.FireEvent(types.EventStringAccOutput(o.Address), tx) + evc.FireEvent(types.EventStringAccOutput(o.Address), types.EventDataTx{tx, nil, ""}) } } return nil @@ -494,8 +494,8 @@ func ExecTx(blockCache *BlockCache, tx types.Tx, runCall bool, evc events.Fireab if err != nil { exception = err.Error() } - evc.FireEvent(types.EventStringAccInput(tx.Input.Address), types.EventMsgCallTx{tx, ret, exception}) - evc.FireEvent(types.EventStringAccOutput(tx.Address), types.EventMsgCallTx{tx, ret, exception}) + evc.FireEvent(types.EventStringAccInput(tx.Input.Address), types.EventDataTx{tx, ret, exception}) + evc.FireEvent(types.EventStringAccOutput(tx.Address), types.EventDataTx{tx, ret, exception}) } } else { // The mempool does not call txs until @@ -543,14 +543,13 @@ func ExecTx(blockCache *BlockCache, tx types.Tx, runCall bool, evc events.Fireab // validate the input strings if err := tx.ValidateStrings(); err != nil { - log.Info(err.Error()) - return types.ErrTxInvalidString + return err } value := tx.Input.Amount - tx.Fee // let's say cost of a name for one block is len(data) + 32 - costPerBlock := types.NameCostPerBlock * types.NameCostPerByte * tx.BaseEntryCost() + costPerBlock := types.NameCostPerBlock(types.NameBaseCost(tx.Name, tx.Data)) expiresIn := int(value / costPerBlock) lastBlockHeight := _s.LastBlockHeight @@ -591,7 +590,7 @@ func ExecTx(blockCache *BlockCache, tx types.Tx, runCall bool, evc events.Fireab } else { // since the size of the data may have changed // we use the total amount of "credit" - oldCredit := int64(entry.Expires-lastBlockHeight) * types.BaseEntryCost(entry.Name, entry.Data) + oldCredit := int64(entry.Expires-lastBlockHeight) * types.NameBaseCost(entry.Name, entry.Data) credit := oldCredit + value expiresIn = int(credit / costPerBlock) if expiresIn < types.MinNameRegistrationPeriod { @@ -627,6 +626,11 @@ func ExecTx(blockCache *BlockCache, tx types.Tx, runCall bool, evc events.Fireab // TODO: maybe we want to take funds on error and allow txs in that don't do anythingi? + if evc != nil { + evc.FireEvent(types.EventStringAccInput(tx.Input.Address), types.EventDataTx{tx, nil, ""}) + evc.FireEvent(types.EventStringNameReg(tx.Name), types.EventDataTx{tx, nil, ""}) + } + return nil case *types.BondTx: @@ -686,7 +690,7 @@ func ExecTx(blockCache *BlockCache, tx types.Tx, runCall bool, evc events.Fireab blockCache.UpdateAccount(acc) } // Add ValidatorInfo - _s.SetValidatorInfo(&ValidatorInfo{ + _s.SetValidatorInfo(&types.ValidatorInfo{ Address: tx.PubKey.Address(), PubKey: tx.PubKey, UnbondTo: tx.UnbondTo, @@ -694,7 +698,7 @@ func ExecTx(blockCache *BlockCache, tx types.Tx, runCall bool, evc events.Fireab FirstBondAmount: outTotal, }) // Add Validator - added := _s.BondedValidators.Add(&Validator{ + added := _s.BondedValidators.Add(&types.Validator{ Address: tx.PubKey.Address(), PubKey: tx.PubKey, BondHeight: _s.LastBlockHeight + 1, @@ -706,7 +710,7 @@ func ExecTx(blockCache *BlockCache, tx types.Tx, runCall bool, evc events.Fireab } if evc != nil { // TODO: fire for all inputs - evc.FireEvent(types.EventStringBond(), tx) + evc.FireEvent(types.EventStringBond(), types.EventDataTx{tx, nil, ""}) } return nil @@ -731,7 +735,7 @@ func ExecTx(blockCache *BlockCache, tx types.Tx, runCall bool, evc events.Fireab // Good! _s.unbondValidator(val) if evc != nil { - evc.FireEvent(types.EventStringUnbond(), tx) + evc.FireEvent(types.EventStringUnbond(), types.EventDataTx{tx, nil, ""}) } return nil @@ -759,7 +763,7 @@ func ExecTx(blockCache *BlockCache, tx types.Tx, runCall bool, evc events.Fireab // Good! _s.rebondValidator(val) if evc != nil { - evc.FireEvent(types.EventStringRebond(), tx) + evc.FireEvent(types.EventStringRebond(), types.EventDataTx{tx, nil, ""}) } return nil @@ -798,7 +802,7 @@ func ExecTx(blockCache *BlockCache, tx types.Tx, runCall bool, evc events.Fireab // Good! (Bad validator!) _s.destroyValidator(accused) if evc != nil { - evc.FireEvent(types.EventStringDupeout(), tx) + evc.FireEvent(types.EventStringDupeout(), types.EventDataTx{tx, nil, ""}) } return nil @@ -888,8 +892,8 @@ func ExecTx(blockCache *BlockCache, tx types.Tx, runCall bool, evc events.Fireab } if evc != nil { - evc.FireEvent(types.EventStringAccInput(tx.Input.Address), tx) - evc.FireEvent(types.EventStringPermissions(ptypes.PermFlagToString(permFlag)), tx) + evc.FireEvent(types.EventStringAccInput(tx.Input.Address), types.EventDataTx{tx, nil, ""}) + evc.FireEvent(types.EventStringPermissions(ptypes.PermFlagToString(permFlag)), types.EventDataTx{tx, nil, ""}) } return nil @@ -976,3 +980,14 @@ func hasBondOrSendPermission(state AccountGetter, accs map[string]*acm.Account) } return true } + +//----------------------------------------------------------------------------- + +type InvalidTxError struct { + Tx types.Tx + Reason error +} + +func (txErr InvalidTxError) Error() string { + return Fmt("Invalid tx: [%v] reason: [%v]", txErr.Tx, txErr.Reason) +} diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/state/genesis.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/state/genesis.go deleted file mode 100644 index e150754c4a4e3e69287f9b4475527e3f9ef76cb4..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/state/genesis.go +++ /dev/null @@ -1,178 +0,0 @@ -package state - -import ( - "io/ioutil" - "os" - "time" - - acm "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/account" - . "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/common" - dbm "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/db" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/merkle" - ptypes "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/permission/types" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/types" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/wire" -) - -//------------------------------------------------------------ -// we store the gendoc in the db - -var GenDocKey = []byte("GenDocKey") - -//------------------------------------------------------------ -// core types for a genesis definition - -type BasicAccount struct { - Address []byte `json:"address"` - Amount int64 `json:"amount"` -} - -type GenesisAccount struct { - Address []byte `json:"address"` - Amount int64 `json:"amount"` - Name string `json:"name"` - Permissions *ptypes.AccountPermissions `json:"permissions"` -} - -type GenesisValidator struct { - PubKey acm.PubKeyEd25519 `json:"pub_key"` - Amount int64 `json:"amount"` - Name string `json:"name"` - UnbondTo []BasicAccount `json:"unbond_to"` -} - -type GenesisParams struct { - GlobalPermissions *ptypes.AccountPermissions `json:"global_permissions"` -} - -type GenesisDoc struct { - GenesisTime time.Time `json:"genesis_time"` - ChainID string `json:"chain_id"` - Params *GenesisParams `json:"params"` - Accounts []GenesisAccount `json:"accounts"` - Validators []GenesisValidator `json:"validators"` -} - -//------------------------------------------------------------ -// Make genesis state from file - -func GenesisDocFromJSON(jsonBlob []byte) (genState *GenesisDoc) { - var err error - wire.ReadJSONPtr(&genState, jsonBlob, &err) - if err != nil { - log.Error(Fmt("Couldn't read GenesisDoc: %v", err)) - os.Exit(1) - } - return -} - -func MakeGenesisStateFromFile(db dbm.DB, genDocFile string) (*GenesisDoc, *State) { - jsonBlob, err := ioutil.ReadFile(genDocFile) - if err != nil { - log.Error(Fmt("Couldn't read GenesisDoc file: %v", err)) - os.Exit(1) - } - genDoc := GenesisDocFromJSON(jsonBlob) - return genDoc, MakeGenesisState(db, genDoc) -} - -func MakeGenesisState(db dbm.DB, genDoc *GenesisDoc) *State { - if len(genDoc.Validators) == 0 { - Exit(Fmt("The genesis file has no validators")) - } - - if genDoc.GenesisTime.IsZero() { - genDoc.GenesisTime = time.Now() - } - - // Make accounts state tree - accounts := merkle.NewIAVLTree(wire.BasicCodec, acm.AccountCodec, defaultAccountsCacheCapacity, db) - for _, genAcc := range genDoc.Accounts { - perm := ptypes.ZeroAccountPermissions - if genAcc.Permissions != nil { - perm = *genAcc.Permissions - } - acc := &acm.Account{ - Address: genAcc.Address, - PubKey: nil, - Sequence: 0, - Balance: genAcc.Amount, - Permissions: perm, - } - accounts.Set(acc.Address, acc) - } - - // global permissions are saved as the 0 address - // so they are included in the accounts tree - globalPerms := ptypes.DefaultAccountPermissions - if genDoc.Params != nil && genDoc.Params.GlobalPermissions != nil { - globalPerms = *genDoc.Params.GlobalPermissions - // XXX: make sure the set bits are all true - // Without it the HasPermission() functions will fail - globalPerms.Base.SetBit = ptypes.AllPermFlags - } - - permsAcc := &acm.Account{ - Address: ptypes.GlobalPermissionsAddress, - PubKey: nil, - Sequence: 0, - Balance: 1337, - Permissions: globalPerms, - } - accounts.Set(permsAcc.Address, permsAcc) - - // Make validatorInfos state tree && validators slice - validatorInfos := merkle.NewIAVLTree(wire.BasicCodec, ValidatorInfoCodec, 0, db) - validators := make([]*Validator, len(genDoc.Validators)) - for i, val := range genDoc.Validators { - pubKey := val.PubKey - address := pubKey.Address() - - // Make ValidatorInfo - valInfo := &ValidatorInfo{ - Address: address, - PubKey: pubKey, - UnbondTo: make([]*types.TxOutput, len(val.UnbondTo)), - FirstBondHeight: 0, - FirstBondAmount: val.Amount, - } - for i, unbondTo := range val.UnbondTo { - valInfo.UnbondTo[i] = &types.TxOutput{ - Address: unbondTo.Address, - Amount: unbondTo.Amount, - } - } - validatorInfos.Set(address, valInfo) - - // Make validator - validators[i] = &Validator{ - Address: address, - PubKey: pubKey, - VotingPower: val.Amount, - } - } - - // Make namereg tree - nameReg := merkle.NewIAVLTree(wire.BasicCodec, NameRegCodec, 0, db) - // TODO: add names, contracts to genesis.json - - // IAVLTrees must be persisted before copy operations. - accounts.Save() - validatorInfos.Save() - nameReg.Save() - - return &State{ - DB: db, - ChainID: genDoc.ChainID, - LastBlockHeight: 0, - LastBlockHash: nil, - LastBlockParts: types.PartSetHeader{}, - LastBlockTime: genDoc.GenesisTime, - BondedValidators: NewValidatorSet(validators), - LastBondedValidators: NewValidatorSet(nil), - UnbondingValidators: NewValidatorSet(nil), - accounts: accounts, - validatorInfos: validatorInfos, - nameReg: nameReg, - } -} diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/state/genesis_test.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/state/genesis_test.go index 5a83d33c3e0c49d72ee2cc42db5f91da591dde99..7c91436dc1bc7abf4db453a5b40a186db7c1dacb 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/state/genesis_test.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/state/genesis_test.go @@ -8,6 +8,7 @@ import ( tdb "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/db" ptypes "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/permission/types" + . "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/state/types" ) var chain_id = "lone_ranger" diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/state/permissions_test.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/state/permissions_test.go index dc51d8bd2416d786c5430e37501b68c389471efb..fcaf48d95a2c16cf10a2087bf7d2a543a5b15b08 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/state/permissions_test.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/state/permissions_test.go @@ -12,6 +12,7 @@ import ( dbm "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/db" "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/events" ptypes "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/permission/types" + . "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/state/types" "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/types" ) @@ -83,7 +84,7 @@ var chainID = "testchain" func makeUsers(n int) []*acm.PrivAccount { accounts := []*acm.PrivAccount{} for i := 0; i < n; i++ { - secret := []byte("mysecret" + strconv.Itoa(i)) + secret := ("mysecret" + strconv.Itoa(i)) user := acm.GenPrivAccountFromSecret(secret) accounts = append(accounts, user) } @@ -1054,7 +1055,7 @@ func execTxWaitEvent(t *testing.T, blockCache *BlockCache, tx types.Tx, eventid evsw := events.NewEventSwitch() evsw.Start() ch := make(chan interface{}) - evsw.AddListenerForEvent("test", eventid, func(msg interface{}) { + evsw.AddListenerForEvent("test", eventid, func(msg types.EventData) { ch <- msg }) evc := events.NewEventCache(evsw) @@ -1073,9 +1074,9 @@ func execTxWaitEvent(t *testing.T, blockCache *BlockCache, tx types.Tx, eventid } switch ev := msg.(type) { - case types.EventMsgCallTx: + case types.EventDataTx: return ev, ev.Exception - case types.EventMsgCall: + case types.EventDataCall: return ev, ev.Exception case string: return nil, ev @@ -1118,7 +1119,7 @@ func testSNativeCALL(t *testing.T, expectPass bool, blockCache *BlockCache, doug if exception != "" { t.Fatal("Unexpected exception", exception) } - evv := ev.(types.EventMsgCall) + evv := ev.(types.EventDataCall) ret := evv.Return if err := f(ret); err != nil { t.Fatal(err) diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/state/state.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/state/state.go index 395c01fff7084c52f6654a2784f66e45973e4400..4abbc242e6481bca9515cec4a7c6372d13e9d3e1 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/state/state.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/state/state.go @@ -3,6 +3,7 @@ package state import ( "bytes" "io" + "io/ioutil" "time" acm "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/account" @@ -10,6 +11,8 @@ import ( dbm "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/db" "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/events" "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/merkle" + ptypes "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/permission/types" + . "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/state/types" "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/types" "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/wire" ) @@ -32,9 +35,9 @@ type State struct { LastBlockHash []byte LastBlockParts types.PartSetHeader LastBlockTime time.Time - BondedValidators *ValidatorSet - LastBondedValidators *ValidatorSet - UnbondingValidators *ValidatorSet + BondedValidators *types.ValidatorSet + LastBondedValidators *types.ValidatorSet + UnbondingValidators *types.ValidatorSet accounts merkle.Tree // Shouldn't be accessed directly. validatorInfos merkle.Tree // Shouldn't be accessed directly. nameReg merkle.Tree // Shouldn't be accessed directly. @@ -54,14 +57,14 @@ func LoadState(db dbm.DB) *State { s.LastBlockHash = wire.ReadByteSlice(r, n, err) s.LastBlockParts = wire.ReadBinary(types.PartSetHeader{}, r, n, err).(types.PartSetHeader) s.LastBlockTime = wire.ReadTime(r, n, err) - s.BondedValidators = wire.ReadBinary(&ValidatorSet{}, r, n, err).(*ValidatorSet) - s.LastBondedValidators = wire.ReadBinary(&ValidatorSet{}, r, n, err).(*ValidatorSet) - s.UnbondingValidators = wire.ReadBinary(&ValidatorSet{}, r, n, err).(*ValidatorSet) + s.BondedValidators = wire.ReadBinary(&types.ValidatorSet{}, r, n, err).(*types.ValidatorSet) + s.LastBondedValidators = wire.ReadBinary(&types.ValidatorSet{}, r, n, err).(*types.ValidatorSet) + s.UnbondingValidators = wire.ReadBinary(&types.ValidatorSet{}, r, n, err).(*types.ValidatorSet) accountsHash := wire.ReadByteSlice(r, n, err) s.accounts = merkle.NewIAVLTree(wire.BasicCodec, acm.AccountCodec, defaultAccountsCacheCapacity, db) s.accounts.Load(accountsHash) validatorInfosHash := wire.ReadByteSlice(r, n, err) - s.validatorInfos = merkle.NewIAVLTree(wire.BasicCodec, ValidatorInfoCodec, 0, db) + s.validatorInfos = merkle.NewIAVLTree(wire.BasicCodec, types.ValidatorInfoCodec, 0, db) s.validatorInfos.Load(validatorInfosHash) nameRegHash := wire.ReadByteSlice(r, n, err) s.nameReg = merkle.NewIAVLTree(wire.BasicCodec, NameRegCodec, 0, db) @@ -120,14 +123,13 @@ func (s *State) Copy() *State { // Returns a hash that represents the state data, excluding Last* func (s *State) Hash() []byte { - hashables := []merkle.Hashable{ - s.BondedValidators, - s.UnbondingValidators, - s.accounts, - s.validatorInfos, - s.nameReg, - } - return merkle.SimpleHashFromHashables(hashables) + return merkle.SimpleHashFromMap(map[string]interface{}{ + "BondedValidators": s.BondedValidators, + "UnbondingValidators": s.UnbondingValidators, + "Accounts": s.accounts, + "ValidatorInfos": s.validatorInfos, + "NameRegistry": s.nameReg, + }) } // Mutates the block in place and updates it with new state hash. @@ -200,18 +202,18 @@ func (s *State) SetAccounts(accounts merkle.Tree) { // The returned ValidatorInfo is a copy, so mutating it // has no side effects. -func (s *State) GetValidatorInfo(address []byte) *ValidatorInfo { +func (s *State) GetValidatorInfo(address []byte) *types.ValidatorInfo { _, valInfo := s.validatorInfos.Get(address) if valInfo == nil { return nil } - return valInfo.(*ValidatorInfo).Copy() + return valInfo.(*types.ValidatorInfo).Copy() } // Returns false if new, true if updated. // The valInfo is copied before setting, so mutating it // afterwards has no side effects. -func (s *State) SetValidatorInfo(valInfo *ValidatorInfo) (updated bool) { +func (s *State) SetValidatorInfo(valInfo *types.ValidatorInfo) (updated bool) { return s.validatorInfos.Set(valInfo.Address, valInfo.Copy()) } @@ -219,7 +221,7 @@ func (s *State) GetValidatorInfos() merkle.Tree { return s.validatorInfos.Copy() } -func (s *State) unbondValidator(val *Validator) { +func (s *State) unbondValidator(val *types.Validator) { // Move validator to UnbondingValidators val, removed := s.BondedValidators.Remove(val.Address) if !removed { @@ -232,7 +234,7 @@ func (s *State) unbondValidator(val *Validator) { } } -func (s *State) rebondValidator(val *Validator) { +func (s *State) rebondValidator(val *types.Validator) { // Move validator to BondingValidators val, removed := s.UnbondingValidators.Remove(val.Address) if !removed { @@ -245,7 +247,7 @@ func (s *State) rebondValidator(val *Validator) { } } -func (s *State) releaseValidator(val *Validator) { +func (s *State) releaseValidator(val *types.Validator) { // Update validatorInfo valInfo := s.GetValidatorInfo(val.Address) if valInfo == nil { @@ -271,7 +273,7 @@ func (s *State) releaseValidator(val *Validator) { } } -func (s *State) destroyValidator(val *Validator) { +func (s *State) destroyValidator(val *types.Validator) { // Update validatorInfo valInfo := s.GetValidatorInfo(val.Address) if valInfo == nil { @@ -360,12 +362,114 @@ func (s *State) SetFireable(evc events.Fireable) { } //----------------------------------------------------------------------------- +// Genesis -type InvalidTxError struct { - Tx types.Tx - Reason error +func MakeGenesisStateFromFile(db dbm.DB, genDocFile string) (*GenesisDoc, *State) { + jsonBlob, err := ioutil.ReadFile(genDocFile) + if err != nil { + Exit(Fmt("Couldn't read GenesisDoc file: %v", err)) + } + genDoc := GenesisDocFromJSON(jsonBlob) + return genDoc, MakeGenesisState(db, genDoc) } -func (txErr InvalidTxError) Error() string { - return Fmt("Invalid tx: [%v] reason: [%v]", txErr.Tx, txErr.Reason) +func MakeGenesisState(db dbm.DB, genDoc *GenesisDoc) *State { + if len(genDoc.Validators) == 0 { + Exit(Fmt("The genesis file has no validators")) + } + + if genDoc.GenesisTime.IsZero() { + genDoc.GenesisTime = time.Now() + } + + // Make accounts state tree + accounts := merkle.NewIAVLTree(wire.BasicCodec, acm.AccountCodec, defaultAccountsCacheCapacity, db) + for _, genAcc := range genDoc.Accounts { + perm := ptypes.ZeroAccountPermissions + if genAcc.Permissions != nil { + perm = *genAcc.Permissions + } + acc := &acm.Account{ + Address: genAcc.Address, + PubKey: nil, + Sequence: 0, + Balance: genAcc.Amount, + Permissions: perm, + } + accounts.Set(acc.Address, acc) + } + + // global permissions are saved as the 0 address + // so they are included in the accounts tree + globalPerms := ptypes.DefaultAccountPermissions + if genDoc.Params != nil && genDoc.Params.GlobalPermissions != nil { + globalPerms = *genDoc.Params.GlobalPermissions + // XXX: make sure the set bits are all true + // Without it the HasPermission() functions will fail + globalPerms.Base.SetBit = ptypes.AllPermFlags + } + + permsAcc := &acm.Account{ + Address: ptypes.GlobalPermissionsAddress, + PubKey: nil, + Sequence: 0, + Balance: 1337, + Permissions: globalPerms, + } + accounts.Set(permsAcc.Address, permsAcc) + + // Make validatorInfos state tree && validators slice + validatorInfos := merkle.NewIAVLTree(wire.BasicCodec, types.ValidatorInfoCodec, 0, db) + validators := make([]*types.Validator, len(genDoc.Validators)) + for i, val := range genDoc.Validators { + pubKey := val.PubKey + address := pubKey.Address() + + // Make ValidatorInfo + valInfo := &types.ValidatorInfo{ + Address: address, + PubKey: pubKey, + UnbondTo: make([]*types.TxOutput, len(val.UnbondTo)), + FirstBondHeight: 0, + FirstBondAmount: val.Amount, + } + for i, unbondTo := range val.UnbondTo { + valInfo.UnbondTo[i] = &types.TxOutput{ + Address: unbondTo.Address, + Amount: unbondTo.Amount, + } + } + validatorInfos.Set(address, valInfo) + + // Make validator + validators[i] = &types.Validator{ + Address: address, + PubKey: pubKey, + VotingPower: val.Amount, + } + } + + // Make namereg tree + nameReg := merkle.NewIAVLTree(wire.BasicCodec, NameRegCodec, 0, db) + // TODO: add names, contracts to genesis.json + + // IAVLTrees must be persisted before copy operations. + accounts.Save() + validatorInfos.Save() + nameReg.Save() + + return &State{ + DB: db, + ChainID: genDoc.ChainID, + LastBlockHeight: 0, + LastBlockHash: nil, + LastBlockParts: types.PartSetHeader{}, + LastBlockTime: genDoc.GenesisTime, + BondedValidators: types.NewValidatorSet(validators), + LastBondedValidators: types.NewValidatorSet(nil), + UnbondingValidators: types.NewValidatorSet(nil), + accounts: accounts, + validatorInfos: validatorInfos, + nameReg: nameReg, + } } diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/state/state_test.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/state/state_test.go index 5793cd97027877be61b973e3e68c24c3ca8d3e45..d030f31942fa75f5d650f97b828a221935fdcf01 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/state/state_test.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/state/state_test.go @@ -1,19 +1,18 @@ package state import ( - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/account" - _ "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/config/tendermint_test" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/types" - "bytes" "testing" "time" + + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/account" + _ "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/config/tendermint_test" + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/types" ) func execTxWithState(state *State, tx types.Tx, runCall bool) error { cache := NewBlockCache(state) - err := ExecTx(cache, tx, runCall, nil) - if err != nil { + if err := ExecTx(cache, tx, runCall, nil); err != nil { return err } else { cache.Sync() @@ -91,6 +90,7 @@ func makeBlock(t *testing.T, state *State, validation *types.Validation, txs []t Txs: txs, }, } + block.FillHeader() // Fill in block StateHash err := state.ComputeBlockStateHash(block) @@ -219,12 +219,12 @@ func TestNameTxs(t *testing.T) { startingBlock := state.LastBlockHeight // try some bad names. these should all fail - names := []string{"", "\n", "123#$%", "\x00", string([]byte{20, 40, 60, 80}), "baffledbythespectacleinallofthisyouseeehesaidwithouteyes", "no spaces please"} + names := []string{"", "\n", "123#$%", "\x00", string([]byte{20, 40, 60, 80}), "baffledbythespectacleinallofthisyouseeehesaidwithouteyessurprised", "no spaces please"} data := "something about all this just doesn't feel right." fee := int64(1000) numDesiredBlocks := 5 for _, name := range names { - amt := fee + int64(numDesiredBlocks)*types.NameCostPerByte*types.NameCostPerBlock*types.BaseEntryCost(name, data) + amt := fee + int64(numDesiredBlocks)*types.NameByteCostMultiplier*types.NameBlockCostMultiplier*types.NameBaseCost(name, data) tx, _ := types.NewNameTx(state, privAccounts[0].PubKey, name, data, amt, fee) tx.Sign(state.ChainID, privAccounts[0]) @@ -237,7 +237,7 @@ func TestNameTxs(t *testing.T) { name := "hold_it_chum" datas := []string{"cold&warm", "!@#$%^&*()", "<<<>>>>", "because why would you ever need a ~ or a & or even a % in a json file? make your case and we'll talk"} for _, data := range datas { - amt := fee + int64(numDesiredBlocks)*types.NameCostPerByte*types.NameCostPerBlock*types.BaseEntryCost(name, data) + amt := fee + int64(numDesiredBlocks)*types.NameByteCostMultiplier*types.NameBlockCostMultiplier*types.NameBaseCost(name, data) tx, _ := types.NewNameTx(state, privAccounts[0].PubKey, name, data, amt, fee) tx.Sign(state.ChainID, privAccounts[0]) @@ -266,9 +266,9 @@ func TestNameTxs(t *testing.T) { } // try a good one, check data, owner, expiry - name = "looking_good/karaoke_bar" - data = "on this side of neptune there are 1234567890 people: first is OMNIVORE. Or is it. Ok this is pretty restrictive. No exclamations :(. Faces tho :')" - amt := fee + int64(numDesiredBlocks)*types.NameCostPerByte*types.NameCostPerBlock*types.BaseEntryCost(name, data) + name = "@looking_good/karaoke_bar.broadband" + data = "on this side of neptune there are 1234567890 people: first is OMNIVORE+-3. Or is it. Ok this is pretty restrictive. No exclamations :(. Faces tho :')" + amt := fee + int64(numDesiredBlocks)*types.NameByteCostMultiplier*types.NameBlockCostMultiplier*types.NameBaseCost(name, data) tx, _ := types.NewNameTx(state, privAccounts[0].PubKey, name, data, amt, fee) tx.Sign(state.ChainID, privAccounts[0]) if err := execTxWithState(state, tx, true); err != nil { @@ -325,7 +325,7 @@ func TestNameTxs(t *testing.T) { data = "In the beginning there was no thing, not even the beginning. It hadn't been here, no there, nor for that matter anywhere, not especially because it had not to even exist, let alone to not. Nothing especially odd about that." oldCredit := amt - fee numDesiredBlocks = 10 - amt = fee + (int64(numDesiredBlocks)*types.NameCostPerByte*types.NameCostPerBlock*types.BaseEntryCost(name, data) - oldCredit) + amt = fee + (int64(numDesiredBlocks)*types.NameByteCostMultiplier*types.NameBlockCostMultiplier*types.NameBaseCost(name, data) - oldCredit) tx, _ = types.NewNameTx(state, privAccounts[1].PubKey, name, data, amt, fee) tx.Sign(state.ChainID, privAccounts[1]) if err := execTxWithState(state, tx, true); err != nil { @@ -351,7 +351,7 @@ func TestNameTxs(t *testing.T) { // test removal by key1 after expiry name = "looking_good/karaoke_bar" data = "some data" - amt = fee + int64(numDesiredBlocks)*types.NameCostPerByte*types.NameCostPerBlock*types.BaseEntryCost(name, data) + amt = fee + int64(numDesiredBlocks)*types.NameByteCostMultiplier*types.NameBlockCostMultiplier*types.NameBaseCost(name, data) tx, _ = types.NewNameTx(state, privAccounts[0].PubKey, name, data, amt, fee) tx.Sign(state.ChainID, privAccounts[0]) if err := execTxWithState(state, tx, true); err != nil { @@ -511,7 +511,7 @@ proof-of-work chain as proof of what happened while they were gone ` tx.Input.Sequence += 1 tx.Input.Signature = privAccounts[0].Sign(state.ChainID, tx) err = execTxWithState(state, tx, true) - if err != types.ErrTxInvalidString { + if _, ok := err.(types.ErrTxInvalidString); !ok { t.Errorf("Expected invalid string error. Got: %s", err.Error()) } } @@ -577,34 +577,41 @@ func TestSuicide(t *testing.T) { acc0PubKey := privAccounts[0].PubKey acc1 := state.GetAccount(privAccounts[1].PubKey.Address()) acc2 := state.GetAccount(privAccounts[2].Address) - sendingAmount, leftoverBalance, oldBalance := int64(1), acc1.Balance, acc2.Balance + sendingAmount, refundedBalance, oldBalance := int64(1), acc1.Balance, acc2.Balance newAcc1 := state.GetAccount(acc1.Address) - // store 0x1 and 0x1, then suicide :) + // store 0x1 at 0x1, push an address, then suicide :) contractCode := []byte{0x60, 0x01, 0x60, 0x01, 0x55, 0x73} contractCode = append(contractCode, acc2.Address...) contractCode = append(contractCode, 0xff) newAcc1.Code = contractCode state.UpdateAccount(newAcc1) - tx := &types.CallTx{ - Input: &types.TxInput{ - Address: acc0.Address, - Amount: sendingAmount, - Sequence: acc0.Sequence + 1, - PubKey: acc0PubKey, - }, - Address: acc1.Address, - GasLimit: 1000, + + // send call tx with no data, cause suicide + tx := types.NewCallTxWithNonce(acc0PubKey, acc1.Address, nil, sendingAmount, 1000, 0, acc0.Sequence+1) + tx.Input.Signature = privAccounts[0].Sign(state.ChainID, tx) + + // we use cache instead of execTxWithState so we can run the tx twice + cache := NewBlockCache(state) + if err := ExecTx(cache, tx, true, nil); err != nil { + t.Errorf("Got error in executing call transaction, %v", err) } + // if we do it again, we won't get an error, but the suicide + // shouldn't happen twice and the caller should lose fee + tx.Input.Sequence += 1 tx.Input.Signature = privAccounts[0].Sign(state.ChainID, tx) - err := execTxWithState(state, tx, true) - if err != nil { + if err := ExecTx(cache, tx, true, nil); err != nil { t.Errorf("Got error in executing call transaction, %v", err) } + + // commit the block + cache.Sync() + + // acc2 should receive the sent funds and the contracts balance newAcc2 := state.GetAccount(acc2.Address) - newBalance := sendingAmount + leftoverBalance + oldBalance + newBalance := sendingAmount + refundedBalance + oldBalance if newAcc2.Balance != newBalance { t.Errorf("Unexpected newAcc2 balance. Expected %v, got %v", newAcc2.Balance, newBalance) @@ -613,6 +620,7 @@ func TestSuicide(t *testing.T) { if newAcc1 != nil { t.Errorf("Expected account to be removed") } + } func TestAddValidator(t *testing.T) { @@ -668,11 +676,11 @@ func TestAddValidator(t *testing.T) { // The validation for the next block should only require 1 signature // (the new validator wasn't active for block0) precommit0 := &types.Vote{ - Height: 1, - Round: 0, - Type: types.VoteTypePrecommit, - BlockHash: block0.Hash(), - BlockParts: block0Parts.Header(), + Height: 1, + Round: 0, + Type: types.VoteTypePrecommit, + BlockHash: block0.Hash(), + BlockPartsHeader: block0Parts.Header(), } privValidators[0].SignVote(s0.ChainID, precommit0) diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/state/test.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/state/test.go index e26aa3a3a1d9afe52e656b4ab5fcaf0074837c04..ca6eae68c62a593e0d0292a26d5edb59a7a604f3 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/state/test.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/state/test.go @@ -1,28 +1,17 @@ package state import ( - "bytes" "sort" + "time" acm "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/account" . "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/common" dbm "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/db" ptypes "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/permission/types" + . "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/state/types" "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/types" - - "io/ioutil" - "os" - "time" ) -func Tempfile(prefix string) (*os.File, string) { - file, err := ioutil.TempFile("", prefix) - if err != nil { - PanicCrisis(err) - } - return file, file.Name() -} - func RandAccount(randBalance bool, minBalance int64) (*acm.Account, *acm.PrivAccount) { privAccount := acm.GenPrivAccount() perms := ptypes.DefaultAccountPermissions @@ -39,37 +28,7 @@ func RandAccount(randBalance bool, minBalance int64) (*acm.Account, *acm.PrivAcc return acc, privAccount } -func RandValidator(randBonded bool, minBonded int64) (*ValidatorInfo, *Validator, *PrivValidator) { - privVal := GenPrivValidator() - _, tempFilePath := Tempfile("priv_validator_") - privVal.SetFile(tempFilePath) - bonded := minBonded - if randBonded { - bonded += int64(RandUint32()) - } - valInfo := &ValidatorInfo{ - Address: privVal.Address, - PubKey: privVal.PubKey, - UnbondTo: []*types.TxOutput{&types.TxOutput{ - Amount: bonded, - Address: privVal.Address, - }}, - FirstBondHeight: 0, - FirstBondAmount: bonded, - } - val := &Validator{ - Address: valInfo.Address, - PubKey: valInfo.PubKey, - BondHeight: 0, - UnbondHeight: 0, - LastCommitHeight: 0, - VotingPower: valInfo.FirstBondAmount, - Accum: 0, - } - return valInfo, val, privVal -} - -func RandGenesisDoc(numAccounts int, randBalance bool, minBalance int64, numValidators int, randBonded bool, minBonded int64) (*GenesisDoc, []*acm.PrivAccount, []*PrivValidator) { +func RandGenesisDoc(numAccounts int, randBalance bool, minBalance int64, numValidators int, randBonded bool, minBonded int64) (*GenesisDoc, []*acm.PrivAccount, []*types.PrivValidator) { accounts := make([]GenesisAccount, numAccounts) privAccounts := make([]*acm.PrivAccount, numAccounts) defaultPerms := ptypes.DefaultAccountPermissions @@ -83,9 +42,9 @@ func RandGenesisDoc(numAccounts int, randBalance bool, minBalance int64, numVali privAccounts[i] = privAccount } validators := make([]GenesisValidator, numValidators) - privValidators := make([]*PrivValidator, numValidators) + privValidators := make([]*types.PrivValidator, numValidators) for i := 0; i < numValidators; i++ { - valInfo, _, privVal := RandValidator(randBonded, minBonded) + valInfo, _, privVal := types.RandValidator(randBonded, minBonded) validators[i] = GenesisValidator{ PubKey: valInfo.PubKey, Amount: valInfo.FirstBondAmount, @@ -98,7 +57,7 @@ func RandGenesisDoc(numAccounts int, randBalance bool, minBalance int64, numVali } privValidators[i] = privVal } - sort.Sort(PrivValidatorsByAddress(privValidators)) + sort.Sort(types.PrivValidatorsByAddress(privValidators)) return &GenesisDoc{ GenesisTime: time.Now(), ChainID: "tendermint_test", @@ -108,28 +67,10 @@ func RandGenesisDoc(numAccounts int, randBalance bool, minBalance int64, numVali } -func RandGenesisState(numAccounts int, randBalance bool, minBalance int64, numValidators int, randBonded bool, minBonded int64) (*State, []*acm.PrivAccount, []*PrivValidator) { +func RandGenesisState(numAccounts int, randBalance bool, minBalance int64, numValidators int, randBonded bool, minBonded int64) (*State, []*acm.PrivAccount, []*types.PrivValidator) { db := dbm.NewMemDB() genDoc, privAccounts, privValidators := RandGenesisDoc(numAccounts, randBalance, minBalance, numValidators, randBonded, minBonded) s0 := MakeGenesisState(db, genDoc) s0.Save() return s0, privAccounts, privValidators } - -//------------------------------------- - -type PrivValidatorsByAddress []*PrivValidator - -func (pvs PrivValidatorsByAddress) Len() int { - return len(pvs) -} - -func (pvs PrivValidatorsByAddress) Less(i, j int) bool { - return bytes.Compare(pvs[i].Address, pvs[j].Address) == -1 -} - -func (pvs PrivValidatorsByAddress) Swap(i, j int) { - it := pvs[i] - pvs[i] = pvs[j] - pvs[j] = it -} diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/state/tx_cache.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/state/tx_cache.go index 422ae7dfacdd6561656b20cfdc9c78a1132bdf5e..532bb896c60ca860b088d861985ae7d95253c779 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/state/tx_cache.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/state/tx_cache.go @@ -4,15 +4,14 @@ import ( acm "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/account" . "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/common" ptypes "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/permission/types" // for GlobalPermissionAddress ... + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/types" "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/vm" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/sha3" ) type TxCache struct { backend *BlockCache accounts map[Word256]vmAccountInfo storages map[Tuple256]Word256 - logs []*vm.Log } func NewTxCache(backend *BlockCache) *TxCache { @@ -20,7 +19,6 @@ func NewTxCache(backend *BlockCache) *TxCache { backend: backend, accounts: make(map[Word256]vmAccountInfo), storages: make(map[Tuple256]Word256), - logs: make([]*vm.Log, 0), } } @@ -138,18 +136,11 @@ func (cache *TxCache) Sync() { } } -func (cache *TxCache) AddLog(log *vm.Log) { - cache.logs = append(cache.logs, log) -} - //----------------------------------------------------------------------------- // Convenience function to return address of new contract func NewContractAddress(caller []byte, nonce int) []byte { - temp := make([]byte, 32+8) - copy(temp, caller) - PutInt64BE(temp[32:], int64(nonce)) - return sha3.Sha3(temp)[:20] + return types.NewContractAddress(caller, nonce) } // Converts backend.Account to vm.Account struct. diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/state/types/genesis.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/state/types/genesis.go new file mode 100644 index 0000000000000000000000000000000000000000..ed90b01bf6623ac4079194db7876d513480b9aef --- /dev/null +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/state/types/genesis.go @@ -0,0 +1,61 @@ +package types + +import ( + "time" + + acm "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/account" + . "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/common" + ptypes "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/permission/types" + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/wire" +) + +//------------------------------------------------------------ +// we store the gendoc in the db + +var GenDocKey = []byte("GenDocKey") + +//------------------------------------------------------------ +// core types for a genesis definition + +type BasicAccount struct { + Address []byte `json:"address"` + Amount int64 `json:"amount"` +} + +type GenesisAccount struct { + Address []byte `json:"address"` + Amount int64 `json:"amount"` + Name string `json:"name"` + Permissions *ptypes.AccountPermissions `json:"permissions"` +} + +type GenesisValidator struct { + PubKey acm.PubKeyEd25519 `json:"pub_key"` + Amount int64 `json:"amount"` + Name string `json:"name"` + UnbondTo []BasicAccount `json:"unbond_to"` +} + +type GenesisParams struct { + GlobalPermissions *ptypes.AccountPermissions `json:"global_permissions"` +} + +type GenesisDoc struct { + GenesisTime time.Time `json:"genesis_time"` + ChainID string `json:"chain_id"` + Params *GenesisParams `json:"params"` + Accounts []GenesisAccount `json:"accounts"` + Validators []GenesisValidator `json:"validators"` +} + +//------------------------------------------------------------ +// Make genesis state from file + +func GenesisDocFromJSON(jsonBlob []byte) (genState *GenesisDoc) { + var err error + wire.ReadJSONPtr(&genState, jsonBlob, &err) + if err != nil { + Exit(Fmt("Couldn't read GenesisDoc: %v", err)) + } + return +} diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/types/block.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/types/block.go index f0cbd11d9810ec199785ba8710325fcdd417718e..7750f97856021762f097e73fd583634aaa53d8e3 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/types/block.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/types/block.go @@ -28,6 +28,14 @@ func (b *Block) ValidateBasic(chainID string, lastBlockHeight int, lastBlockHash if b.Height != lastBlockHeight+1 { return errors.New(Fmt("Wrong Block.Header.Height. Expected %v, got %v", lastBlockHeight+1, b.Height)) } + /* TODO: Determine bounds for Time + See blockchain/reactor "stopSyncingDurationMinutes" + + if !b.Time.After(lastBlockTime) { + return errors.New("Invalid Block.Header.Time") + } + */ + // TODO: validate Fees if b.NumTxs != len(b.Data.Txs) { return errors.New(Fmt("Wrong Block.Header.NumTxs. Expected %v, got %v", len(b.Data.Txs), b.NumTxs)) } @@ -37,22 +45,26 @@ func (b *Block) ValidateBasic(chainID string, lastBlockHeight int, lastBlockHash if !b.LastBlockParts.Equals(lastBlockParts) { return errors.New(Fmt("Wrong Block.Header.LastBlockParts. Expected %v, got %v", lastBlockParts, b.LastBlockParts)) } - /* TODO: Determine bounds - See blockchain/reactor "stopSyncingDurationMinutes" - - if !b.Time.After(lastBlockTime) { - return errors.New("Invalid Block.Header.Time") - } - */ + if !bytes.Equal(b.LastValidationHash, b.LastValidation.Hash()) { + return errors.New(Fmt("Wrong Block.Header.LastValidationHash. Expected %X, got %X", b.LastValidationHash, b.LastValidation.Hash())) + } if b.Header.Height != 1 { if err := b.LastValidation.ValidateBasic(); err != nil { return err } } - // XXX more validation + if !bytes.Equal(b.DataHash, b.Data.Hash()) { + return errors.New(Fmt("Wrong Block.Header.DataHash. Expected %X, got %X", b.DataHash, b.Data.Hash())) + } + // NOTE: the StateHash is validated later. return nil } +func (b *Block) FillHeader() { + b.LastValidationHash = b.LastValidation.Hash() + b.DataHash = b.Data.Hash() +} + // Computes and returns the block hash. // If the block is incomplete (e.g. missing Header.StateHash) // then the hash is nil, to prevent the usage of that hash. @@ -60,18 +72,8 @@ func (b *Block) Hash() []byte { if b.Header == nil || b.Data == nil || b.LastValidation == nil { return nil } - hashHeader := b.Header.Hash() - hashData := b.Data.Hash() - hashLastValidation := b.LastValidation.Hash() - - // If hashHeader is nil, required fields are missing. - if len(hashHeader) == 0 { - return nil - } - - // Merkle hash from subhashes. - hashes := [][]byte{hashHeader, hashData, hashLastValidation} - return merkle.SimpleHashFromHashes(hashes) + b.FillHeader() + return b.Header.Hash() } func (b *Block) MakePartSet() *PartSet { @@ -121,14 +123,16 @@ func (b *Block) StringShort() string { //----------------------------------------------------------------------------- type Header struct { - ChainID string `json:"chain_id"` - Height int `json:"height"` - Time time.Time `json:"time"` - Fees int64 `json:"fees"` - NumTxs int `json:"num_txs"` - LastBlockHash []byte `json:"last_block_hash"` - LastBlockParts PartSetHeader `json:"last_block_parts"` - StateHash []byte `json:"state_hash"` + ChainID string `json:"chain_id"` + Height int `json:"height"` + Time time.Time `json:"time"` + Fees int64 `json:"fees"` + NumTxs int `json:"num_txs"` + LastBlockHash []byte `json:"last_block_hash"` + LastBlockParts PartSetHeader `json:"last_block_parts"` + LastValidationHash []byte `json:"last_validation_hash"` + DataHash []byte `json:"data_hash"` + StateHash []byte `json:"state_hash"` } // NOTE: hash is nil if required fields are missing. @@ -136,8 +140,18 @@ func (h *Header) Hash() []byte { if len(h.StateHash) == 0 { return nil } - - return wire.BinaryRipemd160(h) + return merkle.SimpleHashFromMap(map[string]interface{}{ + "ChainID": h.ChainID, + "Height": h.Height, + "Time": h.Time, + "Fees": h.Fees, + "NumTxs": h.NumTxs, + "LastBlock": h.LastBlockHash, + "LastBlockParts": h.LastBlockParts, + "LastValidation": h.LastValidationHash, + "Data": h.DataHash, + "State": h.StateHash, + }) } func (h *Header) StringIndented(indent string) string { diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/types/events.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/types/events.go index e3502a1a5e057022081d99fbb1d3610752c12963..8ce11fabd92deff82351f99a1bb12aaba2c18c3c 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/types/events.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/types/events.go @@ -2,63 +2,88 @@ package types import ( "fmt" + "time" + + . "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/common" + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/wire" ) // Functions to generate eventId strings -func EventStringAccInput(addr []byte) string { - return fmt.Sprintf("Acc/%X/Input", addr) -} - -func EventStringAccOutput(addr []byte) string { - return fmt.Sprintf("Acc/%X/Output", addr) -} - -func EventStringAccCall(addr []byte) string { - return fmt.Sprintf("Acc/%X/Call", addr) -} - -func EventStringLogEvent(addr []byte) string { - return fmt.Sprintf("Log/%X", addr) -} - -func EventStringPermissions(name string) string { - return fmt.Sprintf("Permissions/%s", name) -} - -func EventStringBond() string { - return "Bond" -} - -func EventStringUnbond() string { - return "Unbond" -} +func EventStringAccInput(addr []byte) string { return fmt.Sprintf("Acc/%X/Input", addr) } +func EventStringAccOutput(addr []byte) string { return fmt.Sprintf("Acc/%X/Output", addr) } +func EventStringAccCall(addr []byte) string { return fmt.Sprintf("Acc/%X/Call", addr) } +func EventStringLogEvent(addr []byte) string { return fmt.Sprintf("Log/%X", addr) } +func EventStringPermissions(name string) string { return fmt.Sprintf("Permissions/%s", name) } +func EventStringNameReg(name string) string { return fmt.Sprintf("NameReg/%s", name) } +func EventStringBond() string { return "Bond" } +func EventStringUnbond() string { return "Unbond" } +func EventStringRebond() string { return "Rebond" } +func EventStringDupeout() string { return "Dupeout" } +func EventStringNewBlock() string { return "NewBlock" } +func EventStringFork() string { return "Fork" } + +func EventStringNewRound() string { return fmt.Sprintf("NewRound") } +func EventStringTimeoutPropose() string { return fmt.Sprintf("TimeoutPropose") } +func EventStringCompleteProposal() string { return fmt.Sprintf("CompleteProposal") } +func EventStringPolka() string { return fmt.Sprintf("Polka") } +func EventStringUnlock() string { return fmt.Sprintf("Unlock") } +func EventStringLock() string { return fmt.Sprintf("Lock") } +func EventStringRelock() string { return fmt.Sprintf("Relock") } +func EventStringTimeoutWait() string { return fmt.Sprintf("TimeoutWait") } +func EventStringVote() string { return fmt.Sprintf("Vote") } + +//---------------------------------------- + +const ( + EventDataTypeNewBlock = byte(0x01) + EventDataTypeFork = byte(0x02) + EventDataTypeTx = byte(0x03) + EventDataTypeCall = byte(0x04) + EventDataTypeLog = byte(0x05) + + EventDataTypeRoundState = byte(0x11) + EventDataTypeVote = byte(0x12) +) -func EventStringRebond() string { - return "Rebond" +type EventData interface { + AssertIsEventData() } -func EventStringDupeout() string { - return "Dupeout" -} +var _ = wire.RegisterInterface( + struct{ EventData }{}, + wire.ConcreteType{EventDataNewBlock{}, EventDataTypeNewBlock}, + // wire.ConcreteType{EventDataFork{}, EventDataTypeFork }, + wire.ConcreteType{EventDataTx{}, EventDataTypeTx}, + wire.ConcreteType{EventDataCall{}, EventDataTypeCall}, + wire.ConcreteType{EventDataLog{}, EventDataTypeLog}, + wire.ConcreteType{EventDataRoundState{}, EventDataTypeRoundState}, + wire.ConcreteType{EventDataVote{}, EventDataTypeVote}, +) -func EventStringNewBlock() string { - return "NewBlock" -} +// Most event messages are basic types (a block, a transaction) +// but some (an input to a call tx or a receive) are more exotic -func EventStringFork() string { - return "Fork" +type EventDataNewBlock struct { + Block *Block `json:"block"` } -// Most event messages are basic types (a block, a transaction) -// but some (an input to a call tx or a receive) are more exotic: - -type EventMsgCallTx struct { +// All txs fire EventDataTx, but only CallTx might have Return or Exception +type EventDataTx struct { Tx Tx `json:"tx"` Return []byte `json:"return"` Exception string `json:"exception"` } +// EventDataCall fires when we call a contract, and when a contract calls another contract +type EventDataCall struct { + CallData *CallData `json:"call_data"` + Origin []byte `json:"origin"` + TxID []byte `json:"tx_id"` + Return []byte `json:"return"` + Exception string `json:"exception"` +} + type CallData struct { Caller []byte `json:"caller"` Callee []byte `json:"callee"` @@ -67,10 +92,40 @@ type CallData struct { Gas int64 `json:"gas"` } -type EventMsgCall struct { - CallData *CallData `json:"call_data"` - Origin []byte `json:"origin"` - TxID []byte `json:"tx_id"` - Return []byte `json:"return"` - Exception string `json:"exception"` +// EventDataLog fires when a contract executes the LOG opcode +type EventDataLog struct { + Address Word256 `json:"address"` + Topics []Word256 `json:"topics"` + Data []byte `json:"data"` + Height int64 `json:"height"` } + +// We fire the most recent round state that led to the event +// (ie. NewRound will have the previous rounds state) +type EventDataRoundState struct { + CurrentTime time.Time `json:"current_time"` + + Height int `json:"height"` + Round int `json:"round"` + Step string `json:"step"` + StartTime time.Time `json:"start_time"` + CommitTime time.Time `json:"commit_time"` + Proposal *Proposal `json:"proposal"` + ProposalBlock *Block `json:"proposal_block"` + LockedRound int `json:"locked_round"` + LockedBlock *Block `json:"locked_block"` + POLRound int `json:"pol_round"` +} + +type EventDataVote struct { + Index int + Address []byte + Vote *Vote +} + +func (_ EventDataNewBlock) AssertIsEventData() {} +func (_ EventDataTx) AssertIsEventData() {} +func (_ EventDataCall) AssertIsEventData() {} +func (_ EventDataLog) AssertIsEventData() {} +func (_ EventDataRoundState) AssertIsEventData() {} +func (_ EventDataVote) AssertIsEventData() {} diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/types/keys.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/types/keys.go new file mode 100644 index 0000000000000000000000000000000000000000..90591b95936e5dc6af8d616a099169f95c9ceca0 --- /dev/null +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/types/keys.go @@ -0,0 +1,6 @@ +package types + +var ( + PeerStateKey = "ConsensusReactor.peerState" + PeerMempoolChKey = "MempoolReactor.peerMempoolCh" +) diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/types/names.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/types/names.go index 9ce4cc6f42b3a369c0937d6d7c789cd994c922fc..2f4c8ff83377289626b8b4414bc96946274ec3ae 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/types/names.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/types/names.go @@ -7,18 +7,21 @@ import ( var ( MinNameRegistrationPeriod int = 5 + // NOTE: base costs and validity checks are here so clients + // can use them without importing state + // cost for storing a name for a block is // CostPerBlock*CostPerByte*(len(data) + 32) - NameCostPerByte int64 = 1 - NameCostPerBlock int64 = 1 + NameByteCostMultiplier int64 = 1 + NameBlockCostMultiplier int64 = 1 - MaxNameLength = 32 + MaxNameLength = 64 MaxDataLength = 1 << 16 - // Name should be alphanum, underscore, slash + // Name should be file system lik // Data should be anything permitted in JSON - regexpAlphaNum = regexp.MustCompile("^[a-zA-Z0-9._/]*$") - regexpJSON = regexp.MustCompile(`^[a-zA-Z0-9_/ \-"':,\n\t.{}()\[\]]*$`) + regexpAlphaNum = regexp.MustCompile("^[a-zA-Z0-9._/-@]*$") + regexpJSON = regexp.MustCompile(`^[a-zA-Z0-9_/ \-+"':,\n\t.{}()\[\]]*$`) ) // filter strings @@ -31,10 +34,14 @@ func validateNameRegEntryData(data string) bool { } // base cost is "effective" number of bytes -func BaseEntryCost(name, data string) int64 { +func NameBaseCost(name, data string) int64 { return int64(len(data) + 32) } +func NameCostPerBlock(baseCost int64) int64 { + return NameBlockCostMultiplier * NameByteCostMultiplier * baseCost +} + type NameRegEntry struct { Name string `json:"name"` // registered name for the entry Owner []byte `json:"owner"` // address that created the entry diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/types/node.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/types/node.go index abc4d1a273cb4d0318579ff17a9c9f603e68d916..e548a5779c46c7e2515bd67355705f4ee9613250 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/types/node.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/types/node.go @@ -7,19 +7,28 @@ import ( ) type NodeInfo struct { - PubKey acm.PubKeyEd25519 `json:"pub_key"` - Moniker string `json:"moniker"` - ChainID string `json:"chain_id"` - Version string `json:"version"` - Revision string `json:"revision"` - Host string `json:"host"` - P2PPort uint16 `json:"p2p_port"` - RPCPort uint16 `json:"rpc_port"` + PubKey acm.PubKeyEd25519 `json:"pub_key"` + Moniker string `json:"moniker"` + ChainID string `json:"chain_id"` + Host string `json:"host"` + P2PPort uint16 `json:"p2p_port"` + RPCPort uint16 `json:"rpc_port"` + + Version Versions `json:"versions"` +} + +type Versions struct { + Revision string `json:"revision"` + Tendermint string `json"tendermint"` + P2P string `json:"p2p"` + RPC string `json:"rpc"` + Wire string `json:"wire"` } +// CONTRACT: two nodes with the same Tendermint major and minor version and with the same ChainID are compatible func (ni *NodeInfo) CompatibleWith(no *NodeInfo) error { - iM, im, _, ie := splitVersion(ni.Version) - oM, om, _, oe := splitVersion(no.Version) + iM, im, _, ie := splitVersion(ni.Version.Tendermint) + oM, om, _, oe := splitVersion(no.Version.Tendermint) // if our own version number is not formatted right, we messed up if ie != nil { diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/state/priv_validator.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/types/priv_validator.go similarity index 89% rename from Godeps/_workspace/src/github.com/tendermint/tendermint/state/priv_validator.go rename to Godeps/_workspace/src/github.com/tendermint/tendermint/types/priv_validator.go index 1a9019bff8174ceefa58a0987270128e8ea943d7..aad8d118c9561fd4931e89b77f71fbef5036154b 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/state/priv_validator.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/types/priv_validator.go @@ -1,6 +1,7 @@ -package state +package types import ( + "bytes" "errors" "fmt" "io/ioutil" @@ -9,8 +10,6 @@ import ( acm "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/account" . "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/common" - . "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/consensus/types" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/types" "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/wire" "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/ed25519" @@ -23,11 +22,11 @@ const ( stepPrecommit = 3 ) -func voteToStep(vote *types.Vote) int8 { +func voteToStep(vote *Vote) int8 { switch vote.Type { - case types.VoteTypePrevote: + case VoteTypePrevote: return stepPrevote - case types.VoteTypePrecommit: + case VoteTypePrecommit: return stepPrecommit default: PanicSanity("Unknown vote type") @@ -104,7 +103,7 @@ func (privVal *PrivValidator) save() { } } -func (privVal *PrivValidator) SignVote(chainID string, vote *types.Vote) error { +func (privVal *PrivValidator) SignVote(chainID string, vote *Vote) error { privVal.mtx.Lock() defer privVal.mtx.Unlock() @@ -135,7 +134,7 @@ func (privVal *PrivValidator) SignVote(chainID string, vote *types.Vote) error { return nil } -func (privVal *PrivValidator) SignVoteUnsafe(chainID string, vote *types.Vote) { +func (privVal *PrivValidator) SignVoteUnsafe(chainID string, vote *Vote) { vote.Signature = privVal.PrivKey.Sign(acm.SignBytes(chainID, vote)).(acm.SignatureEd25519) } @@ -160,7 +159,7 @@ func (privVal *PrivValidator) SignProposal(chainID string, proposal *Proposal) e } } -func (privVal *PrivValidator) SignRebondTx(chainID string, rebondTx *types.RebondTx) error { +func (privVal *PrivValidator) SignRebondTx(chainID string, rebondTx *RebondTx) error { privVal.mtx.Lock() defer privVal.mtx.Unlock() if privVal.LastHeight < rebondTx.Height { @@ -183,3 +182,21 @@ func (privVal *PrivValidator) SignRebondTx(chainID string, rebondTx *types.Rebon func (privVal *PrivValidator) String() string { return fmt.Sprintf("PrivValidator{%X LH:%v, LR:%v, LS:%v}", privVal.Address, privVal.LastHeight, privVal.LastRound, privVal.LastStep) } + +//------------------------------------- + +type PrivValidatorsByAddress []*PrivValidator + +func (pvs PrivValidatorsByAddress) Len() int { + return len(pvs) +} + +func (pvs PrivValidatorsByAddress) Less(i, j int) bool { + return bytes.Compare(pvs[i].Address, pvs[j].Address) == -1 +} + +func (pvs PrivValidatorsByAddress) Swap(i, j int) { + it := pvs[i] + pvs[i] = pvs[j] + pvs[j] = it +} diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/consensus/types/proposal.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/types/proposal.go similarity index 84% rename from Godeps/_workspace/src/github.com/tendermint/tendermint/consensus/types/proposal.go rename to Godeps/_workspace/src/github.com/tendermint/tendermint/types/proposal.go index 5e9c508992c3dfdbb973a0c8fc9be3afd4b91be5..bebfc3a87b65097f316b22a35228365cdf0acfd8 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/consensus/types/proposal.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/types/proposal.go @@ -1,4 +1,4 @@ -package consensus +package types import ( "errors" @@ -7,7 +7,6 @@ import ( acm "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/account" . "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/common" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/types" "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/wire" ) @@ -19,12 +18,12 @@ var ( type Proposal struct { Height int `json:"height"` Round int `json:"round"` - BlockPartsHeader types.PartSetHeader `json:"block_parts_header"` + BlockPartsHeader PartSetHeader `json:"block_parts_header"` POLRound int `json:"pol_round"` // -1 if null. Signature acm.SignatureEd25519 `json:"signature"` } -func NewProposal(height int, round int, blockPartsHeader types.PartSetHeader, polRound int) *Proposal { +func NewProposal(height int, round int, blockPartsHeader PartSetHeader, polRound int) *Proposal { return &Proposal{ Height: height, Round: round, diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/consensus/types/proposal_test.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/types/proposal_test.go similarity index 83% rename from Godeps/_workspace/src/github.com/tendermint/tendermint/consensus/types/proposal_test.go rename to Godeps/_workspace/src/github.com/tendermint/tendermint/types/proposal_test.go index ccba09ad7a02d3acfdfef141920ff3135c2bc6e0..fb1e23c9ad00ee45cbbb4dfae92bac0ef9573cda 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/consensus/types/proposal_test.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/types/proposal_test.go @@ -1,4 +1,4 @@ -package consensus +package types import ( "testing" @@ -6,14 +6,13 @@ import ( acm "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/account" . "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/common" _ "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/config/tendermint_test" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/types" ) func TestProposalSignable(t *testing.T) { proposal := &Proposal{ Height: 12345, Round: 23456, - BlockPartsHeader: types.PartSetHeader{111, []byte("blockparts")}, + BlockPartsHeader: PartSetHeader{111, []byte("blockparts")}, POLRound: -1, } signBytes := acm.SignBytes(config.GetString("chain_id"), proposal) diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/types/tx.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/types/tx.go index cf9f611bcac76ea48d3919e336eb83ac449d5a20..ff2534e518f3e371fda0c96c0b23b53acfebbf0d 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/types/tx.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/types/tx.go @@ -5,6 +5,8 @@ import ( "errors" "io" + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/golang.org/x/crypto/ripemd160" + acm "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/account" . "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/common" ptypes "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/permission/types" @@ -20,10 +22,17 @@ var ( ErrTxUnknownPubKey = errors.New("Error unknown pubkey") ErrTxInvalidPubKey = errors.New("Error invalid pubkey") ErrTxInvalidSignature = errors.New("Error invalid signature") - ErrTxInvalidString = errors.New("Error invalid string") ErrTxPermissionDenied = errors.New("Error permission denied") ) +type ErrTxInvalidString struct { + Msg string +} + +func (e ErrTxInvalidString) Error() string { + return e.Msg +} + type ErrTxInvalidSequence struct { Got int Expected int @@ -189,6 +198,15 @@ func (tx *CallTx) String() string { return Fmt("CallTx{%v -> %x: %x}", tx.Input, tx.Address, tx.Data) } +func NewContractAddress(caller []byte, nonce int) []byte { + temp := make([]byte, 32+8) + copy(temp, caller) + PutInt64BE(temp[32:], int64(nonce)) + hasher := ripemd160.New() + hasher.Write(temp) // does not error + return hasher.Sum(nil) +} + //----------------------------------------------------------------------------- type NameTx struct { @@ -209,30 +227,26 @@ func (tx *NameTx) WriteSignBytes(chainID string, w io.Writer, n *int64, err *err func (tx *NameTx) ValidateStrings() error { if len(tx.Name) == 0 { - return errors.New("Name must not be empty") + return ErrTxInvalidString{"Name must not be empty"} } if len(tx.Name) > MaxNameLength { - return errors.New(Fmt("Name is too long. Max %d bytes", MaxNameLength)) + return ErrTxInvalidString{Fmt("Name is too long. Max %d bytes", MaxNameLength)} } if len(tx.Data) > MaxDataLength { - return errors.New(Fmt("Data is too long. Max %d bytes", MaxDataLength)) + return ErrTxInvalidString{Fmt("Data is too long. Max %d bytes", MaxDataLength)} } if !validateNameRegEntryName(tx.Name) { - return errors.New(Fmt("Invalid characters found in NameTx.Name (%s). Only alphanumeric, underscores, and forward slashes allowed", tx.Name)) + return ErrTxInvalidString{Fmt("Invalid characters found in NameTx.Name (%s). Only alphanumeric, underscores, dashes, forward slashes, and @ are allowed", tx.Name)} } if !validateNameRegEntryData(tx.Data) { - return errors.New(Fmt("Invalid characters found in NameTx.Data (%s). Only the kind of things found in a JSON file are allowed", tx.Data)) + return ErrTxInvalidString{Fmt("Invalid characters found in NameTx.Data (%s). Only the kind of things found in a JSON file are allowed", tx.Data)} } return nil } -func (tx *NameTx) BaseEntryCost() int64 { - return BaseEntryCost(tx.Name, tx.Data) -} - func (tx *NameTx) String() string { return Fmt("NameTx{%v -> %s: %s}", tx.Input, tx.Name, tx.Data) } diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/types/tx_test.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/types/tx_test.go index a15785cb4550d50c664fcecd8dc6ffeabe76df9c..ad6fb584919ce406376f8d834da45d8722b501e6 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/types/tx_test.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/types/tx_test.go @@ -92,9 +92,7 @@ func TestNameTxSignable(t *testing.T) { func TestBondTxSignable(t *testing.T) { privKeyBytes := make([]byte, 64) - var privKeyArray [64]byte - copy(privKeyArray[:], privKeyBytes) - privAccount := acm.GenPrivAccountFromPrivKeyBytes(&privKeyArray) + privAccount := acm.GenPrivAccountFromPrivKeyBytes(privKeyBytes) bondTx := &BondTx{ PubKey: privAccount.PubKey.(acm.PubKeyEd25519), Inputs: []*TxInput{ diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/state/validator.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/types/validator.go similarity index 95% rename from Godeps/_workspace/src/github.com/tendermint/tendermint/state/validator.go rename to Godeps/_workspace/src/github.com/tendermint/tendermint/types/validator.go index de34d407c409982462bcc70c5f9d7331e037cfd6..f6e347829f4716d8a317bee63a7d2fe9f38bef32 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/state/validator.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/types/validator.go @@ -1,4 +1,4 @@ -package state +package types import ( "bytes" @@ -7,7 +7,6 @@ import ( acm "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/account" . "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/common" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/types" "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/wire" ) @@ -15,7 +14,7 @@ import ( type ValidatorInfo struct { Address []byte `json:"address"` PubKey acm.PubKeyEd25519 `json:"pub_key"` - UnbondTo []*types.TxOutput `json:"unbond_to"` + UnbondTo []*TxOutput `json:"unbond_to"` FirstBondHeight int `json:"first_bond_height"` FirstBondAmount int64 `json:"first_bond_amount"` DestroyedHeight int `json:"destroyed_height"` // If destroyed diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/state/validator_set.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/types/validator_set.go similarity index 96% rename from Godeps/_workspace/src/github.com/tendermint/tendermint/state/validator_set.go rename to Godeps/_workspace/src/github.com/tendermint/tendermint/types/validator_set.go index 2b2a37dc5eaa8aa3385d4d6f799ff9d8045534bb..566dce4972edf531951f450c271cd934f350eca6 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/state/validator_set.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/types/validator_set.go @@ -1,4 +1,4 @@ -package state +package types import ( "bytes" @@ -9,7 +9,6 @@ import ( "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/account" . "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/common" "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/merkle" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/types" ) // ValidatorSet represent a set of *Validator at a given height. @@ -204,7 +203,7 @@ func (valSet *ValidatorSet) Iterate(fn func(index int, val *Validator) bool) { // Verify that +2/3 of the set had signed the given signBytes func (valSet *ValidatorSet) VerifyValidation(chainID string, - hash []byte, parts types.PartSetHeader, height int, v *types.Validation) error { + hash []byte, parts PartSetHeader, height int, v *Validation) error { if valSet.Size() != len(v.Precommits) { return fmt.Errorf("Invalid validation -- wrong set size: %v vs %v", valSet.Size(), len(v.Precommits)) } @@ -226,7 +225,7 @@ func (valSet *ValidatorSet) VerifyValidation(chainID string, if precommit.Round != round { return fmt.Errorf("Invalid validation -- wrong round: %v vs %v", round, precommit.Round) } - if precommit.Type != types.VoteTypePrecommit { + if precommit.Type != VoteTypePrecommit { return fmt.Errorf("Invalid validation -- not precommit @ index %v", idx) } _, val := valSet.GetByIndex(idx) @@ -238,7 +237,7 @@ func (valSet *ValidatorSet) VerifyValidation(chainID string, if !bytes.Equal(precommit.BlockHash, hash) { continue // Not an error, but doesn't count } - if !parts.Equals(precommit.BlockParts) { + if !parts.Equals(precommit.BlockPartsHeader) { continue // Not an error, but doesn't count } // Good precommit! diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/state/validator_set_test.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/types/validator_set_test.go similarity index 99% rename from Godeps/_workspace/src/github.com/tendermint/tendermint/state/validator_set_test.go rename to Godeps/_workspace/src/github.com/tendermint/tendermint/types/validator_set_test.go index 82b593bb77055ac1995a84669111126c5a019dee..3d5d01b1d0930b87fa513d26647fac3c28a03a5c 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/state/validator_set_test.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/types/validator_set_test.go @@ -1,4 +1,4 @@ -package state +package types import ( "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/account" diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/types/vote.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/types/vote.go index 776ab7d2a461e80f958200db517935857b4be2a2..be6fbbef97c53434f4140dd15bd1194b20f12520 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/types/vote.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/types/vote.go @@ -28,12 +28,12 @@ func (err *ErrVoteConflictingSignature) Error() string { // Represents a prevote, precommit, or commit vote from validators for consensus. type Vote struct { - Height int `json:"height"` - Round int `json:"round"` - Type byte `json:"type"` - BlockHash []byte `json:"block_hash"` // empty if vote is nil. - BlockParts PartSetHeader `json:"block_parts"` // zero if vote is nil. - Signature acm.SignatureEd25519 `json:"signature"` + Height int `json:"height"` + Round int `json:"round"` + Type byte `json:"type"` + BlockHash []byte `json:"block_hash"` // empty if vote is nil. + BlockPartsHeader PartSetHeader `json:"block_parts_header"` // zero if vote is nil. + Signature acm.SignatureEd25519 `json:"signature"` } // Types of votes @@ -44,7 +44,7 @@ const ( func (vote *Vote) WriteSignBytes(chainID string, w io.Writer, n *int64, err *error) { wire.WriteTo([]byte(Fmt(`{"chain_id":"%s"`, chainID)), w, n, err) - wire.WriteTo([]byte(Fmt(`,"vote":{"block_hash":"%X","block_parts":%v`, vote.BlockHash, vote.BlockParts)), w, n, err) + wire.WriteTo([]byte(Fmt(`,"vote":{"block_hash":"%X","block_parts_header":%v`, vote.BlockHash, vote.BlockPartsHeader)), w, n, err) wire.WriteTo([]byte(Fmt(`,"height":%v,"round":%v,"type":%v}}`, vote.Height, vote.Round, vote.Type)), w, n, err) } @@ -67,7 +67,7 @@ func (vote *Vote) String() string { PanicSanity("Unknown vote type") } - return fmt.Sprintf("Vote{%v/%02d/%v(%v) %X#%v %v}", vote.Height, vote.Round, vote.Type, typeString, Fingerprint(vote.BlockHash), vote.BlockParts, vote.Signature) + return fmt.Sprintf("Vote{%v/%02d/%v(%v) %X#%v %v}", vote.Height, vote.Round, vote.Type, typeString, Fingerprint(vote.BlockHash), vote.BlockPartsHeader, vote.Signature) } //-------------------------------------------------------------------------------- diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/consensus/vote_set.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/types/vote_set.go similarity index 69% rename from Godeps/_workspace/src/github.com/tendermint/tendermint/consensus/vote_set.go rename to Godeps/_workspace/src/github.com/tendermint/tendermint/types/vote_set.go index aebcd6434f18e3a42eb76effc76726a9cb103708..a1c551e9202f7b7fcf16fdaadd8b42ab143c7f5e 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/consensus/vote_set.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/types/vote_set.go @@ -1,4 +1,4 @@ -package consensus +package types import ( "bytes" @@ -8,8 +8,6 @@ import ( acm "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/account" . "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/common" - sm "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/state" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/types" "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/wire" ) @@ -23,19 +21,19 @@ type VoteSet struct { round int type_ byte - mtx sync.Mutex - valSet *sm.ValidatorSet - votes []*types.Vote // validator index -> vote - votesBitArray *BitArray // validator index -> has vote? - votesByBlock map[string]int64 // string(blockHash)+string(blockParts) -> vote sum. - totalVotes int64 - maj23Hash []byte - maj23Parts types.PartSetHeader - maj23Exists bool + mtx sync.Mutex + valSet *ValidatorSet + votes []*Vote // validator index -> vote + votesBitArray *BitArray // validator index -> has vote? + votesByBlock map[string]int64 // string(blockHash)+string(blockParts) -> vote sum. + totalVotes int64 + maj23Hash []byte + maj23PartsHeader PartSetHeader + maj23Exists bool } // Constructs a new VoteSet struct used to accumulate votes for given height/round. -func NewVoteSet(height int, round int, type_ byte, valSet *sm.ValidatorSet) *VoteSet { +func NewVoteSet(height int, round int, type_ byte, valSet *ValidatorSet) *VoteSet { if height == 0 { PanicSanity("Cannot make VoteSet for height == 0, doesn't make sense.") } @@ -44,7 +42,7 @@ func NewVoteSet(height int, round int, type_ byte, valSet *sm.ValidatorSet) *Vot round: round, type_: type_, valSet: valSet, - votes: make([]*types.Vote, valSet.Size()), + votes: make([]*Vote, valSet.Size()), votesBitArray: NewBitArray(valSet.Size()), votesByBlock: make(map[string]int64), totalVotes: 0, @@ -61,7 +59,7 @@ func (voteSet *VoteSet) Height() int { func (voteSet *VoteSet) Round() int { if voteSet == nil { - return 0 + return -1 } else { return voteSet.round } @@ -87,7 +85,7 @@ func (voteSet *VoteSet) Size() int { // Otherwise returns err=ErrVote[UnexpectedStep|InvalidAccount|InvalidSignature|InvalidBlockHash|ConflictingSignature] // Duplicate votes return added=false, err=nil. // NOTE: vote should not be mutated after adding. -func (voteSet *VoteSet) AddByIndex(valIndex int, vote *types.Vote) (added bool, index int, err error) { +func (voteSet *VoteSet) AddByIndex(valIndex int, vote *Vote) (added bool, address []byte, err error) { voteSet.mtx.Lock() defer voteSet.mtx.Unlock() @@ -98,42 +96,43 @@ func (voteSet *VoteSet) AddByIndex(valIndex int, vote *types.Vote) (added bool, // Otherwise returns err=ErrVote[UnexpectedStep|InvalidAccount|InvalidSignature|InvalidBlockHash|ConflictingSignature] // Duplicate votes return added=false, err=nil. // NOTE: vote should not be mutated after adding. -func (voteSet *VoteSet) AddByAddress(address []byte, vote *types.Vote) (added bool, index int, err error) { +func (voteSet *VoteSet) AddByAddress(address []byte, vote *Vote) (added bool, index int, err error) { voteSet.mtx.Lock() defer voteSet.mtx.Unlock() // Ensure that signer is a validator. valIndex, val := voteSet.valSet.GetByAddress(address) if val == nil { - return false, 0, types.ErrVoteInvalidAccount + return false, 0, ErrVoteInvalidAccount } return voteSet.addVote(val, valIndex, vote) } -func (voteSet *VoteSet) addByIndex(valIndex int, vote *types.Vote) (bool, int, error) { +func (voteSet *VoteSet) addByIndex(valIndex int, vote *Vote) (added bool, address []byte, err error) { // Ensure that signer is a validator. - _, val := voteSet.valSet.GetByIndex(valIndex) + address, val := voteSet.valSet.GetByIndex(valIndex) if val == nil { - return false, 0, types.ErrVoteInvalidAccount + return false, nil, ErrVoteInvalidAccount } - return voteSet.addVote(val, valIndex, vote) + added, _, err = voteSet.addVote(val, valIndex, vote) + return } -func (voteSet *VoteSet) addVote(val *sm.Validator, valIndex int, vote *types.Vote) (bool, int, error) { +func (voteSet *VoteSet) addVote(val *Validator, valIndex int, vote *Vote) (bool, int, error) { // Make sure the step matches. (or that vote is commit && round < voteSet.round) if (vote.Height != voteSet.height) || (vote.Round != voteSet.round) || (vote.Type != voteSet.type_) { - return false, 0, types.ErrVoteUnexpectedStep + return false, 0, ErrVoteUnexpectedStep } // Check signature. if !val.PubKey.VerifyBytes(acm.SignBytes(config.GetString("chain_id"), vote), vote.Signature) { // Bad signature. - return false, 0, types.ErrVoteInvalidSignature + return false, 0, ErrVoteInvalidSignature } // If vote already exists, return false. @@ -141,7 +140,7 @@ func (voteSet *VoteSet) addVote(val *sm.Validator, valIndex int, vote *types.Vot if bytes.Equal(existingVote.BlockHash, vote.BlockHash) { return false, valIndex, nil } else { - return false, valIndex, &types.ErrVoteConflictingSignature{ + return false, valIndex, &ErrVoteConflictingSignature{ VoteA: existingVote, VoteB: vote, } @@ -151,7 +150,7 @@ func (voteSet *VoteSet) addVote(val *sm.Validator, valIndex int, vote *types.Vot // Add vote. voteSet.votes[valIndex] = vote voteSet.votesBitArray.SetIndex(valIndex, true) - blockKey := string(vote.BlockHash) + string(wire.BinaryBytes(vote.BlockParts)) + blockKey := string(vote.BlockHash) + string(wire.BinaryBytes(vote.BlockPartsHeader)) totalBlockHashVotes := voteSet.votesByBlock[blockKey] + val.VotingPower voteSet.votesByBlock[blockKey] = totalBlockHashVotes voteSet.totalVotes += val.VotingPower @@ -160,7 +159,7 @@ func (voteSet *VoteSet) addVote(val *sm.Validator, valIndex int, vote *types.Vot if totalBlockHashVotes > voteSet.valSet.TotalVotingPower()*2/3 && (totalBlockHashVotes-val.VotingPower) <= voteSet.valSet.TotalVotingPower()*2/3 { voteSet.maj23Hash = vote.BlockHash - voteSet.maj23Parts = vote.BlockParts + voteSet.maj23PartsHeader = vote.BlockPartsHeader voteSet.maj23Exists = true } @@ -176,13 +175,13 @@ func (voteSet *VoteSet) BitArray() *BitArray { return voteSet.votesBitArray.Copy() } -func (voteSet *VoteSet) GetByIndex(valIndex int) *types.Vote { +func (voteSet *VoteSet) GetByIndex(valIndex int) *Vote { voteSet.mtx.Lock() defer voteSet.mtx.Unlock() return voteSet.votes[valIndex] } -func (voteSet *VoteSet) GetByAddress(address []byte) *types.Vote { +func (voteSet *VoteSet) GetByAddress(address []byte) *Vote { voteSet.mtx.Lock() defer voteSet.mtx.Unlock() valIndex, val := voteSet.valSet.GetByAddress(address) @@ -221,13 +220,13 @@ func (voteSet *VoteSet) HasTwoThirdsAny() bool { // Returns either a blockhash (or nil) that received +2/3 majority. // If there exists no such majority, returns (nil, false). -func (voteSet *VoteSet) TwoThirdsMajority() (hash []byte, parts types.PartSetHeader, ok bool) { +func (voteSet *VoteSet) TwoThirdsMajority() (hash []byte, parts PartSetHeader, ok bool) { voteSet.mtx.Lock() defer voteSet.mtx.Unlock() if voteSet.maj23Exists { - return voteSet.maj23Hash, voteSet.maj23Parts, true + return voteSet.maj23Hash, voteSet.maj23PartsHeader, true } else { - return nil, types.PartSetHeader{}, false + return nil, PartSetHeader{}, false } } @@ -271,17 +270,17 @@ func (voteSet *VoteSet) StringShort() string { //-------------------------------------------------------------------------------- // Validation -func (voteSet *VoteSet) MakeValidation() *types.Validation { - if voteSet.type_ != types.VoteTypePrecommit { - PanicSanity("Cannot MakeValidation() unless VoteSet.Type is types.VoteTypePrecommit") +func (voteSet *VoteSet) MakeValidation() *Validation { + if voteSet.type_ != VoteTypePrecommit { + PanicSanity("Cannot MakeValidation() unless VoteSet.Type is VoteTypePrecommit") } voteSet.mtx.Lock() defer voteSet.mtx.Unlock() if len(voteSet.maj23Hash) == 0 { PanicSanity("Cannot MakeValidation() unless a blockhash has +2/3") } - precommits := make([]*types.Vote, voteSet.valSet.Size()) - voteSet.valSet.Iterate(func(valIndex int, val *sm.Validator) bool { + precommits := make([]*Vote, voteSet.valSet.Size()) + voteSet.valSet.Iterate(func(valIndex int, val *Validator) bool { vote := voteSet.votes[valIndex] if vote == nil { return false @@ -289,13 +288,46 @@ func (voteSet *VoteSet) MakeValidation() *types.Validation { if !bytes.Equal(vote.BlockHash, voteSet.maj23Hash) { return false } - if !vote.BlockParts.Equals(voteSet.maj23Parts) { + if !vote.BlockPartsHeader.Equals(voteSet.maj23PartsHeader) { return false } precommits[valIndex] = vote return false }) - return &types.Validation{ + return &Validation{ Precommits: precommits, } } + +//-------------------------------------------------------------------------------- +// For testing... + +func RandValidator(randBonded bool, minBonded int64) (*ValidatorInfo, *Validator, *PrivValidator) { + privVal := GenPrivValidator() + _, tempFilePath := Tempfile("priv_validator_") + privVal.SetFile(tempFilePath) + bonded := minBonded + if randBonded { + bonded += int64(RandUint32()) + } + valInfo := &ValidatorInfo{ + Address: privVal.Address, + PubKey: privVal.PubKey, + UnbondTo: []*TxOutput{&TxOutput{ + Amount: bonded, + Address: privVal.Address, + }}, + FirstBondHeight: 0, + FirstBondAmount: bonded, + } + val := &Validator{ + Address: valInfo.Address, + PubKey: valInfo.PubKey, + BondHeight: 0, + UnbondHeight: 0, + LastCommitHeight: 0, + VotingPower: valInfo.FirstBondAmount, + Accum: 0, + } + return valInfo, val, privVal +} diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/consensus/vote_set_test.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/types/vote_set_test.go similarity index 70% rename from Godeps/_workspace/src/github.com/tendermint/tendermint/consensus/vote_set_test.go rename to Godeps/_workspace/src/github.com/tendermint/tendermint/types/vote_set_test.go index 896e386928a9366b7df0d66483f79b96b844d9d4..10a42f31e67c964fa91075945f7550e9b25fd59c 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/consensus/vote_set_test.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/types/vote_set_test.go @@ -1,55 +1,65 @@ -package consensus +package types import ( "bytes" + "sort" . "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/common" . "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/common/test" _ "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/config/tendermint_test" - sm "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/state" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/types" "testing" ) -// NOTE: see consensus/test.go for common test methods. +func randVoteSet(height int, round int, type_ byte, numValidators int, votingPower int64) (*VoteSet, *ValidatorSet, []*PrivValidator) { + vals := make([]*Validator, numValidators) + privValidators := make([]*PrivValidator, numValidators) + for i := 0; i < numValidators; i++ { + _, val, privValidator := RandValidator(false, votingPower) + vals[i] = val + privValidators[i] = privValidator + } + valSet := NewValidatorSet(vals) + sort.Sort(PrivValidatorsByAddress(privValidators)) + return NewVoteSet(height, round, type_, valSet), valSet, privValidators +} // Convenience: Return new vote with different height -func withHeight(vote *types.Vote, height int) *types.Vote { +func withHeight(vote *Vote, height int) *Vote { vote = vote.Copy() vote.Height = height return vote } // Convenience: Return new vote with different round -func withRound(vote *types.Vote, round int) *types.Vote { +func withRound(vote *Vote, round int) *Vote { vote = vote.Copy() vote.Round = round return vote } // Convenience: Return new vote with different type -func withType(vote *types.Vote, type_ byte) *types.Vote { +func withType(vote *Vote, type_ byte) *Vote { vote = vote.Copy() vote.Type = type_ return vote } // Convenience: Return new vote with different blockHash -func withBlockHash(vote *types.Vote, blockHash []byte) *types.Vote { +func withBlockHash(vote *Vote, blockHash []byte) *Vote { vote = vote.Copy() vote.BlockHash = blockHash return vote } // Convenience: Return new vote with different blockParts -func withBlockParts(vote *types.Vote, blockParts types.PartSetHeader) *types.Vote { +func withBlockPartsHeader(vote *Vote, blockPartsHeader PartSetHeader) *Vote { vote = vote.Copy() - vote.BlockParts = blockParts + vote.BlockPartsHeader = blockPartsHeader return vote } -func signAddVote(privVal *sm.PrivValidator, vote *types.Vote, voteSet *VoteSet) (bool, error) { +func signAddVote(privVal *PrivValidator, vote *Vote, voteSet *VoteSet) (bool, error) { privVal.SignVoteUnsafe(config.GetString("chain_id"), vote) added, _, err := voteSet.AddByAddress(privVal.Address, vote) return added, err @@ -57,7 +67,7 @@ func signAddVote(privVal *sm.PrivValidator, vote *types.Vote, voteSet *VoteSet) func TestAddVote(t *testing.T) { height, round := 1, 0 - voteSet, _, privValidators := randVoteSet(height, round, types.VoteTypePrevote, 10, 1) + voteSet, _, privValidators := randVoteSet(height, round, VoteTypePrevote, 10, 1) val0 := privValidators[0] // t.Logf(">> %v", voteSet) @@ -73,7 +83,7 @@ func TestAddVote(t *testing.T) { t.Errorf("There should be no 2/3 majority") } - vote := &types.Vote{Height: height, Round: round, Type: types.VoteTypePrevote, BlockHash: nil} + vote := &Vote{Height: height, Round: round, Type: VoteTypePrevote, BlockHash: nil} signAddVote(val0, vote, voteSet) if voteSet.GetByAddress(val0.Address) == nil { @@ -90,9 +100,9 @@ func TestAddVote(t *testing.T) { func Test2_3Majority(t *testing.T) { height, round := 1, 0 - voteSet, _, privValidators := randVoteSet(height, round, types.VoteTypePrevote, 10, 1) + voteSet, _, privValidators := randVoteSet(height, round, VoteTypePrevote, 10, 1) - vote := &types.Vote{Height: height, Round: round, Type: types.VoteTypePrevote, BlockHash: nil} + vote := &Vote{Height: height, Round: round, Type: VoteTypePrevote, BlockHash: nil} // 6 out of 10 voted for nil. for i := 0; i < 6; i++ { @@ -124,13 +134,13 @@ func Test2_3Majority(t *testing.T) { func Test2_3MajorityRedux(t *testing.T) { height, round := 1, 0 - voteSet, _, privValidators := randVoteSet(height, round, types.VoteTypePrevote, 100, 1) + voteSet, _, privValidators := randVoteSet(height, round, VoteTypePrevote, 100, 1) blockHash := CRandBytes(32) blockPartsTotal := 123 - blockParts := types.PartSetHeader{blockPartsTotal, CRandBytes(32)} + blockPartsHeader := PartSetHeader{blockPartsTotal, CRandBytes(32)} - vote := &types.Vote{Height: height, Round: round, Type: types.VoteTypePrevote, BlockHash: blockHash, BlockParts: blockParts} + vote := &Vote{Height: height, Round: round, Type: VoteTypePrevote, BlockHash: blockHash, BlockPartsHeader: blockPartsHeader} // 66 out of 100 voted for nil. for i := 0; i < 66; i++ { @@ -152,8 +162,8 @@ func Test2_3MajorityRedux(t *testing.T) { // 68th validator voted for a different BlockParts PartSetHeader { - blockParts := types.PartSetHeader{blockPartsTotal, CRandBytes(32)} - signAddVote(privValidators[67], withBlockParts(vote, blockParts), voteSet) + blockPartsHeader := PartSetHeader{blockPartsTotal, CRandBytes(32)} + signAddVote(privValidators[67], withBlockPartsHeader(vote, blockPartsHeader), voteSet) hash, header, ok = voteSet.TwoThirdsMajority() if hash != nil || !header.IsZero() || ok { t.Errorf("There should be no 2/3 majority: last vote added had different PartSetHeader Hash") @@ -162,8 +172,8 @@ func Test2_3MajorityRedux(t *testing.T) { // 69th validator voted for different BlockParts Total { - blockParts := types.PartSetHeader{blockPartsTotal + 1, blockParts.Hash} - signAddVote(privValidators[68], withBlockParts(vote, blockParts), voteSet) + blockPartsHeader := PartSetHeader{blockPartsTotal + 1, blockPartsHeader.Hash} + signAddVote(privValidators[68], withBlockPartsHeader(vote, blockPartsHeader), voteSet) hash, header, ok = voteSet.TwoThirdsMajority() if hash != nil || !header.IsZero() || ok { t.Errorf("There should be no 2/3 majority: last vote added had different PartSetHeader Total") @@ -179,11 +189,11 @@ func Test2_3MajorityRedux(t *testing.T) { } } - // 71st validator voted for the right BlockHash & BlockParts + // 71st validator voted for the right BlockHash & BlockPartsHeader { signAddVote(privValidators[70], vote, voteSet) hash, header, ok = voteSet.TwoThirdsMajority() - if !bytes.Equal(hash, blockHash) || !header.Equals(blockParts) || !ok { + if !bytes.Equal(hash, blockHash) || !header.Equals(blockPartsHeader) || !ok { t.Errorf("There should be 2/3 majority") } } @@ -191,10 +201,10 @@ func Test2_3MajorityRedux(t *testing.T) { func TestBadVotes(t *testing.T) { height, round := 1, 0 - voteSet, _, privValidators := randVoteSet(height, round, types.VoteTypePrevote, 10, 1) + voteSet, _, privValidators := randVoteSet(height, round, VoteTypePrevote, 10, 1) // val0 votes for nil. - vote := &types.Vote{Height: height, Round: round, Type: types.VoteTypePrevote, BlockHash: nil} + vote := &Vote{Height: height, Round: round, Type: VoteTypePrevote, BlockHash: nil} added, err := signAddVote(privValidators[0], vote, voteSet) if !added || err != nil { t.Errorf("Expected VoteSet.Add to succeed") @@ -219,7 +229,7 @@ func TestBadVotes(t *testing.T) { } // val3 votes of another type. - added, err = signAddVote(privValidators[3], withType(vote, types.VoteTypePrecommit), voteSet) + added, err = signAddVote(privValidators[3], withType(vote, VoteTypePrecommit), voteSet) if added { t.Errorf("Expected VoteSet.Add to fail, wrong type") } @@ -227,11 +237,11 @@ func TestBadVotes(t *testing.T) { func TestMakeValidation(t *testing.T) { height, round := 1, 0 - voteSet, _, privValidators := randVoteSet(height, round, types.VoteTypePrecommit, 10, 1) - blockHash, blockParts := CRandBytes(32), types.PartSetHeader{123, CRandBytes(32)} + voteSet, _, privValidators := randVoteSet(height, round, VoteTypePrecommit, 10, 1) + blockHash, blockPartsHeader := CRandBytes(32), PartSetHeader{123, CRandBytes(32)} - vote := &types.Vote{Height: height, Round: round, Type: types.VoteTypePrecommit, - BlockHash: blockHash, BlockParts: blockParts} + vote := &Vote{Height: height, Round: round, Type: VoteTypePrecommit, + BlockHash: blockHash, BlockPartsHeader: blockPartsHeader} // 6 out of 10 voted for some block. for i := 0; i < 6; i++ { @@ -244,7 +254,7 @@ func TestMakeValidation(t *testing.T) { // 7th voted for some other block. { vote := withBlockHash(vote, RandBytes(32)) - vote = withBlockParts(vote, types.PartSetHeader{123, RandBytes(32)}) + vote = withBlockPartsHeader(vote, PartSetHeader{123, RandBytes(32)}) signAddVote(privValidators[6], vote, voteSet) } diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/native.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/native.go index e0a73bd6c5e848b6a60309da312ed3c6e7cd67e7..e5fd2def190db4a1ce83356c6b8ec587c8ffea0a 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/native.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/native.go @@ -4,8 +4,6 @@ import ( "crypto/sha256" "github.com/eris-ltd/eris-db/Godeps/_workspace/src/code.google.com/p/go.crypto/ripemd160" . "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/common" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/sha3" ) var registeredNativeContracts = make(map[Word256]NativeContract) @@ -15,13 +13,22 @@ func RegisteredNativeContract(addr Word256) bool { return ok } +func RegisterNativeContract(addr Word256, fn NativeContract) bool { + _, exists := registeredNativeContracts[addr] + if exists { + return false + } + registeredNativeContracts[addr] = fn + return true +} + func init() { registerNativeContracts() registerSNativeContracts() } func registerNativeContracts() { - registeredNativeContracts[Int64ToWord256(1)] = ecrecoverFunc + // registeredNativeContracts[Int64ToWord256(1)] = ecrecoverFunc registeredNativeContracts[Int64ToWord256(2)] = sha256Func registeredNativeContracts[Int64ToWord256(3)] = ripemd160Func registeredNativeContracts[Int64ToWord256(4)] = identityFunc @@ -31,6 +38,7 @@ func registerNativeContracts() { type NativeContract func(appState AppState, caller *Account, input []byte, gas *int64) (output []byte, err error) +/* Removed due to C dependency func ecrecoverFunc(appState AppState, caller *Account, input []byte, gas *int64) (output []byte, err error) { // Deduct gas gasRequired := GasEcRecover @@ -51,6 +59,7 @@ func ecrecoverFunc(appState AppState, caller *Account, input []byte, gas *int64) hashed := sha3.Sha3(recovered[1:]) return LeftPadBytes(hashed, 32), nil } +*/ func sha256Func(appState AppState, caller *Account, input []byte, gas *int64) (output []byte, err error) { // Deduct gas diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/.gitignore b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/.gitignore deleted file mode 100644 index 802b6744a1d9fb2b9711384aca36a8790bae7f0f..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/.gitignore +++ /dev/null @@ -1,24 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe - -*~ diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/README.md b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/README.md deleted file mode 100644 index 5a86147d4856306b8c40a28831fb444476d5ffec..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/README.md +++ /dev/null @@ -1,25 +0,0 @@ -secp256k1-go -======= - -golang secp256k1 library - -Implements cryptographic operations for the secp256k1 ECDSA curve used by Bitcoin. - -Installing -=== - -GMP library headers are required to build. On Debian-based systems, the package is called `libgmp-dev`. - -``` -sudo apt-get install libgmp-dev -``` - -Now compiles with cgo! - -Test -=== - -To run tests do -``` -go tests -``` \ No newline at end of file diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/notes.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/notes.go deleted file mode 100644 index 7ed16caabce99a0a4e2e5991117dff631e081502..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/notes.go +++ /dev/null @@ -1,192 +0,0 @@ -package secp256k1 - -/* -<HaltingState> sipa, int secp256k1_ecdsa_pubkey_create(unsigned char *pubkey, int *pubkeylen, const unsigned char *seckey, int compressed); -<HaltingState> is that how i generate private/public keys? -<sipa> HaltingState: you pass in a random 32-byte string as seckey -<sipa> HaltingState: if it is valid, the corresponding pubkey is put in pubkey -<sipa> and true is returned -<sipa> otherwise, false is returned -<sipa> around 1 in 2^128 32-byte strings are invalid, so the odds of even ever seeing one is extremely rare - -<sipa> private keys are mathematically numbers -<sipa> each has a corresponding point on the curve as public key -<sipa> a private key is just a number -<sipa> a public key is a point with x/y coordinates -<sipa> almost every 256-bit number is a valid private key (one with a point on the curve corresponding to it) -<sipa> HaltingState: ok? - -<sipa> more than half of random points are not on the curve -<sipa> and actually, it is less than the square root, not less than half, sorry :) -!!! -<sipa> a private key is a NUMBER -<sipa> a public key is a POINT -<gmaxwell> half the x,y values in the field are not on the curve, a private key is an integer. - -<sipa> HaltingState: yes, n,q = private keys; N,Q = corresponding public keys (N=n*G, Q=q*G); then it follows that n*Q = n*q*G = q*n*G = q*N -<sipa> that's the reason ECDH works -<sipa> multiplication is associative and commutativ -*/ - -/* -<HaltingState> sipa, ok; i am doing compact signatures and I want to know; can someone change the signature to get another valid signature for same message without the private key -<HaltingState> because i know they can do that for the normal 72 byte signatures that openssl was putting out -<sipa> HaltingState: if you don't enforce non-malleability, yes -<sipa> HaltingState: if you force the highest bit of t - -<sipa> it _creates_ signatures that already satisfy that condition -<sipa> but it will accept ones that don't -<sipa> maybe i should change that, and be strict -<HaltingState> yes; i want some way to know signature is valid but fails malleability -<sipa> well if the highest bit of S is 1, you can take its complement -<sipa> and end up with a valid signature -<sipa> that is canonical -*/ - -/* - -<HaltingState> sipa, I am signing messages and highest bit of the compact signature is 1!!! -<HaltingState> if (b & 0x80) == 0x80 { -<HaltingState> log.Panic("b= %v b2= %v \n", b, b&0x80) -<HaltingState> } -<sipa> what bit? -* Pengoo has quit (Ping timeout: 272 seconds) -<HaltingState> the highest bit of the first byte of signature -<sipa> it's the highest bit of S -<sipa> so the 32nd byte -<HaltingState> wtf - -*/ - -/* - For instance, nonces are used in HTTP digest access authentication to calculate an MD5 digest - of the password. The nonces are different each time the 401 authentication challenge - response code is presented, thus making replay attacks virtually impossible. - -can verify client/server match without sending password over network -*/ - -/* -<hanihani> one thing I dont get about armory for instance, -is how the hot-wallet can generate new addresses without -knowing the master key -*/ - -/* -<HaltingState> i am yelling at the telehash people for using secp256r1 -instead of secp256k1; they thing r1 is "more secure" despite fact that -there is no implementation that works and wrapping it is now taking -up massive time, lol -<gmaxwell> ... - -<gmaxwell> You know that the *r curves are selected via an undisclosed -secret process, right? -<gmaxwell> HaltingState: telehash is offtopic for this channel. -*/ -/* - For instance, nonces are used in HTTP digest access authentication to calculate an MD5 digest - of the password. The nonces are different each time the 401 authentication challenge - response code is presented, thus making replay attacks virtually impossible. - -can verify client/server match without sending password over network -*/ - -/* -void secp256k1_start(void); -void secp256k1_stop(void); - - * Verify an ECDSA signature. - * Returns: 1: correct signature - * 0: incorrect signature - * -1: invalid public key - * -2: invalid signature - * -int secp256k1_ecdsa_verify(const unsigned char *msg, int msglen, - const unsigned char *sig, int siglen, - const unsigned char *pubkey, int pubkeylen); - -http://www.nilsschneider.net/2013/01/28/recovering-bitcoin-private-keys.html - -Why did this work? ECDSA requires a random number for each signature. If this random -number is ever used twice with the same private key it can be recovered. -This transaction was generated by a hardware bitcoin wallet using a pseudo-random number -generator that was returning the same “random†number every time. - -Nonce is 32 bytes? - - * 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). - * -int secp256k1_ecdsa_sign(const unsigned char *msg, int msglen, - unsigned char *sig, int *siglen, - const unsigned char *seckey, - const unsigned char *nonce); - - - * 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); - - * 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. - * - -recovery id is between 0 and 3 - -int secp256k1_ecdsa_recover_compact(const unsigned char *msg, int msglen, - const unsigned char *sig64, - unsigned char *pubkey, int *pubkeylen, - int compressed, int recid); - - - * 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 - * -int secp256k1_ecdsa_seckey_verify(const unsigned char *seckey); - -** Just validate a public key. - * Returns: 1: valid public key - * 0: invalid public key - * -int secp256k1_ecdsa_pubkey_verify(const unsigned char *pubkey, int pubkeylen); - -** 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. - * -int secp256k1_ecdsa_pubkey_create(unsigned char *pubkey, int *pubkeylen, const unsigned char *seckey, int compressed); -*/ diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256.go deleted file mode 100644 index 04c3f84c83f9e39b8e11603af61068fd38ffd593..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256.go +++ /dev/null @@ -1,248 +0,0 @@ -package secp256k1 - -// TODO: set USE_SCALAR_4X64 depending on platform? - -/* -#cgo CFLAGS: -I./secp256k1 -#cgo darwin CFLAGS: -I/usr/local/include -#cgo linux,arm CFLAGS: -I/usr/local/arm/include -#cgo LDFLAGS: -lgmp -#cgo darwin LDFLAGS: -L/usr/local/lib -#cgo linux,arm LDFLAGS: -L/usr/local/arm/lib -#define USE_NUM_GMP -#define USE_FIELD_10X26 -#define USE_FIELD_INV_BUILTIN -#define USE_SCALAR_8X32 -#define USE_SCALAR_INV_BUILTIN -#define NDEBUG -#include "./secp256k1/src/secp256k1.c" -*/ -import "C" - -import ( - "bytes" - "errors" - "unsafe" - - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/randentropy" -) - -//#define USE_FIELD_5X64 - -/* - Todo: - > Centralize key management in module - > add pubkey/private key struct - > Dont let keys leave module; address keys as ints - - > store private keys in buffer and shuffle (deters persistance on swap disc) - > Byte permutation (changing) - > xor with chaning random block (to deter scanning memory for 0x63) (stream cipher?) - - On Disk - > Store keys in wallets - > use slow key derivation function for wallet encryption key (2 seconds) -*/ - -func init() { - //takes 10ms to 100ms - C.secp256k1_start(3) // SECP256K1_START_SIGN | SECP256K1_START_VERIFY -} - -func Stop() { - C.secp256k1_stop() -} - -func GenerateKeyPair() ([]byte, []byte) { - - pubkey_len := C.int(65) - const seckey_len = 32 - - var pubkey []byte = make([]byte, pubkey_len) - var seckey []byte = randentropy.GetEntropyCSPRNG(seckey_len) - - 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_ec_pubkey_create( - pubkey_ptr, &pubkey_len, - seckey_ptr, 0) - - if ret != C.int(1) { - return GenerateKeyPair() //invalid secret, try again - } - return pubkey, seckey -} - -func GeneratePubKey(seckey []byte) ([]byte, error) { - if err := VerifySeckeyValidity(seckey); err != nil { - return nil, err - } - - pubkey_len := C.int(65) - const seckey_len = 32 - - var pubkey []byte = make([]byte, pubkey_len) - - 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_ec_pubkey_create( - pubkey_ptr, &pubkey_len, - seckey_ptr, 0) - - if ret != C.int(1) { - return nil, errors.New("Unable to generate pubkey from seckey") - } - - return pubkey, nil -} - -func Sign(msg []byte, seckey []byte) ([]byte, error) { - nonce := randentropy.GetEntropyCSPRNG(32) - - var sig []byte = make([]byte, 65) - var recid C.int - - var msg_ptr *C.uchar = (*C.uchar)(unsafe.Pointer(&msg[0])) - var sig_ptr *C.uchar = (*C.uchar)(unsafe.Pointer(&sig[0])) - var seckey_ptr *C.uchar = (*C.uchar)(unsafe.Pointer(&seckey[0])) - - 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, - sig_ptr, - seckey_ptr, - noncefp_ptr, - ndata_ptr, - &recid) - - sig[64] = byte(int(recid)) - - if ret != C.int(1) { - // nonce invalid, retry - return Sign(msg, seckey) - } - - return sig, nil - -} - -func VerifySeckeyValidity(seckey []byte) error { - if len(seckey) != 32 { - return errors.New("priv key is not 32 bytes") - } - var seckey_ptr *C.uchar = (*C.uchar)(unsafe.Pointer(&seckey[0])) - ret := C.secp256k1_ec_seckey_verify(seckey_ptr) - if int(ret) != 1 { - return errors.New("invalid seckey") - } - return nil -} - -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_ec_pubkey_verify(pubkey_ptr, 65) - if int(ret) != 1 { - return errors.New("invalid pubkey") - } - - return nil -} - -func VerifySignatureValidity(sig []byte) bool { - //64+1 - if len(sig) != 65 { - return false - } - //malleability check, highest bit must be 1 - if (sig[32] & 0x80) == 0x80 { - return false - } - //recovery id check - if sig[64] >= 4 { - return false - } - - return true -} - -//for compressed signatures, does not need pubkey -func VerifySignature(msg []byte, sig []byte, pubkey1 []byte) error { - if msg == nil || sig == nil || pubkey1 == nil { - return errors.New("inputs must be non-nil") - } - if len(sig) != 65 { - return errors.New("invalid signature length") - } - if len(pubkey1) != 65 { - return errors.New("Invalid public key length") - } - - //to enforce malleability, highest bit of S must be 0 - //S starts at 32nd byte - if (sig[32] & 0x80) == 0x80 { //highest bit must be 1 - return errors.New("Signature not malleable") - } - - if sig[64] >= 4 { - return errors.New("Recover byte invalid") - } - - // if pubkey recovered, signature valid - pubkey2, err := RecoverPubkey(msg, sig) - if err != nil { - return err - } - if len(pubkey2) != 65 { - return errors.New("Invalid recovered public key length") - } - if !bytes.Equal(pubkey1, pubkey2) { - return errors.New("Public key does not match recovered public key") - } - - return nil -} - -//recovers the public key from the signature -//recovery of pubkey means correct signature -func RecoverPubkey(msg []byte, sig []byte) ([]byte, error) { - if len(sig) != 65 { - return nil, errors.New("Invalid signature length") - } - - var pubkey []byte = make([]byte, 65) - - var msg_ptr *C.uchar = (*C.uchar)(unsafe.Pointer(&msg[0])) - var sig_ptr *C.uchar = (*C.uchar)(unsafe.Pointer(&sig[0])) - var pubkey_ptr *C.uchar = (*C.uchar)(unsafe.Pointer(&pubkey[0])) - - var pubkeylen C.int - - ret := C.secp256k1_ecdsa_recover_compact( - msg_ptr, - sig_ptr, - pubkey_ptr, - &pubkeylen, - C.int(0), - C.int(sig[64]), - ) - - if ret == C.int(0) { - return nil, errors.New("Failed to recover public key") - } else if pubkeylen != C.int(65) { - return nil, errors.New("Impossible Error: Invalid recovered public key length") - } else { - return pubkey, nil - } - return nil, errors.New("Impossible Error: func RecoverPubkey has reached an unreachable state") -} diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256_test.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256_test.go deleted file mode 100644 index cebc3b9f21fd98da3b2c4a6808b395820033e461..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256_test.go +++ /dev/null @@ -1,238 +0,0 @@ -package secp256k1 - -import ( - "bytes" - "fmt" - "log" - "testing" - - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/randentropy" -) - -const TESTS = 10000 // how many tests -const SigSize = 65 //64+1 - -func Test_Secp256_00(t *testing.T) { - - var nonce []byte = randentropy.GetEntropyCSPRNG(32) //going to get bitcoins stolen! - - if len(nonce) != 32 { - t.Fatal() - } - -} - -//tests for Malleability -//highest bit of S must be 0; 32nd byte -func CompactSigTest(sig []byte) { - - var b int = int(sig[32]) - if b < 0 { - log.Panic() - } - if ((b >> 7) == 1) != ((b & 0x80) == 0x80) { - log.Panic("b= %v b2= %v \n", b, b>>7) - } - if (b & 0x80) == 0x80 { - log.Panic("b= %v b2= %v \n", b, b&0x80) - } -} - -//test pubkey/private generation -func Test_Secp256_01(t *testing.T) { - pubkey, seckey := GenerateKeyPair() - if err := VerifySeckeyValidity(seckey); err != nil { - t.Fatal() - } - if err := VerifyPubkeyValidity(pubkey); err != nil { - t.Fatal() - } -} - -//test size of messages -func Test_Secp256_02s(t *testing.T) { - pubkey, seckey := GenerateKeyPair() - msg := randentropy.GetEntropyCSPRNG(32) - sig, _ := Sign(msg, seckey) - CompactSigTest(sig) - if sig == nil { - t.Fatal("Signature nil") - } - if len(pubkey) != 65 { - t.Fail() - } - if len(seckey) != 32 { - t.Fail() - } - if len(sig) != 64+1 { - t.Fail() - } - if int(sig[64]) > 4 { - t.Fail() - } //should be 0 to 4 -} - -//test signing message -func Test_Secp256_02(t *testing.T) { - pubkey1, seckey := GenerateKeyPair() - msg := randentropy.GetEntropyCSPRNG(32) - sig, _ := Sign(msg, seckey) - if sig == nil { - t.Fatal("Signature nil") - } - - pubkey2, _ := RecoverPubkey(msg, sig) - if pubkey2 == nil { - t.Fatal("Recovered pubkey invalid") - } - if bytes.Equal(pubkey1, pubkey2) == false { - t.Fatal("Recovered pubkey does not match") - } - - err := VerifySignature(msg, sig, pubkey1) - if err != nil { - t.Fatal("Signature invalid") - } -} - -//test pubkey recovery -func Test_Secp256_02a(t *testing.T) { - pubkey1, seckey1 := GenerateKeyPair() - msg := randentropy.GetEntropyCSPRNG(32) - sig, _ := Sign(msg, seckey1) - - if sig == nil { - t.Fatal("Signature nil") - } - err := VerifySignature(msg, sig, pubkey1) - if err != nil { - t.Fatal("Signature invalid") - } - - pubkey2, _ := RecoverPubkey(msg, sig) - if len(pubkey1) != len(pubkey2) { - t.Fatal() - } - for i, _ := range pubkey1 { - if pubkey1[i] != pubkey2[i] { - t.Fatal() - } - } - if bytes.Equal(pubkey1, pubkey2) == false { - t.Fatal() - } -} - -//test random messages for the same pub/private key -func Test_Secp256_03(t *testing.T) { - _, seckey := GenerateKeyPair() - for i := 0; i < TESTS; i++ { - msg := randentropy.GetEntropyCSPRNG(32) - sig, _ := Sign(msg, seckey) - CompactSigTest(sig) - - sig[len(sig)-1] %= 4 - pubkey2, _ := RecoverPubkey(msg, sig) - if pubkey2 == nil { - t.Fail() - } - } -} - -//test random messages for different pub/private keys -func Test_Secp256_04(t *testing.T) { - for i := 0; i < TESTS; i++ { - pubkey1, seckey := GenerateKeyPair() - msg := randentropy.GetEntropyCSPRNG(32) - sig, _ := Sign(msg, seckey) - CompactSigTest(sig) - - if sig[len(sig)-1] >= 4 { - t.Fail() - } - pubkey2, _ := RecoverPubkey(msg, sig) - if pubkey2 == nil { - t.Fail() - } - if bytes.Equal(pubkey1, pubkey2) == false { - t.Fail() - } - } -} - -//test random signatures against fixed messages; should fail - -//crashes: -// -SIPA look at this - -func randSig() []byte { - sig := randentropy.GetEntropyCSPRNG(65) - sig[32] &= 0x70 - sig[64] %= 4 - return sig -} - -func Test_Secp256_06a_alt0(t *testing.T) { - pubkey1, seckey := GenerateKeyPair() - msg := randentropy.GetEntropyCSPRNG(32) - sig, _ := Sign(msg, seckey) - - if sig == nil { - t.Fail() - } - if len(sig) != 65 { - t.Fail() - } - for i := 0; i < TESTS; i++ { - sig = randSig() - pubkey2, _ := RecoverPubkey(msg, sig) - - if bytes.Equal(pubkey1, pubkey2) == true { - t.Fail() - } - - if pubkey2 != nil && VerifySignature(msg, sig, pubkey2) != nil { - t.Fail() - } - - if VerifySignature(msg, sig, pubkey1) == nil { - t.Fail() - } - } -} - -//test random messages against valid signature: should fail - -func Test_Secp256_06b(t *testing.T) { - pubkey1, seckey := GenerateKeyPair() - msg := randentropy.GetEntropyCSPRNG(32) - sig, _ := Sign(msg, seckey) - - fail_count := 0 - for i := 0; i < TESTS; i++ { - msg = randentropy.GetEntropyCSPRNG(32) - pubkey2, _ := RecoverPubkey(msg, sig) - if bytes.Equal(pubkey1, pubkey2) == true { - t.Fail() - } - - if pubkey2 != nil && VerifySignature(msg, sig, pubkey2) != nil { - t.Fail() - } - - if VerifySignature(msg, sig, pubkey1) == nil { - t.Fail() - } - } - if fail_count != 0 { - fmt.Printf("ERROR: Accepted signature for %v of %v random messages\n", fail_count, TESTS) - } -} - -func TestInvalidKey(t *testing.T) { - p1 := make([]byte, 32) - err := VerifySeckeyValidity(p1) - if err == nil { - t.Errorf("pvk %x varify sec key should have returned error", p1) - } -} diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/.travis.yml b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/.travis.yml deleted file mode 100644 index 40f8dae23f8b97ffca212bf96391d879f169275e..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/.travis.yml +++ /dev/null @@ -1,32 +0,0 @@ -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 diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/COPYING b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/COPYING deleted file mode 100644 index 4522a5990e2823f2be0db7efcbc4fca139c08025..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/COPYING +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2013 Pieter Wuille - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/Makefile.am b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/Makefile.am deleted file mode 100644 index cc15338b7ef7c6e7a1acade834d35b6638e27363..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/Makefile.am +++ /dev/null @@ -1,77 +0,0 @@ -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 diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/README.md b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/README.md deleted file mode 100644 index 6095db42205be95ba7f1a8bfc9151e251548dc19..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/README.md +++ /dev/null @@ -1,61 +0,0 @@ -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 diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/TODO b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/TODO deleted file mode 100644 index a300e1c5eb9b1376c82b1f5d557d56be5708546f..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/TODO +++ /dev/null @@ -1,3 +0,0 @@ -* Unit tests for fieldelem/groupelem, including ones intended to - trigger fieldelem's boundary cases. -* Complete constant-time operations for signing/keygen diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/autogen.sh b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/autogen.sh deleted file mode 100644 index 65286b93530332340a0c4ec89301a54bff92a35b..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/autogen.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/sh -set -e -autoreconf -if --warnings=all diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/build-aux/m4/bitcoin_secp.m4 b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/build-aux/m4/bitcoin_secp.m4 deleted file mode 100644 index 4a398d6c93a58745e16959ba3b237a282fc4aa5b..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/build-aux/m4/bitcoin_secp.m4 +++ /dev/null @@ -1,61 +0,0 @@ -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 -]) diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/configure.ac b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/configure.ac deleted file mode 100644 index 3dc1829516e4ec574c4dc17f0b692eb977e2b371..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/configure.ac +++ /dev/null @@ -1,330 +0,0 @@ -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 diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/include/secp256k1.h b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/include/secp256k1.h deleted file mode 100644 index a6e39d13dbe652cac1abcda81fc74cff9495bd94..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/include/secp256k1.h +++ /dev/null @@ -1,295 +0,0 @@ -#ifndef _SECP256K1_ -# define _SECP256K1_ - -# ifdef __cplusplus -extern "C" { -# 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(unsigned int flags); - -/** Free all memory associated with this library. After this, no - * functions can be called anymore, except secp256k1_start() - */ -void secp256k1_stop(void); - -/** Verify an ECDSA signature. - * Returns: 1: correct signature - * 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. - */ -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: 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 *msg32, - unsigned char *sig, - int *siglen, - const unsigned char *seckey, - 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: 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 *msg32, - unsigned char *sig64, - const unsigned char *seckey, - 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 successfully recovered (which guarantees a correct signature). - * 0: otherwise. - * 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 (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. - */ -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 -) 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 (cannot be NULL) - */ -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 - */ -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 (cannot be NULL) - * Out: pubkey: pointer to a 33-byte (if compressed) or 65-byte (if uncompressed) - * area to store the public key (cannot be NULL) - * pubkeylen: pointer to int that will be updated to contains the pubkey's - * length (cannot be NULL) - * Returns: 1: secret was valid, public key stores - * 0: secret was invalid, try again. - * Requires starting using SECP256K1_START_SIGN. - */ -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); - -/** 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); - -/** 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); - -/** 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); - -/** 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); - -/** 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 diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/libsecp256k1.pc.in b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/libsecp256k1.pc.in deleted file mode 100644 index 1c72dd00037b5cbef34d24792f809d700049e105..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/libsecp256k1.pc.in +++ /dev/null @@ -1,13 +0,0 @@ -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 - diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/obj/.gitignore b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/obj/.gitignore deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/bench.h b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/bench.h deleted file mode 100644 index 0559b3e85352c55858d830cb98fed25af4fe4e19..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/bench.h +++ /dev/null @@ -1,56 +0,0 @@ -/********************************************************************** - * 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 diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/bench_internal.c b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/bench_internal.c deleted file mode 100644 index a960549b94ff0f57db967f556c4d339de5505659..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/bench_internal.c +++ /dev/null @@ -1,318 +0,0 @@ -/********************************************************************** - * 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; -} diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/bench_recover.c b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/bench_recover.c deleted file mode 100644 index 6991cc9d6c595765386fefcb99270ecf7b0a9935..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/bench_recover.c +++ /dev/null @@ -1,49 +0,0 @@ -/********************************************************************** - * 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; -} diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/bench_sign.c b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/bench_sign.c deleted file mode 100644 index c5b6829a84639a647a136a404bfd77afd36a0f8f..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/bench_sign.c +++ /dev/null @@ -1,48 +0,0 @@ -/********************************************************************** - * 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; -} diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/bench_verify.c b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/bench_verify.c deleted file mode 100644 index c279305a0dba6e7560bc834e011f574a30c8ccd0..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/bench_verify.c +++ /dev/null @@ -1,55 +0,0 @@ -/********************************************************************** - * 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; -} diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/ecdsa.h b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/ecdsa.h deleted file mode 100644 index c195e7afcbf115e4efaceca526aabdd80a8c0c2d..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/ecdsa.h +++ /dev/null @@ -1,23 +0,0 @@ -/********************************************************************** - * 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 "scalar.h" -#include "group.h" - -typedef struct { - secp256k1_scalar_t r, s; -} secp256k1_ecdsa_sig_t; - -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 diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/ecdsa_impl.h b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/ecdsa_impl.h deleted file mode 100644 index 17514047b9c72afe866ed2abcbbd4a114cf45135..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/ecdsa_impl.h +++ /dev/null @@ -1,263 +0,0 @@ -/********************************************************************** - * 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 diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/eckey.h b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/eckey.h deleted file mode 100644 index 6de5dc0a590fb9849e3f2c6ddbce766d2295ce11..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/eckey.h +++ /dev/null @@ -1,24 +0,0 @@ -/********************************************************************** - * 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 diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/eckey_impl.h b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/eckey_impl.h deleted file mode 100644 index 4382ff5f324b549c30bfa1ea0b1e104dd2b1bba8..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/eckey_impl.h +++ /dev/null @@ -1,202 +0,0 @@ -/********************************************************************** - * 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 diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/ecmult.h b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/ecmult.h deleted file mode 100644 index 15a7100a4a1fa03468f6c434c6372aa22809b1b1..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/ecmult.h +++ /dev/null @@ -1,19 +0,0 @@ -/********************************************************************** - * 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_ - -#include "num.h" -#include "group.h" - -static void secp256k1_ecmult_start(void); -static void secp256k1_ecmult_stop(void); - -/** Double multiply: R = na*A + ng*G */ -static void secp256k1_ecmult(secp256k1_gej_t *r, const secp256k1_gej_t *a, const secp256k1_scalar_t *na, const secp256k1_scalar_t *ng); - -#endif diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/ecmult_gen.h b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/ecmult_gen.h deleted file mode 100644 index 42f822f9cef299f354968ec4fbe0b2ef55c9606c..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/ecmult_gen.h +++ /dev/null @@ -1,19 +0,0 @@ -/********************************************************************** - * 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 diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/ecmult_gen_impl.h b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/ecmult_gen_impl.h deleted file mode 100644 index 3146a93b572c13d49813a221aa0128fd6630d8dd..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/ecmult_gen_impl.h +++ /dev/null @@ -1,128 +0,0 @@ -/********************************************************************** - * 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 diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/ecmult_impl.h b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/ecmult_impl.h deleted file mode 100644 index f6f0c4294e87950fea9aff7aeec129d7b744a1f9..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/ecmult_impl.h +++ /dev/null @@ -1,302 +0,0 @@ -/********************************************************************** - * 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 diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/field.h b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/field.h deleted file mode 100644 index 9e6d7d3c0421314faee7b6dbbad225b44c8410eb..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/field.h +++ /dev/null @@ -1,116 +0,0 @@ -/********************************************************************** - * 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_ - -/** Field element module. - * - * Field elements can be represented in several ways, but code accessing - * it (and implementations) need to take certain properaties into account: - * - Each field element can be normalized or not. - * - Each field element has a magnitude, which represents how far away - * its representation is away from normalization. Normalized elements - * always have a magnitude of 1, but a magnitude of 1 doesn't imply - * normality. - */ - -#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" -#else -#error "Please select field implementation" -#endif - -/** Normalize a field element. */ -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. */ -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. */ -static int secp256k1_fe_is_zero(const secp256k1_fe_t *a); - -/** Check the "oddness" of a field element. Requires the input to be normalized. */ -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 */ -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. 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 */ -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. */ -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. */ -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. */ -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). */ -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). */ -static void secp256k1_fe_sqr(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). */ -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. */ -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 the storage type. */ -static void secp256k1_fe_to_storage(secp256k1_fe_storage_t *r, const secp256k1_fe_t*); - -/** 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 diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/field_10x26.h b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/field_10x26.h deleted file mode 100644 index 44bce6525df9f154ea6a394f8ea56acb10cde44d..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/field_10x26.h +++ /dev/null @@ -1,47 +0,0 @@ -/********************************************************************** - * 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_ - -#include <stdint.h> - -typedef struct { - /* X = sum(i=0..9, elem[i]*2^26) mod n */ - uint32_t n[10]; -#ifdef VERIFY - int magnitude; - int normalized; -#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 diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/field_10x26_impl.h b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/field_10x26_impl.h deleted file mode 100644 index b32a666f5373d7c8848590312ec106994eea0608..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/field_10x26_impl.h +++ /dev/null @@ -1,1116 +0,0 @@ -/********************************************************************** - * 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_ - -#include <stdio.h> -#include <string.h> -#include "util.h" -#include "num.h" -#include "field.h" - -#ifdef VERIFY -static void secp256k1_fe_verify(const secp256k1_fe_t *a) { - const uint32_t *d = a->n; - int m = a->normalized ? 1 : 2 * a->magnitude, r = 1; - r &= (d[0] <= 0x3FFFFFFUL * m); - r &= (d[1] <= 0x3FFFFFFUL * m); - r &= (d[2] <= 0x3FFFFFFUL * m); - r &= (d[3] <= 0x3FFFFFFUL * m); - r &= (d[4] <= 0x3FFFFFFUL * m); - r &= (d[5] <= 0x3FFFFFFUL * m); - r &= (d[6] <= 0x3FFFFFFUL * m); - r &= (d[7] <= 0x3FFFFFFUL * m); - r &= (d[8] <= 0x3FFFFFFUL * m); - r &= (d[9] <= 0x03FFFFFUL * m); - r &= (a->magnitude >= 0); - r &= (a->magnitude <= 32); - if (a->normalized) { - r &= (a->magnitude <= 1); - if (r && (d[9] == 0x03FFFFFUL)) { - uint32_t mid = d[8] & d[7] & d[6] & d[5] & d[4] & d[3] & d[2]; - if (mid == 0x3FFFFFFUL) { - r &= ((d[1] + 0x40UL + ((d[0] + 0x3D1UL) >> 26)) <= 0x3FFFFFFUL); - } - } - } - 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) { - uint32_t t0 = r->n[0], t1 = r->n[1], t2 = r->n[2], t3 = r->n[3], t4 = r->n[4], - t5 = r->n[5], t6 = r->n[6], t7 = r->n[7], t8 = r->n[8], t9 = r->n[9]; - - /* Reduce t9 at the start so there will be at most a single carry from the first pass */ - uint32_t m; - uint32_t x = t9 >> 22; t9 &= 0x03FFFFFUL; - - /* The first pass ensures the magnitude is 1, ... */ - t0 += x * 0x3D1UL; t1 += (x << 6); - t1 += (t0 >> 26); t0 &= 0x3FFFFFFUL; - t2 += (t1 >> 26); t1 &= 0x3FFFFFFUL; - t3 += (t2 >> 26); t2 &= 0x3FFFFFFUL; m = t2; - t4 += (t3 >> 26); t3 &= 0x3FFFFFFUL; m &= t3; - t5 += (t4 >> 26); t4 &= 0x3FFFFFFUL; m &= t4; - t6 += (t5 >> 26); t5 &= 0x3FFFFFFUL; m &= t5; - t7 += (t6 >> 26); t6 &= 0x3FFFFFFUL; m &= t6; - t8 += (t7 >> 26); t7 &= 0x3FFFFFFUL; m &= t7; - t9 += (t8 >> 26); t8 &= 0x3FFFFFFUL; m &= t8; - - /* ... except for a possible carry at bit 22 of t9 (i.e. bit 256 of the field element) */ - VERIFY_CHECK(t9 >> 23 == 0); - - /* At most a single final reduction is needed; check if the value is >= the field characteristic */ - x = (t9 >> 22) | ((t9 == 0x03FFFFFUL) & (m == 0x3FFFFFFUL) - & ((t1 + 0x40UL + ((t0 + 0x3D1UL) >> 26)) > 0x3FFFFFFUL)); - - /* Apply the final reduction (for constant-time behaviour, we do it always) */ - t0 += x * 0x3D1UL; t1 += (x << 6); - t1 += (t0 >> 26); t0 &= 0x3FFFFFFUL; - t2 += (t1 >> 26); t1 &= 0x3FFFFFFUL; - t3 += (t2 >> 26); t2 &= 0x3FFFFFFUL; - t4 += (t3 >> 26); t3 &= 0x3FFFFFFUL; - t5 += (t4 >> 26); t4 &= 0x3FFFFFFUL; - t6 += (t5 >> 26); t5 &= 0x3FFFFFFUL; - t7 += (t6 >> 26); t6 &= 0x3FFFFFFUL; - t8 += (t7 >> 26); t7 &= 0x3FFFFFFUL; - t9 += (t8 >> 26); t8 &= 0x3FFFFFFUL; - - /* If t9 didn't carry to bit 22 already, then it should have after any final reduction */ - VERIFY_CHECK(t9 >> 22 == x); - - /* Mask off the possible multiple of 2^256 from the final reduction */ - t9 &= 0x03FFFFFUL; - - 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; - -#ifdef VERIFY - r->magnitude = 1; - r->normalized = 1; - secp256k1_fe_verify(r); -#endif -} - -static void secp256k1_fe_normalize_weak(secp256k1_fe_t *r) { - uint32_t t0 = r->n[0], t1 = r->n[1], t2 = r->n[2], t3 = r->n[3], t4 = r->n[4], - t5 = r->n[5], t6 = r->n[6], t7 = r->n[7], t8 = r->n[8], t9 = r->n[9]; - - /* Reduce t9 at the start so there will be at most a single carry from the first pass */ - uint32_t x = t9 >> 22; t9 &= 0x03FFFFFUL; - - /* The first pass ensures the magnitude is 1, ... */ - t0 += x * 0x3D1UL; t1 += (x << 6); - t1 += (t0 >> 26); t0 &= 0x3FFFFFFUL; - t2 += (t1 >> 26); t1 &= 0x3FFFFFFUL; - t3 += (t2 >> 26); t2 &= 0x3FFFFFFUL; - t4 += (t3 >> 26); t3 &= 0x3FFFFFFUL; - t5 += (t4 >> 26); t4 &= 0x3FFFFFFUL; - t6 += (t5 >> 26); t5 &= 0x3FFFFFFUL; - t7 += (t6 >> 26); t6 &= 0x3FFFFFFUL; - t8 += (t7 >> 26); t7 &= 0x3FFFFFFUL; - t9 += (t8 >> 26); t8 &= 0x3FFFFFFUL; - - /* ... except for a possible carry at bit 22 of t9 (i.e. bit 256 of the field element) */ - VERIFY_CHECK(t9 >> 23 == 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; - -#ifdef VERIFY - r->magnitude = 1; - secp256k1_fe_verify(r); -#endif -} - -static void secp256k1_fe_normalize_var(secp256k1_fe_t *r) { - uint32_t t0 = r->n[0], t1 = r->n[1], t2 = r->n[2], t3 = r->n[3], t4 = r->n[4], - t5 = r->n[5], t6 = r->n[6], t7 = r->n[7], t8 = r->n[8], t9 = r->n[9]; - - /* Reduce t9 at the start so there will be at most a single carry from the first pass */ - uint32_t m; - uint32_t x = t9 >> 22; t9 &= 0x03FFFFFUL; - - /* The first pass ensures the magnitude is 1, ... */ - t0 += x * 0x3D1UL; t1 += (x << 6); - t1 += (t0 >> 26); t0 &= 0x3FFFFFFUL; - t2 += (t1 >> 26); t1 &= 0x3FFFFFFUL; - t3 += (t2 >> 26); t2 &= 0x3FFFFFFUL; m = t2; - t4 += (t3 >> 26); t3 &= 0x3FFFFFFUL; m &= t3; - t5 += (t4 >> 26); t4 &= 0x3FFFFFFUL; m &= t4; - t6 += (t5 >> 26); t5 &= 0x3FFFFFFUL; m &= t5; - t7 += (t6 >> 26); t6 &= 0x3FFFFFFUL; m &= t6; - t8 += (t7 >> 26); t7 &= 0x3FFFFFFUL; m &= t7; - t9 += (t8 >> 26); t8 &= 0x3FFFFFFUL; m &= t8; - - /* ... except for a possible carry at bit 22 of t9 (i.e. bit 256 of the field element) */ - VERIFY_CHECK(t9 >> 23 == 0); - - /* At most a single final reduction is needed; check if the value is >= the field characteristic */ - x = (t9 >> 22) | ((t9 == 0x03FFFFFUL) & (m == 0x3FFFFFFUL) - & ((t1 + 0x40UL + ((t0 + 0x3D1UL) >> 26)) > 0x3FFFFFFUL)); - - if (x) { - t0 += 0x3D1UL; t1 += (x << 6); - t1 += (t0 >> 26); t0 &= 0x3FFFFFFUL; - t2 += (t1 >> 26); t1 &= 0x3FFFFFFUL; - t3 += (t2 >> 26); t2 &= 0x3FFFFFFUL; - t4 += (t3 >> 26); t3 &= 0x3FFFFFFUL; - t5 += (t4 >> 26); t4 &= 0x3FFFFFFUL; - t6 += (t5 >> 26); t5 &= 0x3FFFFFFUL; - t7 += (t6 >> 26); t6 &= 0x3FFFFFFUL; - t8 += (t7 >> 26); t7 &= 0x3FFFFFFUL; - t9 += (t8 >> 26); t8 &= 0x3FFFFFFUL; - - /* If t9 didn't carry to bit 22 already, then it should have after any final reduction */ - VERIFY_CHECK(t9 >> 22 == x); - - /* Mask off the possible multiple of 2^256 from the final reduction */ - t9 &= 0x03FFFFFUL; - } - - 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; - -#ifdef VERIFY - r->magnitude = 1; - r->normalized = 1; - secp256k1_fe_verify(r); -#endif -} - -static int secp256k1_fe_normalizes_to_zero(secp256k1_fe_t *r) { - uint32_t t0 = r->n[0], t1 = r->n[1], t2 = r->n[2], t3 = r->n[3], t4 = r->n[4], - t5 = r->n[5], t6 = r->n[6], t7 = r->n[7], t8 = r->n[8], t9 = r->n[9]; - - /* z0 tracks a possible raw value of 0, z1 tracks a possible raw value of P */ - uint32_t z0, z1; - - /* Reduce t9 at the start so there will be at most a single carry from the first pass */ - uint32_t x = t9 >> 22; t9 &= 0x03FFFFFUL; - - /* The first pass ensures the magnitude is 1, ... */ - t0 += x * 0x3D1UL; t1 += (x << 6); - t1 += (t0 >> 26); t0 &= 0x3FFFFFFUL; z0 = t0; z1 = t0 ^ 0x3D0UL; - t2 += (t1 >> 26); t1 &= 0x3FFFFFFUL; z0 |= t1; z1 &= t1 ^ 0x40UL; - t3 += (t2 >> 26); t2 &= 0x3FFFFFFUL; z0 |= t2; z1 &= t2; - t4 += (t3 >> 26); t3 &= 0x3FFFFFFUL; z0 |= t3; z1 &= t3; - t5 += (t4 >> 26); t4 &= 0x3FFFFFFUL; z0 |= t4; z1 &= t4; - t6 += (t5 >> 26); t5 &= 0x3FFFFFFUL; z0 |= t5; z1 &= t5; - t7 += (t6 >> 26); t6 &= 0x3FFFFFFUL; z0 |= t6; z1 &= t6; - t8 += (t7 >> 26); t7 &= 0x3FFFFFFUL; z0 |= t7; z1 &= t7; - t9 += (t8 >> 26); t8 &= 0x3FFFFFFUL; z0 |= t8; z1 &= t8; - z0 |= t9; z1 &= t9 ^ 0x3C00000UL; - - /* ... except for a possible carry at bit 22 of t9 (i.e. bit 256 of the field element) */ - VERIFY_CHECK(t9 >> 23 == 0); - - return (z0 == 0) | (z1 == 0x3FFFFFFUL); -} - -static int secp256k1_fe_normalizes_to_zero_var(secp256k1_fe_t *r) { - uint32_t t0, t1, t2, t3, t4, t5, t6, t7, t8, t9; - uint32_t z0, z1; - uint32_t x; - - t0 = r->n[0]; - t9 = r->n[9]; - - /* Reduce t9 at the start so there will be at most a single carry from the first pass */ - x = t9 >> 22; - - /* The first pass ensures the magnitude is 1, ... */ - t0 += x * 0x3D1UL; - - /* z0 tracks a possible raw value of 0, z1 tracks a possible raw value of P */ - z0 = t0 & 0x3FFFFFFUL; - z1 = z0 ^ 0x3D0UL; - - /* Fast return path should catch the majority of cases */ - if ((z0 != 0UL) & (z1 != 0x3FFFFFFUL)) { - return 0; - } - - t1 = r->n[1]; - t2 = r->n[2]; - t3 = r->n[3]; - t4 = r->n[4]; - t5 = r->n[5]; - t6 = r->n[6]; - t7 = r->n[7]; - t8 = r->n[8]; - - t9 &= 0x03FFFFFUL; - t1 += (x << 6); - - t1 += (t0 >> 26); t0 = z0; - t2 += (t1 >> 26); t1 &= 0x3FFFFFFUL; z0 |= t1; z1 &= t1 ^ 0x40UL; - t3 += (t2 >> 26); t2 &= 0x3FFFFFFUL; z0 |= t2; z1 &= t2; - t4 += (t3 >> 26); t3 &= 0x3FFFFFFUL; z0 |= t3; z1 &= t3; - t5 += (t4 >> 26); t4 &= 0x3FFFFFFUL; z0 |= t4; z1 &= t4; - t6 += (t5 >> 26); t5 &= 0x3FFFFFFUL; z0 |= t5; z1 &= t5; - t7 += (t6 >> 26); t6 &= 0x3FFFFFFUL; z0 |= t6; z1 &= t6; - t8 += (t7 >> 26); t7 &= 0x3FFFFFFUL; z0 |= t7; z1 &= t7; - t9 += (t8 >> 26); t8 &= 0x3FFFFFFUL; z0 |= t8; z1 &= t8; - z0 |= t9; z1 &= t9 ^ 0x3C00000UL; - - /* ... except for a possible carry at bit 22 of t9 (i.e. bit 256 of the field element) */ - VERIFY_CHECK(t9 >> 23 == 0); - - return (z0 == 0) | (z1 == 0x3FFFFFFUL); -} - -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] = r->n[5] = r->n[6] = r->n[7] = r->n[8] = r->n[9] = 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 uint32_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] | t[5] | t[6] | t[7] | t[8] | t[9]) == 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<10; 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 = 9; 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; - r->n[5] = r->n[6] = r->n[7] = r->n[8] = r->n[9] = 0; - for (i=0; i<32; i++) { - int j; - for (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; - } - } - if (r->n[9] == 0x3FFFFFUL && (r->n[8] & r->n[7] & r->n[6] & r->n[5] & r->n[4] & r->n[3] & r->n[2]) == 0x3FFFFFFUL && (r->n[1] + 0x40UL + ((r->n[0] + 0x3D1UL) >> 26)) > 0x3FFFFFFUL) { - 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<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; - } -} - -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] = 0x3FFFC2FUL * 2 * (m + 1) - a->n[0]; - r->n[1] = 0x3FFFFBFUL * 2 * (m + 1) - a->n[1]; - r->n[2] = 0x3FFFFFFUL * 2 * (m + 1) - a->n[2]; - r->n[3] = 0x3FFFFFFUL * 2 * (m + 1) - a->n[3]; - r->n[4] = 0x3FFFFFFUL * 2 * (m + 1) - a->n[4]; - r->n[5] = 0x3FFFFFFUL * 2 * (m + 1) - a->n[5]; - r->n[6] = 0x3FFFFFFUL * 2 * (m + 1) - a->n[6]; - r->n[7] = 0x3FFFFFFUL * 2 * (m + 1) - a->n[7]; - r->n[8] = 0x3FFFFFFUL * 2 * (m + 1) - a->n[8]; - r->n[9] = 0x03FFFFFUL * 2 * (m + 1) - a->n[9]; -#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; - r->n[5] *= a; - r->n[6] *= a; - r->n[7] *= a; - r->n[8] *= a; - r->n[9] *= 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]; - 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]; -#ifdef VERIFY - r->magnitude += a->magnitude; - r->normalized = 0; - secp256k1_fe_verify(r); -#endif -} - -#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(uint32_t *r, const uint32_t *a, const uint32_t * SECP256K1_RESTRICT b) { - uint64_t c, d; - uint64_t u0, u1, u2, u3, u4, u5, u6, u7, u8; - uint32_t t9, t1, t0, t2, t3, t4, t5, t6, t7; - const uint32_t M = 0x3FFFFFFUL, R0 = 0x3D10UL, R1 = 0x400UL; - - VERIFY_BITS(a[0], 30); - VERIFY_BITS(a[1], 30); - VERIFY_BITS(a[2], 30); - VERIFY_BITS(a[3], 30); - VERIFY_BITS(a[4], 30); - VERIFY_BITS(a[5], 30); - VERIFY_BITS(a[6], 30); - VERIFY_BITS(a[7], 30); - VERIFY_BITS(a[8], 30); - VERIFY_BITS(a[9], 26); - VERIFY_BITS(b[0], 30); - VERIFY_BITS(b[1], 30); - VERIFY_BITS(b[2], 30); - VERIFY_BITS(b[3], 30); - VERIFY_BITS(b[4], 30); - VERIFY_BITS(b[5], 30); - VERIFY_BITS(b[6], 30); - VERIFY_BITS(b[7], 30); - VERIFY_BITS(b[8], 30); - VERIFY_BITS(b[9], 26); - - /** [... a b c] is a shorthand for ... + a<<52 + b<<26 + 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 0 0 0 0 0] = [x*R1 x*R0]. - */ - - d = (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]; - /* VERIFY_BITS(d, 64); */ - /* [d 0 0 0 0 0 0 0 0 0] = [p9 0 0 0 0 0 0 0 0 0] */ - t9 = d & M; d >>= 26; - VERIFY_BITS(t9, 26); - VERIFY_BITS(d, 38); - /* [d t9 0 0 0 0 0 0 0 0 0] = [p9 0 0 0 0 0 0 0 0 0] */ - - c = (uint64_t)a[0] * b[0]; - VERIFY_BITS(c, 60); - /* [d t9 0 0 0 0 0 0 0 0 c] = [p9 0 0 0 0 0 0 0 0 p0] */ - d += (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]; - VERIFY_BITS(d, 63); - /* [d t9 0 0 0 0 0 0 0 0 c] = [p10 p9 0 0 0 0 0 0 0 0 p0] */ - u0 = d & M; d >>= 26; c += u0 * R0; - VERIFY_BITS(u0, 26); - VERIFY_BITS(d, 37); - VERIFY_BITS(c, 61); - /* [d u0 t9 0 0 0 0 0 0 0 0 c-u0*R0] = [p10 p9 0 0 0 0 0 0 0 0 p0] */ - t0 = c & M; c >>= 26; c += u0 * R1; - VERIFY_BITS(t0, 26); - VERIFY_BITS(c, 37); - /* [d u0 t9 0 0 0 0 0 0 0 c-u0*R1 t0-u0*R0] = [p10 p9 0 0 0 0 0 0 0 0 p0] */ - /* [d 0 t9 0 0 0 0 0 0 0 c t0] = [p10 p9 0 0 0 0 0 0 0 0 p0] */ - - c += (uint64_t)a[0] * b[1] - + (uint64_t)a[1] * b[0]; - VERIFY_BITS(c, 62); - /* [d 0 t9 0 0 0 0 0 0 0 c t0] = [p10 p9 0 0 0 0 0 0 0 p1 p0] */ - d += (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]; - VERIFY_BITS(d, 63); - /* [d 0 t9 0 0 0 0 0 0 0 c t0] = [p11 p10 p9 0 0 0 0 0 0 0 p1 p0] */ - u1 = d & M; d >>= 26; c += u1 * R0; - VERIFY_BITS(u1, 26); - VERIFY_BITS(d, 37); - VERIFY_BITS(c, 63); - /* [d u1 0 t9 0 0 0 0 0 0 0 c-u1*R0 t0] = [p11 p10 p9 0 0 0 0 0 0 0 p1 p0] */ - t1 = c & M; c >>= 26; c += u1 * R1; - VERIFY_BITS(t1, 26); - VERIFY_BITS(c, 38); - /* [d u1 0 t9 0 0 0 0 0 0 c-u1*R1 t1-u1*R0 t0] = [p11 p10 p9 0 0 0 0 0 0 0 p1 p0] */ - /* [d 0 0 t9 0 0 0 0 0 0 c t1 t0] = [p11 p10 p9 0 0 0 0 0 0 0 p1 p0] */ - - c += (uint64_t)a[0] * b[2] - + (uint64_t)a[1] * b[1] - + (uint64_t)a[2] * b[0]; - VERIFY_BITS(c, 62); - /* [d 0 0 t9 0 0 0 0 0 0 c t1 t0] = [p11 p10 p9 0 0 0 0 0 0 p2 p1 p0] */ - d += (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]; - VERIFY_BITS(d, 63); - /* [d 0 0 t9 0 0 0 0 0 0 c t1 t0] = [p12 p11 p10 p9 0 0 0 0 0 0 p2 p1 p0] */ - u2 = d & M; d >>= 26; c += u2 * R0; - VERIFY_BITS(u2, 26); - VERIFY_BITS(d, 37); - VERIFY_BITS(c, 63); - /* [d u2 0 0 t9 0 0 0 0 0 0 c-u2*R0 t1 t0] = [p12 p11 p10 p9 0 0 0 0 0 0 p2 p1 p0] */ - t2 = c & M; c >>= 26; c += u2 * R1; - VERIFY_BITS(t2, 26); - VERIFY_BITS(c, 38); - /* [d u2 0 0 t9 0 0 0 0 0 c-u2*R1 t2-u2*R0 t1 t0] = [p12 p11 p10 p9 0 0 0 0 0 0 p2 p1 p0] */ - /* [d 0 0 0 t9 0 0 0 0 0 c t2 t1 t0] = [p12 p11 p10 p9 0 0 0 0 0 0 p2 p1 p0] */ - - 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]; - VERIFY_BITS(c, 63); - /* [d 0 0 0 t9 0 0 0 0 0 c t2 t1 t0] = [p12 p11 p10 p9 0 0 0 0 0 p3 p2 p1 p0] */ - d += (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]; - VERIFY_BITS(d, 63); - /* [d 0 0 0 t9 0 0 0 0 0 c t2 t1 t0] = [p13 p12 p11 p10 p9 0 0 0 0 0 p3 p2 p1 p0] */ - u3 = d & M; d >>= 26; c += u3 * R0; - VERIFY_BITS(u3, 26); - VERIFY_BITS(d, 37); - /* VERIFY_BITS(c, 64); */ - /* [d u3 0 0 0 t9 0 0 0 0 0 c-u3*R0 t2 t1 t0] = [p13 p12 p11 p10 p9 0 0 0 0 0 p3 p2 p1 p0] */ - t3 = c & M; c >>= 26; c += u3 * R1; - VERIFY_BITS(t3, 26); - VERIFY_BITS(c, 39); - /* [d u3 0 0 0 t9 0 0 0 0 c-u3*R1 t3-u3*R0 t2 t1 t0] = [p13 p12 p11 p10 p9 0 0 0 0 0 p3 p2 p1 p0] */ - /* [d 0 0 0 0 t9 0 0 0 0 c t3 t2 t1 t0] = [p13 p12 p11 p10 p9 0 0 0 0 0 p3 p2 p1 p0] */ - - 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]; - VERIFY_BITS(c, 63); - /* [d 0 0 0 0 t9 0 0 0 0 c t3 t2 t1 t0] = [p13 p12 p11 p10 p9 0 0 0 0 p4 p3 p2 p1 p0] */ - d += (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]; - VERIFY_BITS(d, 62); - /* [d 0 0 0 0 t9 0 0 0 0 c t3 t2 t1 t0] = [p14 p13 p12 p11 p10 p9 0 0 0 0 p4 p3 p2 p1 p0] */ - u4 = d & M; d >>= 26; c += u4 * R0; - VERIFY_BITS(u4, 26); - VERIFY_BITS(d, 36); - /* VERIFY_BITS(c, 64); */ - /* [d u4 0 0 0 0 t9 0 0 0 0 c-u4*R0 t3 t2 t1 t0] = [p14 p13 p12 p11 p10 p9 0 0 0 0 p4 p3 p2 p1 p0] */ - t4 = c & M; c >>= 26; c += u4 * R1; - VERIFY_BITS(t4, 26); - VERIFY_BITS(c, 39); - /* [d u4 0 0 0 0 t9 0 0 0 c-u4*R1 t4-u4*R0 t3 t2 t1 t0] = [p14 p13 p12 p11 p10 p9 0 0 0 0 p4 p3 p2 p1 p0] */ - /* [d 0 0 0 0 0 t9 0 0 0 c t4 t3 t2 t1 t0] = [p14 p13 p12 p11 p10 p9 0 0 0 0 p4 p3 p2 p1 p0] */ - - 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]; - VERIFY_BITS(c, 63); - /* [d 0 0 0 0 0 t9 0 0 0 c t4 t3 t2 t1 t0] = [p14 p13 p12 p11 p10 p9 0 0 0 p5 p4 p3 p2 p1 p0] */ - d += (uint64_t)a[6] * b[9] - + (uint64_t)a[7] * b[8] - + (uint64_t)a[8] * b[7] - + (uint64_t)a[9] * b[6]; - VERIFY_BITS(d, 62); - /* [d 0 0 0 0 0 t9 0 0 0 c t4 t3 t2 t1 t0] = [p15 p14 p13 p12 p11 p10 p9 0 0 0 p5 p4 p3 p2 p1 p0] */ - u5 = d & M; d >>= 26; c += u5 * R0; - VERIFY_BITS(u5, 26); - VERIFY_BITS(d, 36); - /* VERIFY_BITS(c, 64); */ - /* [d u5 0 0 0 0 0 t9 0 0 0 c-u5*R0 t4 t3 t2 t1 t0] = [p15 p14 p13 p12 p11 p10 p9 0 0 0 p5 p4 p3 p2 p1 p0] */ - t5 = c & M; c >>= 26; c += u5 * R1; - VERIFY_BITS(t5, 26); - VERIFY_BITS(c, 39); - /* [d u5 0 0 0 0 0 t9 0 0 c-u5*R1 t5-u5*R0 t4 t3 t2 t1 t0] = [p15 p14 p13 p12 p11 p10 p9 0 0 0 p5 p4 p3 p2 p1 p0] */ - /* [d 0 0 0 0 0 0 t9 0 0 c t5 t4 t3 t2 t1 t0] = [p15 p14 p13 p12 p11 p10 p9 0 0 0 p5 p4 p3 p2 p1 p0] */ - - 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]; - VERIFY_BITS(c, 63); - /* [d 0 0 0 0 0 0 t9 0 0 c t5 t4 t3 t2 t1 t0] = [p15 p14 p13 p12 p11 p10 p9 0 0 p6 p5 p4 p3 p2 p1 p0] */ - d += (uint64_t)a[7] * b[9] - + (uint64_t)a[8] * b[8] - + (uint64_t)a[9] * b[7]; - VERIFY_BITS(d, 61); - /* [d 0 0 0 0 0 0 t9 0 0 c t5 t4 t3 t2 t1 t0] = [p16 p15 p14 p13 p12 p11 p10 p9 0 0 p6 p5 p4 p3 p2 p1 p0] */ - u6 = d & M; d >>= 26; c += u6 * R0; - VERIFY_BITS(u6, 26); - VERIFY_BITS(d, 35); - /* VERIFY_BITS(c, 64); */ - /* [d u6 0 0 0 0 0 0 t9 0 0 c-u6*R0 t5 t4 t3 t2 t1 t0] = [p16 p15 p14 p13 p12 p11 p10 p9 0 0 p6 p5 p4 p3 p2 p1 p0] */ - t6 = c & M; c >>= 26; c += u6 * R1; - VERIFY_BITS(t6, 26); - VERIFY_BITS(c, 39); - /* [d u6 0 0 0 0 0 0 t9 0 c-u6*R1 t6-u6*R0 t5 t4 t3 t2 t1 t0] = [p16 p15 p14 p13 p12 p11 p10 p9 0 0 p6 p5 p4 p3 p2 p1 p0] */ - /* [d 0 0 0 0 0 0 0 t9 0 c t6 t5 t4 t3 t2 t1 t0] = [p16 p15 p14 p13 p12 p11 p10 p9 0 0 p6 p5 p4 p3 p2 p1 p0] */ - - 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]; - /* VERIFY_BITS(c, 64); */ - VERIFY_CHECK(c <= 0x8000007C00000007ULL); - /* [d 0 0 0 0 0 0 0 t9 0 c t6 t5 t4 t3 t2 t1 t0] = [p16 p15 p14 p13 p12 p11 p10 p9 0 p7 p6 p5 p4 p3 p2 p1 p0] */ - d += (uint64_t)a[8] * b[9] - + (uint64_t)a[9] * b[8]; - VERIFY_BITS(d, 58); - /* [d 0 0 0 0 0 0 0 t9 0 c t6 t5 t4 t3 t2 t1 t0] = [p17 p16 p15 p14 p13 p12 p11 p10 p9 0 p7 p6 p5 p4 p3 p2 p1 p0] */ - u7 = d & M; d >>= 26; c += u7 * R0; - VERIFY_BITS(u7, 26); - VERIFY_BITS(d, 32); - /* VERIFY_BITS(c, 64); */ - VERIFY_CHECK(c <= 0x800001703FFFC2F7ULL); - /* [d u7 0 0 0 0 0 0 0 t9 0 c-u7*R0 t6 t5 t4 t3 t2 t1 t0] = [p17 p16 p15 p14 p13 p12 p11 p10 p9 0 p7 p6 p5 p4 p3 p2 p1 p0] */ - t7 = c & M; c >>= 26; c += u7 * R1; - VERIFY_BITS(t7, 26); - VERIFY_BITS(c, 38); - /* [d u7 0 0 0 0 0 0 0 t9 c-u7*R1 t7-u7*R0 t6 t5 t4 t3 t2 t1 t0] = [p17 p16 p15 p14 p13 p12 p11 p10 p9 0 p7 p6 p5 p4 p3 p2 p1 p0] */ - /* [d 0 0 0 0 0 0 0 0 t9 c t7 t6 t5 t4 t3 t2 t1 t0] = [p17 p16 p15 p14 p13 p12 p11 p10 p9 0 p7 p6 p5 p4 p3 p2 p1 p0] */ - - 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]; - /* VERIFY_BITS(c, 64); */ - VERIFY_CHECK(c <= 0x9000007B80000008ULL); - /* [d 0 0 0 0 0 0 0 0 t9 c t7 t6 t5 t4 t3 t2 t1 t0] = [p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ - d += (uint64_t)a[9] * b[9]; - VERIFY_BITS(d, 57); - /* [d 0 0 0 0 0 0 0 0 t9 c t7 t6 t5 t4 t3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ - u8 = d & M; d >>= 26; c += u8 * R0; - VERIFY_BITS(u8, 26); - VERIFY_BITS(d, 31); - /* VERIFY_BITS(c, 64); */ - VERIFY_CHECK(c <= 0x9000016FBFFFC2F8ULL); - /* [d u8 0 0 0 0 0 0 0 0 t9 c-u8*R0 t7 t6 t5 t4 t3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ - - r[3] = t3; - VERIFY_BITS(r[3], 26); - /* [d u8 0 0 0 0 0 0 0 0 t9 c-u8*R0 t7 t6 t5 t4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ - r[4] = t4; - VERIFY_BITS(r[4], 26); - /* [d u8 0 0 0 0 0 0 0 0 t9 c-u8*R0 t7 t6 t5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ - r[5] = t5; - VERIFY_BITS(r[5], 26); - /* [d u8 0 0 0 0 0 0 0 0 t9 c-u8*R0 t7 t6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ - r[6] = t6; - VERIFY_BITS(r[6], 26); - /* [d u8 0 0 0 0 0 0 0 0 t9 c-u8*R0 t7 r6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ - r[7] = t7; - VERIFY_BITS(r[7], 26); - /* [d u8 0 0 0 0 0 0 0 0 t9 c-u8*R0 r7 r6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ - - r[8] = c & M; c >>= 26; c += u8 * R1; - VERIFY_BITS(r[8], 26); - VERIFY_BITS(c, 39); - /* [d u8 0 0 0 0 0 0 0 0 t9+c-u8*R1 r8-u8*R0 r7 r6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ - /* [d 0 0 0 0 0 0 0 0 0 t9+c r8 r7 r6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ - c += d * R0 + t9; - VERIFY_BITS(c, 45); - /* [d 0 0 0 0 0 0 0 0 0 c-d*R0 r8 r7 r6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ - r[9] = c & (M >> 4); c >>= 22; c += d * (R1 << 4); - VERIFY_BITS(r[9], 22); - VERIFY_BITS(c, 46); - /* [d 0 0 0 0 0 0 0 0 r9+((c-d*R1<<4)<<22)-d*R0 r8 r7 r6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ - /* [d 0 0 0 0 0 0 0 -d*R1 r9+(c<<22)-d*R0 r8 r7 r6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ - /* [r9+(c<<22) r8 r7 r6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ - - d = c * (R0 >> 4) + t0; - VERIFY_BITS(d, 56); - /* [r9+(c<<22) r8 r7 r6 r5 r4 r3 t2 t1 d-c*R0>>4] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ - r[0] = d & M; d >>= 26; - VERIFY_BITS(r[0], 26); - VERIFY_BITS(d, 30); - /* [r9+(c<<22) r8 r7 r6 r5 r4 r3 t2 t1+d r0-c*R0>>4] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ - d += c * (R1 >> 4) + t1; - VERIFY_BITS(d, 53); - VERIFY_CHECK(d <= 0x10000003FFFFBFULL); - /* [r9+(c<<22) r8 r7 r6 r5 r4 r3 t2 d-c*R1>>4 r0-c*R0>>4] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ - /* [r9 r8 r7 r6 r5 r4 r3 t2 d r0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ - r[1] = d & M; d >>= 26; - VERIFY_BITS(r[1], 26); - VERIFY_BITS(d, 27); - VERIFY_CHECK(d <= 0x4000000ULL); - /* [r9 r8 r7 r6 r5 r4 r3 t2+d r1 r0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ - d += t2; - VERIFY_BITS(d, 27); - /* [r9 r8 r7 r6 r5 r4 r3 d r1 r0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ - r[2] = d; - VERIFY_BITS(r[2], 27); - /* [r9 r8 r7 r6 r5 r4 r3 r2 r1 r0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ -} - -SECP256K1_INLINE static void secp256k1_fe_sqr_inner(uint32_t *r, const uint32_t *a) { - uint64_t c, d; - uint64_t u0, u1, u2, u3, u4, u5, u6, u7, u8; - uint32_t t9, t0, t1, t2, t3, t4, t5, t6, t7; - const uint32_t M = 0x3FFFFFFUL, R0 = 0x3D10UL, R1 = 0x400UL; - - VERIFY_BITS(a[0], 30); - VERIFY_BITS(a[1], 30); - VERIFY_BITS(a[2], 30); - VERIFY_BITS(a[3], 30); - VERIFY_BITS(a[4], 30); - VERIFY_BITS(a[5], 30); - VERIFY_BITS(a[6], 30); - VERIFY_BITS(a[7], 30); - VERIFY_BITS(a[8], 30); - VERIFY_BITS(a[9], 26); - - /** [... a b c] is a shorthand for ... + a<<52 + b<<26 + 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 0 0 0 0 0] = [x*R1 x*R0]. - */ - - d = (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]; - /* VERIFY_BITS(d, 64); */ - /* [d 0 0 0 0 0 0 0 0 0] = [p9 0 0 0 0 0 0 0 0 0] */ - t9 = d & M; d >>= 26; - VERIFY_BITS(t9, 26); - VERIFY_BITS(d, 38); - /* [d t9 0 0 0 0 0 0 0 0 0] = [p9 0 0 0 0 0 0 0 0 0] */ - - c = (uint64_t)a[0] * a[0]; - VERIFY_BITS(c, 60); - /* [d t9 0 0 0 0 0 0 0 0 c] = [p9 0 0 0 0 0 0 0 0 p0] */ - d += (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]; - VERIFY_BITS(d, 63); - /* [d t9 0 0 0 0 0 0 0 0 c] = [p10 p9 0 0 0 0 0 0 0 0 p0] */ - u0 = d & M; d >>= 26; c += u0 * R0; - VERIFY_BITS(u0, 26); - VERIFY_BITS(d, 37); - VERIFY_BITS(c, 61); - /* [d u0 t9 0 0 0 0 0 0 0 0 c-u0*R0] = [p10 p9 0 0 0 0 0 0 0 0 p0] */ - t0 = c & M; c >>= 26; c += u0 * R1; - VERIFY_BITS(t0, 26); - VERIFY_BITS(c, 37); - /* [d u0 t9 0 0 0 0 0 0 0 c-u0*R1 t0-u0*R0] = [p10 p9 0 0 0 0 0 0 0 0 p0] */ - /* [d 0 t9 0 0 0 0 0 0 0 c t0] = [p10 p9 0 0 0 0 0 0 0 0 p0] */ - - c += (uint64_t)(a[0]*2) * a[1]; - VERIFY_BITS(c, 62); - /* [d 0 t9 0 0 0 0 0 0 0 c t0] = [p10 p9 0 0 0 0 0 0 0 p1 p0] */ - d += (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]; - VERIFY_BITS(d, 63); - /* [d 0 t9 0 0 0 0 0 0 0 c t0] = [p11 p10 p9 0 0 0 0 0 0 0 p1 p0] */ - u1 = d & M; d >>= 26; c += u1 * R0; - VERIFY_BITS(u1, 26); - VERIFY_BITS(d, 37); - VERIFY_BITS(c, 63); - /* [d u1 0 t9 0 0 0 0 0 0 0 c-u1*R0 t0] = [p11 p10 p9 0 0 0 0 0 0 0 p1 p0] */ - t1 = c & M; c >>= 26; c += u1 * R1; - VERIFY_BITS(t1, 26); - VERIFY_BITS(c, 38); - /* [d u1 0 t9 0 0 0 0 0 0 c-u1*R1 t1-u1*R0 t0] = [p11 p10 p9 0 0 0 0 0 0 0 p1 p0] */ - /* [d 0 0 t9 0 0 0 0 0 0 c t1 t0] = [p11 p10 p9 0 0 0 0 0 0 0 p1 p0] */ - - c += (uint64_t)(a[0]*2) * a[2] - + (uint64_t)a[1] * a[1]; - VERIFY_BITS(c, 62); - /* [d 0 0 t9 0 0 0 0 0 0 c t1 t0] = [p11 p10 p9 0 0 0 0 0 0 p2 p1 p0] */ - d += (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]; - VERIFY_BITS(d, 63); - /* [d 0 0 t9 0 0 0 0 0 0 c t1 t0] = [p12 p11 p10 p9 0 0 0 0 0 0 p2 p1 p0] */ - u2 = d & M; d >>= 26; c += u2 * R0; - VERIFY_BITS(u2, 26); - VERIFY_BITS(d, 37); - VERIFY_BITS(c, 63); - /* [d u2 0 0 t9 0 0 0 0 0 0 c-u2*R0 t1 t0] = [p12 p11 p10 p9 0 0 0 0 0 0 p2 p1 p0] */ - t2 = c & M; c >>= 26; c += u2 * R1; - VERIFY_BITS(t2, 26); - VERIFY_BITS(c, 38); - /* [d u2 0 0 t9 0 0 0 0 0 c-u2*R1 t2-u2*R0 t1 t0] = [p12 p11 p10 p9 0 0 0 0 0 0 p2 p1 p0] */ - /* [d 0 0 0 t9 0 0 0 0 0 c t2 t1 t0] = [p12 p11 p10 p9 0 0 0 0 0 0 p2 p1 p0] */ - - c += (uint64_t)(a[0]*2) * a[3] - + (uint64_t)(a[1]*2) * a[2]; - VERIFY_BITS(c, 63); - /* [d 0 0 0 t9 0 0 0 0 0 c t2 t1 t0] = [p12 p11 p10 p9 0 0 0 0 0 p3 p2 p1 p0] */ - d += (uint64_t)(a[4]*2) * a[9] - + (uint64_t)(a[5]*2) * a[8] - + (uint64_t)(a[6]*2) * a[7]; - VERIFY_BITS(d, 63); - /* [d 0 0 0 t9 0 0 0 0 0 c t2 t1 t0] = [p13 p12 p11 p10 p9 0 0 0 0 0 p3 p2 p1 p0] */ - u3 = d & M; d >>= 26; c += u3 * R0; - VERIFY_BITS(u3, 26); - VERIFY_BITS(d, 37); - /* VERIFY_BITS(c, 64); */ - /* [d u3 0 0 0 t9 0 0 0 0 0 c-u3*R0 t2 t1 t0] = [p13 p12 p11 p10 p9 0 0 0 0 0 p3 p2 p1 p0] */ - t3 = c & M; c >>= 26; c += u3 * R1; - VERIFY_BITS(t3, 26); - VERIFY_BITS(c, 39); - /* [d u3 0 0 0 t9 0 0 0 0 c-u3*R1 t3-u3*R0 t2 t1 t0] = [p13 p12 p11 p10 p9 0 0 0 0 0 p3 p2 p1 p0] */ - /* [d 0 0 0 0 t9 0 0 0 0 c t3 t2 t1 t0] = [p13 p12 p11 p10 p9 0 0 0 0 0 p3 p2 p1 p0] */ - - c += (uint64_t)(a[0]*2) * a[4] - + (uint64_t)(a[1]*2) * a[3] - + (uint64_t)a[2] * a[2]; - VERIFY_BITS(c, 63); - /* [d 0 0 0 0 t9 0 0 0 0 c t3 t2 t1 t0] = [p13 p12 p11 p10 p9 0 0 0 0 p4 p3 p2 p1 p0] */ - d += (uint64_t)(a[5]*2) * a[9] - + (uint64_t)(a[6]*2) * a[8] - + (uint64_t)a[7] * a[7]; - VERIFY_BITS(d, 62); - /* [d 0 0 0 0 t9 0 0 0 0 c t3 t2 t1 t0] = [p14 p13 p12 p11 p10 p9 0 0 0 0 p4 p3 p2 p1 p0] */ - u4 = d & M; d >>= 26; c += u4 * R0; - VERIFY_BITS(u4, 26); - VERIFY_BITS(d, 36); - /* VERIFY_BITS(c, 64); */ - /* [d u4 0 0 0 0 t9 0 0 0 0 c-u4*R0 t3 t2 t1 t0] = [p14 p13 p12 p11 p10 p9 0 0 0 0 p4 p3 p2 p1 p0] */ - t4 = c & M; c >>= 26; c += u4 * R1; - VERIFY_BITS(t4, 26); - VERIFY_BITS(c, 39); - /* [d u4 0 0 0 0 t9 0 0 0 c-u4*R1 t4-u4*R0 t3 t2 t1 t0] = [p14 p13 p12 p11 p10 p9 0 0 0 0 p4 p3 p2 p1 p0] */ - /* [d 0 0 0 0 0 t9 0 0 0 c t4 t3 t2 t1 t0] = [p14 p13 p12 p11 p10 p9 0 0 0 0 p4 p3 p2 p1 p0] */ - - c += (uint64_t)(a[0]*2) * a[5] - + (uint64_t)(a[1]*2) * a[4] - + (uint64_t)(a[2]*2) * a[3]; - VERIFY_BITS(c, 63); - /* [d 0 0 0 0 0 t9 0 0 0 c t4 t3 t2 t1 t0] = [p14 p13 p12 p11 p10 p9 0 0 0 p5 p4 p3 p2 p1 p0] */ - d += (uint64_t)(a[6]*2) * a[9] - + (uint64_t)(a[7]*2) * a[8]; - VERIFY_BITS(d, 62); - /* [d 0 0 0 0 0 t9 0 0 0 c t4 t3 t2 t1 t0] = [p15 p14 p13 p12 p11 p10 p9 0 0 0 p5 p4 p3 p2 p1 p0] */ - u5 = d & M; d >>= 26; c += u5 * R0; - VERIFY_BITS(u5, 26); - VERIFY_BITS(d, 36); - /* VERIFY_BITS(c, 64); */ - /* [d u5 0 0 0 0 0 t9 0 0 0 c-u5*R0 t4 t3 t2 t1 t0] = [p15 p14 p13 p12 p11 p10 p9 0 0 0 p5 p4 p3 p2 p1 p0] */ - t5 = c & M; c >>= 26; c += u5 * R1; - VERIFY_BITS(t5, 26); - VERIFY_BITS(c, 39); - /* [d u5 0 0 0 0 0 t9 0 0 c-u5*R1 t5-u5*R0 t4 t3 t2 t1 t0] = [p15 p14 p13 p12 p11 p10 p9 0 0 0 p5 p4 p3 p2 p1 p0] */ - /* [d 0 0 0 0 0 0 t9 0 0 c t5 t4 t3 t2 t1 t0] = [p15 p14 p13 p12 p11 p10 p9 0 0 0 p5 p4 p3 p2 p1 p0] */ - - 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]; - VERIFY_BITS(c, 63); - /* [d 0 0 0 0 0 0 t9 0 0 c t5 t4 t3 t2 t1 t0] = [p15 p14 p13 p12 p11 p10 p9 0 0 p6 p5 p4 p3 p2 p1 p0] */ - d += (uint64_t)(a[7]*2) * a[9] - + (uint64_t)a[8] * a[8]; - VERIFY_BITS(d, 61); - /* [d 0 0 0 0 0 0 t9 0 0 c t5 t4 t3 t2 t1 t0] = [p16 p15 p14 p13 p12 p11 p10 p9 0 0 p6 p5 p4 p3 p2 p1 p0] */ - u6 = d & M; d >>= 26; c += u6 * R0; - VERIFY_BITS(u6, 26); - VERIFY_BITS(d, 35); - /* VERIFY_BITS(c, 64); */ - /* [d u6 0 0 0 0 0 0 t9 0 0 c-u6*R0 t5 t4 t3 t2 t1 t0] = [p16 p15 p14 p13 p12 p11 p10 p9 0 0 p6 p5 p4 p3 p2 p1 p0] */ - t6 = c & M; c >>= 26; c += u6 * R1; - VERIFY_BITS(t6, 26); - VERIFY_BITS(c, 39); - /* [d u6 0 0 0 0 0 0 t9 0 c-u6*R1 t6-u6*R0 t5 t4 t3 t2 t1 t0] = [p16 p15 p14 p13 p12 p11 p10 p9 0 0 p6 p5 p4 p3 p2 p1 p0] */ - /* [d 0 0 0 0 0 0 0 t9 0 c t6 t5 t4 t3 t2 t1 t0] = [p16 p15 p14 p13 p12 p11 p10 p9 0 0 p6 p5 p4 p3 p2 p1 p0] */ - - 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]; - /* VERIFY_BITS(c, 64); */ - VERIFY_CHECK(c <= 0x8000007C00000007ULL); - /* [d 0 0 0 0 0 0 0 t9 0 c t6 t5 t4 t3 t2 t1 t0] = [p16 p15 p14 p13 p12 p11 p10 p9 0 p7 p6 p5 p4 p3 p2 p1 p0] */ - d += (uint64_t)(a[8]*2) * a[9]; - VERIFY_BITS(d, 58); - /* [d 0 0 0 0 0 0 0 t9 0 c t6 t5 t4 t3 t2 t1 t0] = [p17 p16 p15 p14 p13 p12 p11 p10 p9 0 p7 p6 p5 p4 p3 p2 p1 p0] */ - u7 = d & M; d >>= 26; c += u7 * R0; - VERIFY_BITS(u7, 26); - VERIFY_BITS(d, 32); - /* VERIFY_BITS(c, 64); */ - VERIFY_CHECK(c <= 0x800001703FFFC2F7ULL); - /* [d u7 0 0 0 0 0 0 0 t9 0 c-u7*R0 t6 t5 t4 t3 t2 t1 t0] = [p17 p16 p15 p14 p13 p12 p11 p10 p9 0 p7 p6 p5 p4 p3 p2 p1 p0] */ - t7 = c & M; c >>= 26; c += u7 * R1; - VERIFY_BITS(t7, 26); - VERIFY_BITS(c, 38); - /* [d u7 0 0 0 0 0 0 0 t9 c-u7*R1 t7-u7*R0 t6 t5 t4 t3 t2 t1 t0] = [p17 p16 p15 p14 p13 p12 p11 p10 p9 0 p7 p6 p5 p4 p3 p2 p1 p0] */ - /* [d 0 0 0 0 0 0 0 0 t9 c t7 t6 t5 t4 t3 t2 t1 t0] = [p17 p16 p15 p14 p13 p12 p11 p10 p9 0 p7 p6 p5 p4 p3 p2 p1 p0] */ - - 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]; - /* VERIFY_BITS(c, 64); */ - VERIFY_CHECK(c <= 0x9000007B80000008ULL); - /* [d 0 0 0 0 0 0 0 0 t9 c t7 t6 t5 t4 t3 t2 t1 t0] = [p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ - d += (uint64_t)a[9] * a[9]; - VERIFY_BITS(d, 57); - /* [d 0 0 0 0 0 0 0 0 t9 c t7 t6 t5 t4 t3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ - u8 = d & M; d >>= 26; c += u8 * R0; - VERIFY_BITS(u8, 26); - VERIFY_BITS(d, 31); - /* VERIFY_BITS(c, 64); */ - VERIFY_CHECK(c <= 0x9000016FBFFFC2F8ULL); - /* [d u8 0 0 0 0 0 0 0 0 t9 c-u8*R0 t7 t6 t5 t4 t3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ - - r[3] = t3; - VERIFY_BITS(r[3], 26); - /* [d u8 0 0 0 0 0 0 0 0 t9 c-u8*R0 t7 t6 t5 t4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ - r[4] = t4; - VERIFY_BITS(r[4], 26); - /* [d u8 0 0 0 0 0 0 0 0 t9 c-u8*R0 t7 t6 t5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ - r[5] = t5; - VERIFY_BITS(r[5], 26); - /* [d u8 0 0 0 0 0 0 0 0 t9 c-u8*R0 t7 t6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ - r[6] = t6; - VERIFY_BITS(r[6], 26); - /* [d u8 0 0 0 0 0 0 0 0 t9 c-u8*R0 t7 r6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ - r[7] = t7; - VERIFY_BITS(r[7], 26); - /* [d u8 0 0 0 0 0 0 0 0 t9 c-u8*R0 r7 r6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ - - r[8] = c & M; c >>= 26; c += u8 * R1; - VERIFY_BITS(r[8], 26); - VERIFY_BITS(c, 39); - /* [d u8 0 0 0 0 0 0 0 0 t9+c-u8*R1 r8-u8*R0 r7 r6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ - /* [d 0 0 0 0 0 0 0 0 0 t9+c r8 r7 r6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ - c += d * R0 + t9; - VERIFY_BITS(c, 45); - /* [d 0 0 0 0 0 0 0 0 0 c-d*R0 r8 r7 r6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ - r[9] = c & (M >> 4); c >>= 22; c += d * (R1 << 4); - VERIFY_BITS(r[9], 22); - VERIFY_BITS(c, 46); - /* [d 0 0 0 0 0 0 0 0 r9+((c-d*R1<<4)<<22)-d*R0 r8 r7 r6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ - /* [d 0 0 0 0 0 0 0 -d*R1 r9+(c<<22)-d*R0 r8 r7 r6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ - /* [r9+(c<<22) r8 r7 r6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ - - d = c * (R0 >> 4) + t0; - VERIFY_BITS(d, 56); - /* [r9+(c<<22) r8 r7 r6 r5 r4 r3 t2 t1 d-c*R0>>4] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ - r[0] = d & M; d >>= 26; - VERIFY_BITS(r[0], 26); - VERIFY_BITS(d, 30); - /* [r9+(c<<22) r8 r7 r6 r5 r4 r3 t2 t1+d r0-c*R0>>4] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ - d += c * (R1 >> 4) + t1; - VERIFY_BITS(d, 53); - VERIFY_CHECK(d <= 0x10000003FFFFBFULL); - /* [r9+(c<<22) r8 r7 r6 r5 r4 r3 t2 d-c*R1>>4 r0-c*R0>>4] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ - /* [r9 r8 r7 r6 r5 r4 r3 t2 d r0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ - r[1] = d & M; d >>= 26; - VERIFY_BITS(r[1], 26); - VERIFY_BITS(d, 27); - VERIFY_CHECK(d <= 0x4000000ULL); - /* [r9 r8 r7 r6 r5 r4 r3 t2+d r1 r0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ - d += t2; - VERIFY_BITS(d, 27); - /* [r9 r8 r7 r6 r5 r4 r3 d r1 r0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ - r[2] = d; - VERIFY_BITS(r[2], 27); - /* [r9 r8 r7 r6 r5 r4 r3 r2 r1 r0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ -} - - -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) { - uint32_t mask0, mask1; - mask0 = flag + ~((uint32_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); - r->n[4] = (r->n[4] & mask0) | (a->n[4] & mask1); - r->n[5] = (r->n[5] & mask0) | (a->n[5] & mask1); - r->n[6] = (r->n[6] & mask0) | (a->n[6] & mask1); - r->n[7] = (r->n[7] & mask0) | (a->n[7] & 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] << 26; - r->n[1] = a->n[1] >> 6 | a->n[2] << 20; - r->n[2] = a->n[2] >> 12 | a->n[3] << 14; - r->n[3] = a->n[3] >> 18 | a->n[4] << 8; - r->n[4] = a->n[4] >> 24 | a->n[5] << 2 | a->n[6] << 28; - r->n[5] = a->n[6] >> 4 | a->n[7] << 22; - r->n[6] = a->n[7] >> 10 | a->n[8] << 16; - r->n[7] = a->n[8] >> 16 | a->n[9] << 10; -} - -static SECP256K1_INLINE void secp256k1_fe_from_storage(secp256k1_fe_t *r, const secp256k1_fe_storage_t *a) { - r->n[0] = a->n[0] & 0x3FFFFFFUL; - r->n[1] = a->n[0] >> 26 | ((a->n[1] << 6) & 0x3FFFFFFUL); - r->n[2] = a->n[1] >> 20 | ((a->n[2] << 12) & 0x3FFFFFFUL); - r->n[3] = a->n[2] >> 14 | ((a->n[3] << 18) & 0x3FFFFFFUL); - r->n[4] = a->n[3] >> 8 | ((a->n[4] << 24) & 0x3FFFFFFUL); - r->n[5] = (a->n[4] >> 2) & 0x3FFFFFFUL; - r->n[6] = a->n[4] >> 28 | ((a->n[5] << 4) & 0x3FFFFFFUL); - r->n[7] = a->n[5] >> 22 | ((a->n[6] << 10) & 0x3FFFFFFUL); - r->n[8] = a->n[6] >> 16 | ((a->n[7] << 16) & 0x3FFFFFFUL); - r->n[9] = a->n[7] >> 10; -#ifdef VERIFY - r->magnitude = 1; - r->normalized = 1; -#endif -} - -#endif diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/field_5x52.h b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/field_5x52.h deleted file mode 100644 index 4513d36f49f3fde2aec60861afe0ed534815b746..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/field_5x52.h +++ /dev/null @@ -1,47 +0,0 @@ -/********************************************************************** - * 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_ - -#include <stdint.h> - -typedef struct { - /* X = sum(i=0..4, elem[i]*2^52) mod n */ - uint64_t n[5]; -#ifdef VERIFY - int magnitude; - int normalized; -#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 diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/field_5x52_asm_impl.h b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/field_5x52_asm_impl.h deleted file mode 100644 index 98cc004bf04a69c201c996a7f1c3ccac68354b5e..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/field_5x52_asm_impl.h +++ /dev/null @@ -1,502 +0,0 @@ -/********************************************************************** - * 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 diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/field_5x52_impl.h b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/field_5x52_impl.h deleted file mode 100644 index 874d3caaba65c8409cd47e370b7e2a7ed32d0817..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/field_5x52_impl.h +++ /dev/null @@ -1,439 +0,0 @@ -/********************************************************************** - * 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 diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/field_5x52_int128_impl.h b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/field_5x52_int128_impl.h deleted file mode 100644 index 9280bb5ea221645b4a7fc2459ee1053f433abe3a..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/field_5x52_int128_impl.h +++ /dev/null @@ -1,277 +0,0 @@ -/********************************************************************** - * 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 diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/field_impl.h b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/field_impl.h deleted file mode 100644 index e6ec11e8f2c48c88863b61cb34dd6d778aa2da03..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/field_impl.h +++ /dev/null @@ -1,263 +0,0 @@ -/********************************************************************** - * 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 diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/group.h b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/group.h deleted file mode 100644 index d1e58349096847ab32988313fda39703d685105d..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/group.h +++ /dev/null @@ -1,118 +0,0 @@ -/********************************************************************** - * 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_ - -#include "num.h" -#include "field.h" - -/** A group element of the secp256k1 curve, in affine coordinates. */ -typedef struct { - secp256k1_fe_t x; - secp256k1_fe_t y; - 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 z; - int infinity; /* whether this represents the point at infinity */ -} secp256k1_gej_t; - -#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_fe_storage_t x; - secp256k1_fe_storage_t y; -} secp256k1_ge_storage_t; - -#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 */ -static void secp256k1_ge_set_infinity(secp256k1_ge_t *r); - -/** Set a group element equal to the point with given X and Y coordinates */ -static void secp256k1_ge_set_xy(secp256k1_ge_t *r, const secp256k1_fe_t *x, const secp256k1_fe_t *y); - -/** 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. */ -static int secp256k1_ge_is_infinity(const secp256k1_ge_t *a); - -/** Check whether a group element is valid (i.e., on the curve). */ -static int secp256k1_ge_is_valid_var(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 */ -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. */ -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. */ -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. */ -static void secp256k1_gej_set_ge(secp256k1_gej_t *r, const secp256k1_ge_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) */ -static void secp256k1_gej_neg(secp256k1_gej_t *r, const secp256k1_gej_t *a); - -/** Check whether a group element is the point at infinity. */ -static int secp256k1_gej_is_infinity(const secp256k1_gej_t *a); - -/** Set r equal to the double of 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. */ -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 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); - -/** 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. */ -static void secp256k1_gej_mul_lambda(secp256k1_gej_t *r, const secp256k1_gej_t *a); -#endif - -/** 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 diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/group_impl.h b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/group_impl.h deleted file mode 100644 index 0d1c7b02ff3b7f50c50dfa637665b5d8deb7b529..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/group_impl.h +++ /dev/null @@ -1,434 +0,0 @@ -/********************************************************************** - * 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 diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/hash.h b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/hash.h deleted file mode 100644 index 843423d7f70ab6958ba5ef22d28fb92823d5e2eb..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/hash.h +++ /dev/null @@ -1,41 +0,0 @@ -/********************************************************************** - * 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 diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/hash_impl.h b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/hash_impl.h deleted file mode 100644 index 9828827bcdb2d872478b57e33a671e20ea906d2c..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/hash_impl.h +++ /dev/null @@ -1,293 +0,0 @@ -/********************************************************************** - * 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 diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/java/org/bitcoin/NativeSecp256k1.java b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/java/org/bitcoin/NativeSecp256k1.java deleted file mode 100644 index 90a498eaa2c40ba17b627a4406fc8af6521e2e0b..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/java/org/bitcoin/NativeSecp256k1.java +++ /dev/null @@ -1,60 +0,0 @@ -package org.bitcoin; - -import java.nio.ByteBuffer; -import java.nio.ByteOrder; - -import com.google.common.base.Preconditions; - - -/** - * This class holds native methods to handle ECDSA verification. - * You can find an example library that can be used for this at - * https://github.com/sipa/secp256k1 - */ -public class NativeSecp256k1 { - public static final boolean enabled; - static { - boolean isEnabled = true; - try { - System.loadLibrary("javasecp256k1"); - } catch (UnsatisfiedLinkError e) { - isEnabled = false; - } - enabled = isEnabled; - } - - private static ThreadLocal<ByteBuffer> nativeECDSABuffer = new ThreadLocal<ByteBuffer>(); - /** - * Verifies the given secp256k1 signature in native code. - * Calling when enabled == false is undefined (probably library not loaded) - * - * @param data The data which was signed, must be exactly 32 bytes - * @param signature The signature - * @param pub The public key which did the signing - */ - public static boolean verify(byte[] data, byte[] signature, byte[] pub) { - Preconditions.checkArgument(data.length == 32 && signature.length <= 520 && pub.length <= 520); - - ByteBuffer byteBuff = nativeECDSABuffer.get(); - if (byteBuff == null) { - byteBuff = ByteBuffer.allocateDirect(32 + 8 + 520 + 520); - byteBuff.order(ByteOrder.nativeOrder()); - nativeECDSABuffer.set(byteBuff); - } - byteBuff.rewind(); - byteBuff.put(data); - byteBuff.putInt(signature.length); - byteBuff.putInt(pub.length); - byteBuff.put(signature); - byteBuff.put(pub); - return secp256k1_ecdsa_verify(byteBuff) == 1; - } - - /** - * @param byteBuff signature format is byte[32] data, - * native-endian int signatureLength, native-endian int pubkeyLength, - * byte[signatureLength] signature, byte[pubkeyLength] pub - * @returns 1 for valid signature, anything else for invalid - */ - private static native int secp256k1_ecdsa_verify(ByteBuffer byteBuff); -} diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/java/org_bitcoin_NativeSecp256k1.c b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/java/org_bitcoin_NativeSecp256k1.c deleted file mode 100644 index bb4cd707280a68f1377e90f7a9d434e194bfa6db..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/java/org_bitcoin_NativeSecp256k1.c +++ /dev/null @@ -1,23 +0,0 @@ -#include "org_bitcoin_NativeSecp256k1.h" -#include "include/secp256k1.h" - -JNIEXPORT jint JNICALL Java_org_bitcoin_NativeSecp256k1_secp256k1_1ecdsa_1verify - (JNIEnv* env, jclass classObject, jobject byteBufferObject) -{ - unsigned char* data = (unsigned char*) (*env)->GetDirectBufferAddress(env, byteBufferObject); - int sigLen = *((int*)(data + 32)); - int pubLen = *((int*)(data + 32 + 4)); - - return secp256k1_ecdsa_verify(data, 32, data+32+8, sigLen, data+32+8+sigLen, pubLen); -} - -static void __javasecp256k1_attach(void) __attribute__((constructor)); -static void __javasecp256k1_detach(void) __attribute__((destructor)); - -static void __javasecp256k1_attach(void) { - secp256k1_start(SECP256K1_START_VERIFY); -} - -static void __javasecp256k1_detach(void) { - secp256k1_stop(); -} diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/java/org_bitcoin_NativeSecp256k1.h b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/java/org_bitcoin_NativeSecp256k1.h deleted file mode 100644 index d7fb004fa841ede0fb2e919aa567d092e8fc2d5a..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/java/org_bitcoin_NativeSecp256k1.h +++ /dev/null @@ -1,21 +0,0 @@ -/* DO NOT EDIT THIS FILE - it is machine generated */ -#include <jni.h> -/* Header for class org_bitcoin_NativeSecp256k1 */ - -#ifndef _Included_org_bitcoin_NativeSecp256k1 -#define _Included_org_bitcoin_NativeSecp256k1 -#ifdef __cplusplus -extern "C" { -#endif -/* - * Class: org_bitcoin_NativeSecp256k1 - * Method: secp256k1_ecdsa_verify - * Signature: (Ljava/nio/ByteBuffer;)I - */ -JNIEXPORT jint JNICALL Java_org_bitcoin_NativeSecp256k1_secp256k1_1ecdsa_1verify - (JNIEnv *, jclass, jobject); - -#ifdef __cplusplus -} -#endif -#endif diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/num.h b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/num.h deleted file mode 100644 index 339b6bb6ec2c2a2ee2d2d75473f2c1b44eaa9a3f..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/num.h +++ /dev/null @@ -1,68 +0,0 @@ -/********************************************************************** - * 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_NUM_ -#define _SECP256K1_NUM_ - -#ifndef USE_NUM_NONE - -#if defined HAVE_CONFIG_H -#include "libsecp256k1-config.h" -#endif - -#if defined(USE_NUM_GMP) -#include "num_gmp.h" -#else -#error "Please select num implementation" -#endif - -/** Copy a number. */ -static void secp256k1_num_copy(secp256k1_num_t *r, const secp256k1_num_t *a); - -/** Convert a number's absolute value to a binary big-endian string. - * There must be enough place. */ -static void secp256k1_num_get_bin(unsigned char *r, unsigned int rlen, const secp256k1_num_t *a); - -/** Set a number to the value of a binary big-endian string. */ -static void secp256k1_num_set_bin(secp256k1_num_t *r, const unsigned char *a, unsigned int alen); - -/** Compute a modular inverse. The input must be less than the modulus. */ -static void secp256k1_num_mod_inverse(secp256k1_num_t *r, const secp256k1_num_t *a, const secp256k1_num_t *m); - -/** Compare the absolute value of two numbers. */ -static int secp256k1_num_cmp(const secp256k1_num_t *a, const secp256k1_num_t *b); - -/** Test whether two number are equal (including sign). */ -static int secp256k1_num_eq(const secp256k1_num_t *a, const secp256k1_num_t *b); - -/** Add two (signed) numbers. */ -static void secp256k1_num_add(secp256k1_num_t *r, const secp256k1_num_t *a, const secp256k1_num_t *b); - -/** Subtract two (signed) numbers. */ -static void secp256k1_num_sub(secp256k1_num_t *r, const secp256k1_num_t *a, const secp256k1_num_t *b); - -/** Multiply two (signed) numbers. */ -static void secp256k1_num_mul(secp256k1_num_t *r, const secp256k1_num_t *a, const secp256k1_num_t *b); - -/** Replace a number by its remainder modulo m. M's sign is ignored. The result is a number between 0 and m-1, - even if r was negative. */ -static void secp256k1_num_mod(secp256k1_num_t *r, const secp256k1_num_t *m); - -/** Right-shift the passed number by bits bits. */ -static void secp256k1_num_shift(secp256k1_num_t *r, int bits); - -/** Check whether a number is zero. */ -static int secp256k1_num_is_zero(const secp256k1_num_t *a); - -/** Check whether a number is strictly negative. */ -static int secp256k1_num_is_neg(const secp256k1_num_t *a); - -/** Change a number's sign. */ -static void secp256k1_num_negate(secp256k1_num_t *r); - -#endif - -#endif diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/num_gmp.h b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/num_gmp.h deleted file mode 100644 index baa1f2bf2e4d56260d15c570fe04f47f3c60141b..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/num_gmp.h +++ /dev/null @@ -1,20 +0,0 @@ -/********************************************************************** - * 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_NUM_REPR_ -#define _SECP256K1_NUM_REPR_ - -#include <gmp.h> - -#define NUM_LIMBS ((256+GMP_NUMB_BITS-1)/GMP_NUMB_BITS) - -typedef struct { - mp_limb_t data[2*NUM_LIMBS]; - int neg; - int limbs; -} secp256k1_num_t; - -#endif diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/num_gmp_impl.h b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/num_gmp_impl.h deleted file mode 100644 index dbbc458d5ddc7d1cea67a14e1678e9dc81881bf2..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/num_gmp_impl.h +++ /dev/null @@ -1,260 +0,0 @@ -/********************************************************************** - * 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_NUM_REPR_IMPL_H_ -#define _SECP256K1_NUM_REPR_IMPL_H_ - -#include <string.h> -#include <stdlib.h> -#include <gmp.h> - -#include "util.h" -#include "num.h" - -#ifdef VERIFY -static void secp256k1_num_sanity(const secp256k1_num_t *a) { - VERIFY_CHECK(a->limbs == 1 || (a->limbs > 1 && a->data[a->limbs-1] != 0)); -} -#else -#define secp256k1_num_sanity(a) do { } while(0) -#endif - -static void secp256k1_num_copy(secp256k1_num_t *r, const secp256k1_num_t *a) { - *r = *a; -} - -static void secp256k1_num_get_bin(unsigned char *r, unsigned int rlen, const secp256k1_num_t *a) { - unsigned char tmp[65]; - int len = 0; - int shift = 0; - if (a->limbs>1 || a->data[0] != 0) { - len = mpn_get_str(tmp, 256, (mp_limb_t*)a->data, a->limbs); - } - while (shift < len && tmp[shift] == 0) shift++; - VERIFY_CHECK(len-shift <= (int)rlen); - memset(r, 0, rlen - len + shift); - if (len > shift) { - memcpy(r + rlen - len + shift, tmp + shift, len - shift); - } - memset(tmp, 0, sizeof(tmp)); -} - -static void secp256k1_num_set_bin(secp256k1_num_t *r, const unsigned char *a, unsigned int alen) { - int len; - VERIFY_CHECK(alen > 0); - VERIFY_CHECK(alen <= 64); - len = mpn_set_str(r->data, a, alen, 256); - if (len == 0) { - r->data[0] = 0; - len = 1; - } - VERIFY_CHECK(len <= NUM_LIMBS*2); - r->limbs = len; - r->neg = 0; - while (r->limbs > 1 && r->data[r->limbs-1]==0) { - r->limbs--; - } -} - -static void secp256k1_num_add_abs(secp256k1_num_t *r, const secp256k1_num_t *a, const secp256k1_num_t *b) { - mp_limb_t c = mpn_add(r->data, a->data, a->limbs, b->data, b->limbs); - r->limbs = a->limbs; - if (c != 0) { - VERIFY_CHECK(r->limbs < 2*NUM_LIMBS); - r->data[r->limbs++] = c; - } -} - -static void secp256k1_num_sub_abs(secp256k1_num_t *r, const secp256k1_num_t *a, const secp256k1_num_t *b) { - mp_limb_t c = mpn_sub(r->data, a->data, a->limbs, b->data, b->limbs); - VERIFY_CHECK(c == 0); - r->limbs = a->limbs; - while (r->limbs > 1 && r->data[r->limbs-1]==0) { - r->limbs--; - } -} - -static void secp256k1_num_mod(secp256k1_num_t *r, const secp256k1_num_t *m) { - secp256k1_num_sanity(r); - secp256k1_num_sanity(m); - - if (r->limbs >= m->limbs) { - mp_limb_t t[2*NUM_LIMBS]; - mpn_tdiv_qr(t, r->data, 0, r->data, r->limbs, m->data, m->limbs); - memset(t, 0, sizeof(t)); - r->limbs = m->limbs; - while (r->limbs > 1 && r->data[r->limbs-1]==0) { - r->limbs--; - } - } - - if (r->neg && (r->limbs > 1 || r->data[0] != 0)) { - secp256k1_num_sub_abs(r, m, r); - r->neg = 0; - } -} - -static void secp256k1_num_mod_inverse(secp256k1_num_t *r, const secp256k1_num_t *a, const secp256k1_num_t *m) { - int i; - mp_limb_t g[NUM_LIMBS+1]; - mp_limb_t u[NUM_LIMBS+1]; - mp_limb_t v[NUM_LIMBS+1]; - mp_size_t sn; - mp_size_t gn; - secp256k1_num_sanity(a); - secp256k1_num_sanity(m); - - /** mpn_gcdext computes: (G,S) = gcdext(U,V), where - * * G = gcd(U,V) - * * G = U*S + V*T - * * U has equal or more limbs than V, and V has no padding - * If we set U to be (a padded version of) a, and V = m: - * G = a*S + m*T - * G = a*S mod m - * Assuming G=1: - * S = 1/a mod m - */ - VERIFY_CHECK(m->limbs <= NUM_LIMBS); - VERIFY_CHECK(m->data[m->limbs-1] != 0); - for (i = 0; i < m->limbs; i++) { - u[i] = (i < a->limbs) ? a->data[i] : 0; - v[i] = m->data[i]; - } - sn = NUM_LIMBS+1; - gn = mpn_gcdext(g, r->data, &sn, u, m->limbs, v, m->limbs); - VERIFY_CHECK(gn == 1); - VERIFY_CHECK(g[0] == 1); - r->neg = a->neg ^ m->neg; - if (sn < 0) { - mpn_sub(r->data, m->data, m->limbs, r->data, -sn); - r->limbs = m->limbs; - while (r->limbs > 1 && r->data[r->limbs-1]==0) { - r->limbs--; - } - } else { - r->limbs = sn; - } - memset(g, 0, sizeof(g)); - memset(u, 0, sizeof(u)); - memset(v, 0, sizeof(v)); -} - -static int secp256k1_num_is_zero(const secp256k1_num_t *a) { - return (a->limbs == 1 && a->data[0] == 0); -} - -static int secp256k1_num_is_neg(const secp256k1_num_t *a) { - return (a->limbs > 1 || a->data[0] != 0) && a->neg; -} - -static int secp256k1_num_cmp(const secp256k1_num_t *a, const secp256k1_num_t *b) { - if (a->limbs > b->limbs) { - return 1; - } - if (a->limbs < b->limbs) { - return -1; - } - return mpn_cmp(a->data, b->data, a->limbs); -} - -static int secp256k1_num_eq(const secp256k1_num_t *a, const secp256k1_num_t *b) { - if (a->limbs > b->limbs) { - return 0; - } - if (a->limbs < b->limbs) { - return 0; - } - if ((a->neg && !secp256k1_num_is_zero(a)) != (b->neg && !secp256k1_num_is_zero(b))) { - return 0; - } - return mpn_cmp(a->data, b->data, a->limbs) == 0; -} - -static void secp256k1_num_subadd(secp256k1_num_t *r, const secp256k1_num_t *a, const secp256k1_num_t *b, int bneg) { - if (!(b->neg ^ bneg ^ a->neg)) { /* a and b have the same sign */ - r->neg = a->neg; - if (a->limbs >= b->limbs) { - secp256k1_num_add_abs(r, a, b); - } else { - secp256k1_num_add_abs(r, b, a); - } - } else { - if (secp256k1_num_cmp(a, b) > 0) { - r->neg = a->neg; - secp256k1_num_sub_abs(r, a, b); - } else { - r->neg = b->neg ^ bneg; - secp256k1_num_sub_abs(r, b, a); - } - } -} - -static void secp256k1_num_add(secp256k1_num_t *r, const secp256k1_num_t *a, const secp256k1_num_t *b) { - secp256k1_num_sanity(a); - secp256k1_num_sanity(b); - secp256k1_num_subadd(r, a, b, 0); -} - -static void secp256k1_num_sub(secp256k1_num_t *r, const secp256k1_num_t *a, const secp256k1_num_t *b) { - secp256k1_num_sanity(a); - secp256k1_num_sanity(b); - secp256k1_num_subadd(r, a, b, 1); -} - -static void secp256k1_num_mul(secp256k1_num_t *r, const secp256k1_num_t *a, const secp256k1_num_t *b) { - mp_limb_t tmp[2*NUM_LIMBS+1]; - secp256k1_num_sanity(a); - secp256k1_num_sanity(b); - - VERIFY_CHECK(a->limbs + b->limbs <= 2*NUM_LIMBS+1); - if ((a->limbs==1 && a->data[0]==0) || (b->limbs==1 && b->data[0]==0)) { - r->limbs = 1; - r->neg = 0; - r->data[0] = 0; - return; - } - if (a->limbs >= b->limbs) { - mpn_mul(tmp, a->data, a->limbs, b->data, b->limbs); - } else { - mpn_mul(tmp, b->data, b->limbs, a->data, a->limbs); - } - r->limbs = a->limbs + b->limbs; - if (r->limbs > 1 && tmp[r->limbs - 1]==0) { - r->limbs--; - } - VERIFY_CHECK(r->limbs <= 2*NUM_LIMBS); - mpn_copyi(r->data, tmp, r->limbs); - r->neg = a->neg ^ b->neg; - memset(tmp, 0, sizeof(tmp)); -} - -static void secp256k1_num_shift(secp256k1_num_t *r, int bits) { - int i; - if (bits % GMP_NUMB_BITS) { - /* Shift within limbs. */ - mpn_rshift(r->data, r->data, r->limbs, bits % GMP_NUMB_BITS); - } - if (bits >= GMP_NUMB_BITS) { - /* Shift full limbs. */ - for (i = 0; i < r->limbs; i++) { - int index = i + (bits / GMP_NUMB_BITS); - if (index < r->limbs && index < 2*NUM_LIMBS) { - r->data[i] = r->data[index]; - } else { - r->data[i] = 0; - } - } - } - while (r->limbs>1 && r->data[r->limbs-1]==0) { - r->limbs--; - } -} - -static void secp256k1_num_negate(secp256k1_num_t *r) { - r->neg ^= 1; -} - -#endif diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/num_impl.h b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/num_impl.h deleted file mode 100644 index 0b0e3a072a15ac5ddd1575d1968578c0ffce9400..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/num_impl.h +++ /dev/null @@ -1,24 +0,0 @@ -/********************************************************************** - * 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_NUM_IMPL_H_ -#define _SECP256K1_NUM_IMPL_H_ - -#if defined HAVE_CONFIG_H -#include "libsecp256k1-config.h" -#endif - -#include "num.h" - -#if defined(USE_NUM_GMP) -#include "num_gmp_impl.h" -#elif defined(USE_NUM_NONE) -/* Nothing. */ -#else -#error "Please select num implementation" -#endif - -#endif diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/scalar.h b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/scalar.h deleted file mode 100644 index f5d09f8d474af52153d16108656176285c953e28..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/scalar.h +++ /dev/null @@ -1,93 +0,0 @@ -/********************************************************************** - * 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_SCALAR_ -#define _SECP256K1_SCALAR_ - -#include "num.h" - -#if defined HAVE_CONFIG_H -#include "libsecp256k1-config.h" -#endif - -#if defined(USE_SCALAR_4X64) -#include "scalar_4x64.h" -#elif defined(USE_SCALAR_8X32) -#include "scalar_8x32.h" -#else -#error "Please select scalar implementation" -#endif - -/** Clear a scalar to prevent the leak of sensitive data. */ -static void secp256k1_scalar_clear(secp256k1_scalar_t *r); - -/** Access bits from a scalar. All requested bits must belong to the same 32-bit limb. */ -static unsigned int secp256k1_scalar_get_bits(const secp256k1_scalar_t *a, unsigned int offset, unsigned int count); - -/** Access bits from a scalar. Not constant time. */ -static unsigned int secp256k1_scalar_get_bits_var(const secp256k1_scalar_t *a, unsigned int offset, unsigned int count); - -/** Set a scalar from a big endian byte array. */ -static void secp256k1_scalar_set_b32(secp256k1_scalar_t *r, const unsigned char *bin, int *overflow); - -/** Set a scalar to an unsigned integer. */ -static void secp256k1_scalar_set_int(secp256k1_scalar_t *r, unsigned int v); - -/** Convert a scalar to a byte array. */ -static void secp256k1_scalar_get_b32(unsigned char *bin, const secp256k1_scalar_t* a); - -/** Add two scalars together (modulo the group order). Returns whether it overflowed. */ -static int secp256k1_scalar_add(secp256k1_scalar_t *r, const secp256k1_scalar_t *a, const secp256k1_scalar_t *b); - -/** Add a power of two to a scalar. The result is not allowed to overflow. */ -static void secp256k1_scalar_add_bit(secp256k1_scalar_t *r, unsigned int bit); - -/** Multiply two scalars (modulo the group order). */ -static void secp256k1_scalar_mul(secp256k1_scalar_t *r, const secp256k1_scalar_t *a, const secp256k1_scalar_t *b); - -/** Compute the square of a scalar (modulo the group order). */ -static void secp256k1_scalar_sqr(secp256k1_scalar_t *r, const secp256k1_scalar_t *a); - -/** Compute the inverse of a scalar (modulo the group order). */ -static void secp256k1_scalar_inverse(secp256k1_scalar_t *r, const secp256k1_scalar_t *a); - -/** Compute the inverse of a scalar (modulo the group order), without constant-time guarantee. */ -static void secp256k1_scalar_inverse_var(secp256k1_scalar_t *r, const secp256k1_scalar_t *a); - -/** Compute the complement of a scalar (modulo the group order). */ -static void secp256k1_scalar_negate(secp256k1_scalar_t *r, const secp256k1_scalar_t *a); - -/** Check whether a scalar equals zero. */ -static int secp256k1_scalar_is_zero(const secp256k1_scalar_t *a); - -/** Check whether a scalar equals one. */ -static int secp256k1_scalar_is_one(const secp256k1_scalar_t *a); - -/** Check whether a scalar is higher than the group order divided by 2. */ -static int secp256k1_scalar_is_high(const secp256k1_scalar_t *a); - -#ifndef USE_NUM_NONE -/** Convert a scalar to a number. */ -static void secp256k1_scalar_get_num(secp256k1_num_t *r, const secp256k1_scalar_t *a); - -/** Get the order of the group as a number. */ -static void secp256k1_scalar_order_get_num(secp256k1_num_t *r); -#endif - -/** Compare two scalars. */ -static int secp256k1_scalar_eq(const secp256k1_scalar_t *a, const secp256k1_scalar_t *b); - -#ifdef USE_ENDOMORPHISM -/** Find r1 and r2 such that r1+r2*2^128 = a. */ -static void secp256k1_scalar_split_128(secp256k1_scalar_t *r1, secp256k1_scalar_t *r2, const secp256k1_scalar_t *a); -/** Find r1 and r2 such that r1+r2*lambda = a, and r1 and r2 are maximum 128 bits long (see secp256k1_gej_mul_lambda). */ -static void secp256k1_scalar_split_lambda_var(secp256k1_scalar_t *r1, secp256k1_scalar_t *r2, const secp256k1_scalar_t *a); -#endif - -/** Multiply a and b (without taking the modulus!), divide by 2**shift, and round to the nearest integer. Shift must be at least 256. */ -static void secp256k1_scalar_mul_shift_var(secp256k1_scalar_t *r, const secp256k1_scalar_t *a, const secp256k1_scalar_t *b, unsigned int shift); - -#endif diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/scalar_4x64.h b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/scalar_4x64.h deleted file mode 100644 index 82899aa7b047ae8a5f4ce7d9bc2054b3045160d3..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/scalar_4x64.h +++ /dev/null @@ -1,19 +0,0 @@ -/********************************************************************** - * 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_SCALAR_REPR_ -#define _SECP256K1_SCALAR_REPR_ - -#include <stdint.h> - -/** A scalar modulo the group order of the secp256k1 curve. */ -typedef struct { - uint64_t d[4]; -} secp256k1_scalar_t; - -#define SECP256K1_SCALAR_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {{((uint64_t)(d1)) << 32 | (d0), ((uint64_t)(d3)) << 32 | (d2), ((uint64_t)(d5)) << 32 | (d4), ((uint64_t)(d7)) << 32 | (d6)}} - -#endif diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/scalar_4x64_impl.h b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/scalar_4x64_impl.h deleted file mode 100644 index ff365292f86f0f2237e4948f0b11c52fac1881d9..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/scalar_4x64_impl.h +++ /dev/null @@ -1,920 +0,0 @@ -/********************************************************************** - * 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_SCALAR_REPR_IMPL_H_ -#define _SECP256K1_SCALAR_REPR_IMPL_H_ - -/* Limbs of the secp256k1 order. */ -#define SECP256K1_N_0 ((uint64_t)0xBFD25E8CD0364141ULL) -#define SECP256K1_N_1 ((uint64_t)0xBAAEDCE6AF48A03BULL) -#define SECP256K1_N_2 ((uint64_t)0xFFFFFFFFFFFFFFFEULL) -#define SECP256K1_N_3 ((uint64_t)0xFFFFFFFFFFFFFFFFULL) - -/* Limbs of 2^256 minus the secp256k1 order. */ -#define SECP256K1_N_C_0 (~SECP256K1_N_0 + 1) -#define SECP256K1_N_C_1 (~SECP256K1_N_1) -#define SECP256K1_N_C_2 (1) - -/* Limbs of half the secp256k1 order. */ -#define SECP256K1_N_H_0 ((uint64_t)0xDFE92F46681B20A0ULL) -#define SECP256K1_N_H_1 ((uint64_t)0x5D576E7357A4501DULL) -#define SECP256K1_N_H_2 ((uint64_t)0xFFFFFFFFFFFFFFFFULL) -#define SECP256K1_N_H_3 ((uint64_t)0x7FFFFFFFFFFFFFFFULL) - -SECP256K1_INLINE static void secp256k1_scalar_clear(secp256k1_scalar_t *r) { - r->d[0] = 0; - r->d[1] = 0; - r->d[2] = 0; - r->d[3] = 0; -} - -SECP256K1_INLINE static void secp256k1_scalar_set_int(secp256k1_scalar_t *r, unsigned int v) { - r->d[0] = v; - r->d[1] = 0; - r->d[2] = 0; - r->d[3] = 0; -} - -SECP256K1_INLINE static unsigned int secp256k1_scalar_get_bits(const secp256k1_scalar_t *a, unsigned int offset, unsigned int count) { - VERIFY_CHECK((offset + count - 1) >> 6 == offset >> 6); - return (a->d[offset >> 6] >> (offset & 0x3F)) & ((((uint64_t)1) << count) - 1); -} - -SECP256K1_INLINE static unsigned int secp256k1_scalar_get_bits_var(const secp256k1_scalar_t *a, unsigned int offset, unsigned int count) { - VERIFY_CHECK(count < 32); - VERIFY_CHECK(offset + count <= 256); - if ((offset + count - 1) >> 6 == offset >> 6) { - return secp256k1_scalar_get_bits(a, offset, count); - } else { - VERIFY_CHECK((offset >> 6) + 1 < 4); - return ((a->d[offset >> 6] >> (offset & 0x3F)) | (a->d[(offset >> 6) + 1] << (64 - (offset & 0x3F)))) & ((((uint64_t)1) << count) - 1); - } -} - -SECP256K1_INLINE static int secp256k1_scalar_check_overflow(const secp256k1_scalar_t *a) { - int yes = 0; - int no = 0; - no |= (a->d[3] < SECP256K1_N_3); /* No need for a > check. */ - no |= (a->d[2] < SECP256K1_N_2); - yes |= (a->d[2] > SECP256K1_N_2) & ~no; - no |= (a->d[1] < SECP256K1_N_1); - yes |= (a->d[1] > SECP256K1_N_1) & ~no; - yes |= (a->d[0] >= SECP256K1_N_0) & ~no; - return yes; -} - -SECP256K1_INLINE static int secp256k1_scalar_reduce(secp256k1_scalar_t *r, unsigned int overflow) { - uint128_t t; - VERIFY_CHECK(overflow <= 1); - t = (uint128_t)r->d[0] + overflow * SECP256K1_N_C_0; - r->d[0] = t & 0xFFFFFFFFFFFFFFFFULL; t >>= 64; - t += (uint128_t)r->d[1] + overflow * SECP256K1_N_C_1; - r->d[1] = t & 0xFFFFFFFFFFFFFFFFULL; t >>= 64; - t += (uint128_t)r->d[2] + overflow * SECP256K1_N_C_2; - r->d[2] = t & 0xFFFFFFFFFFFFFFFFULL; t >>= 64; - t += (uint64_t)r->d[3]; - r->d[3] = t & 0xFFFFFFFFFFFFFFFFULL; - return overflow; -} - -static int secp256k1_scalar_add(secp256k1_scalar_t *r, const secp256k1_scalar_t *a, const secp256k1_scalar_t *b) { - int overflow; - uint128_t t = (uint128_t)a->d[0] + b->d[0]; - r->d[0] = t & 0xFFFFFFFFFFFFFFFFULL; t >>= 64; - t += (uint128_t)a->d[1] + b->d[1]; - r->d[1] = t & 0xFFFFFFFFFFFFFFFFULL; t >>= 64; - t += (uint128_t)a->d[2] + b->d[2]; - r->d[2] = t & 0xFFFFFFFFFFFFFFFFULL; t >>= 64; - t += (uint128_t)a->d[3] + b->d[3]; - r->d[3] = t & 0xFFFFFFFFFFFFFFFFULL; t >>= 64; - overflow = t + secp256k1_scalar_check_overflow(r); - VERIFY_CHECK(overflow == 0 || overflow == 1); - secp256k1_scalar_reduce(r, overflow); - return overflow; -} - -static void secp256k1_scalar_add_bit(secp256k1_scalar_t *r, unsigned int bit) { - uint128_t t; - VERIFY_CHECK(bit < 256); - t = (uint128_t)r->d[0] + (((uint64_t)((bit >> 6) == 0)) << (bit & 0x3F)); - r->d[0] = t & 0xFFFFFFFFFFFFFFFFULL; t >>= 64; - t += (uint128_t)r->d[1] + (((uint64_t)((bit >> 6) == 1)) << (bit & 0x3F)); - r->d[1] = t & 0xFFFFFFFFFFFFFFFFULL; t >>= 64; - t += (uint128_t)r->d[2] + (((uint64_t)((bit >> 6) == 2)) << (bit & 0x3F)); - r->d[2] = t & 0xFFFFFFFFFFFFFFFFULL; t >>= 64; - t += (uint128_t)r->d[3] + (((uint64_t)((bit >> 6) == 3)) << (bit & 0x3F)); - r->d[3] = t & 0xFFFFFFFFFFFFFFFFULL; -#ifdef VERIFY - VERIFY_CHECK((t >> 64) == 0); - VERIFY_CHECK(secp256k1_scalar_check_overflow(r) == 0); -#endif -} - -static void secp256k1_scalar_set_b32(secp256k1_scalar_t *r, const unsigned char *b32, int *overflow) { - int over; - r->d[0] = (uint64_t)b32[31] | (uint64_t)b32[30] << 8 | (uint64_t)b32[29] << 16 | (uint64_t)b32[28] << 24 | (uint64_t)b32[27] << 32 | (uint64_t)b32[26] << 40 | (uint64_t)b32[25] << 48 | (uint64_t)b32[24] << 56; - r->d[1] = (uint64_t)b32[23] | (uint64_t)b32[22] << 8 | (uint64_t)b32[21] << 16 | (uint64_t)b32[20] << 24 | (uint64_t)b32[19] << 32 | (uint64_t)b32[18] << 40 | (uint64_t)b32[17] << 48 | (uint64_t)b32[16] << 56; - r->d[2] = (uint64_t)b32[15] | (uint64_t)b32[14] << 8 | (uint64_t)b32[13] << 16 | (uint64_t)b32[12] << 24 | (uint64_t)b32[11] << 32 | (uint64_t)b32[10] << 40 | (uint64_t)b32[9] << 48 | (uint64_t)b32[8] << 56; - r->d[3] = (uint64_t)b32[7] | (uint64_t)b32[6] << 8 | (uint64_t)b32[5] << 16 | (uint64_t)b32[4] << 24 | (uint64_t)b32[3] << 32 | (uint64_t)b32[2] << 40 | (uint64_t)b32[1] << 48 | (uint64_t)b32[0] << 56; - over = secp256k1_scalar_reduce(r, secp256k1_scalar_check_overflow(r)); - if (overflow) { - *overflow = over; - } -} - -static void secp256k1_scalar_get_b32(unsigned char *bin, const secp256k1_scalar_t* a) { - bin[0] = a->d[3] >> 56; bin[1] = a->d[3] >> 48; bin[2] = a->d[3] >> 40; bin[3] = a->d[3] >> 32; bin[4] = a->d[3] >> 24; bin[5] = a->d[3] >> 16; bin[6] = a->d[3] >> 8; bin[7] = a->d[3]; - bin[8] = a->d[2] >> 56; bin[9] = a->d[2] >> 48; bin[10] = a->d[2] >> 40; bin[11] = a->d[2] >> 32; bin[12] = a->d[2] >> 24; bin[13] = a->d[2] >> 16; bin[14] = a->d[2] >> 8; bin[15] = a->d[2]; - bin[16] = a->d[1] >> 56; bin[17] = a->d[1] >> 48; bin[18] = a->d[1] >> 40; bin[19] = a->d[1] >> 32; bin[20] = a->d[1] >> 24; bin[21] = a->d[1] >> 16; bin[22] = a->d[1] >> 8; bin[23] = a->d[1]; - bin[24] = a->d[0] >> 56; bin[25] = a->d[0] >> 48; bin[26] = a->d[0] >> 40; bin[27] = a->d[0] >> 32; bin[28] = a->d[0] >> 24; bin[29] = a->d[0] >> 16; bin[30] = a->d[0] >> 8; bin[31] = a->d[0]; -} - -SECP256K1_INLINE static int secp256k1_scalar_is_zero(const secp256k1_scalar_t *a) { - return (a->d[0] | a->d[1] | a->d[2] | a->d[3]) == 0; -} - -static void secp256k1_scalar_negate(secp256k1_scalar_t *r, const secp256k1_scalar_t *a) { - uint64_t nonzero = 0xFFFFFFFFFFFFFFFFULL * (secp256k1_scalar_is_zero(a) == 0); - uint128_t t = (uint128_t)(~a->d[0]) + SECP256K1_N_0 + 1; - r->d[0] = t & nonzero; t >>= 64; - t += (uint128_t)(~a->d[1]) + SECP256K1_N_1; - r->d[1] = t & nonzero; t >>= 64; - t += (uint128_t)(~a->d[2]) + SECP256K1_N_2; - r->d[2] = t & nonzero; t >>= 64; - t += (uint128_t)(~a->d[3]) + SECP256K1_N_3; - r->d[3] = t & nonzero; -} - -SECP256K1_INLINE static int secp256k1_scalar_is_one(const secp256k1_scalar_t *a) { - return ((a->d[0] ^ 1) | a->d[1] | a->d[2] | a->d[3]) == 0; -} - -static int secp256k1_scalar_is_high(const secp256k1_scalar_t *a) { - int yes = 0; - int no = 0; - no |= (a->d[3] < SECP256K1_N_H_3); - yes |= (a->d[3] > SECP256K1_N_H_3) & ~no; - no |= (a->d[2] < SECP256K1_N_H_2) & ~yes; /* No need for a > check. */ - no |= (a->d[1] < SECP256K1_N_H_1) & ~yes; - yes |= (a->d[1] > SECP256K1_N_H_1) & ~no; - yes |= (a->d[0] > SECP256K1_N_H_0) & ~no; - return yes; -} - -/* Inspired by the macros in OpenSSL's crypto/bn/asm/x86_64-gcc.c. */ - -/** Add a*b to the number defined by (c0,c1,c2). c2 must never overflow. */ -#define muladd(a,b) { \ - uint64_t tl, th; \ - { \ - uint128_t t = (uint128_t)a * b; \ - th = t >> 64; /* at most 0xFFFFFFFFFFFFFFFE */ \ - tl = t; \ - } \ - c0 += tl; /* overflow is handled on the next line */ \ - th += (c0 < tl) ? 1 : 0; /* at most 0xFFFFFFFFFFFFFFFF */ \ - c1 += th; /* overflow is handled on the next line */ \ - c2 += (c1 < th) ? 1 : 0; /* never overflows by contract (verified in the next line) */ \ - VERIFY_CHECK((c1 >= th) || (c2 != 0)); \ -} - -/** Add a*b to the number defined by (c0,c1). c1 must never overflow. */ -#define muladd_fast(a,b) { \ - uint64_t tl, th; \ - { \ - uint128_t t = (uint128_t)a * b; \ - th = t >> 64; /* at most 0xFFFFFFFFFFFFFFFE */ \ - tl = t; \ - } \ - c0 += tl; /* overflow is handled on the next line */ \ - th += (c0 < tl) ? 1 : 0; /* at most 0xFFFFFFFFFFFFFFFF */ \ - c1 += th; /* never overflows by contract (verified in the next line) */ \ - VERIFY_CHECK(c1 >= th); \ -} - -/** Add 2*a*b to the number defined by (c0,c1,c2). c2 must never overflow. */ -#define muladd2(a,b) { \ - uint64_t tl, th, th2, tl2; \ - { \ - uint128_t t = (uint128_t)a * b; \ - th = t >> 64; /* at most 0xFFFFFFFFFFFFFFFE */ \ - tl = t; \ - } \ - th2 = th + th; /* at most 0xFFFFFFFFFFFFFFFE (in case th was 0x7FFFFFFFFFFFFFFF) */ \ - c2 += (th2 < th) ? 1 : 0; /* never overflows by contract (verified the next line) */ \ - VERIFY_CHECK((th2 >= th) || (c2 != 0)); \ - tl2 = tl + tl; /* at most 0xFFFFFFFFFFFFFFFE (in case the lowest 63 bits of tl were 0x7FFFFFFFFFFFFFFF) */ \ - th2 += (tl2 < tl) ? 1 : 0; /* at most 0xFFFFFFFFFFFFFFFF */ \ - c0 += tl2; /* overflow is handled on the next line */ \ - th2 += (c0 < tl2) ? 1 : 0; /* second overflow is handled on the next line */ \ - c2 += (c0 < tl2) & (th2 == 0); /* never overflows by contract (verified the next line) */ \ - VERIFY_CHECK((c0 >= tl2) || (th2 != 0) || (c2 != 0)); \ - c1 += th2; /* overflow is handled on the next line */ \ - c2 += (c1 < th2) ? 1 : 0; /* never overflows by contract (verified the next line) */ \ - VERIFY_CHECK((c1 >= th2) || (c2 != 0)); \ -} - -/** Add a to the number defined by (c0,c1,c2). c2 must never overflow. */ -#define sumadd(a) { \ - unsigned int over; \ - c0 += (a); /* overflow is handled on the next line */ \ - over = (c0 < (a)) ? 1 : 0; \ - c1 += over; /* overflow is handled on the next line */ \ - c2 += (c1 < over) ? 1 : 0; /* never overflows by contract */ \ -} - -/** Add a to the number defined by (c0,c1). c1 must never overflow, c2 must be zero. */ -#define sumadd_fast(a) { \ - c0 += (a); /* overflow is handled on the next line */ \ - c1 += (c0 < (a)) ? 1 : 0; /* never overflows by contract (verified the next line) */ \ - VERIFY_CHECK((c1 != 0) | (c0 >= (a))); \ - VERIFY_CHECK(c2 == 0); \ -} - -/** Extract the lowest 64 bits of (c0,c1,c2) into n, and left shift the number 64 bits. */ -#define extract(n) { \ - (n) = c0; \ - c0 = c1; \ - c1 = c2; \ - c2 = 0; \ -} - -/** Extract the lowest 64 bits of (c0,c1,c2) into n, and left shift the number 64 bits. c2 is required to be zero. */ -#define extract_fast(n) { \ - (n) = c0; \ - c0 = c1; \ - c1 = 0; \ - VERIFY_CHECK(c2 == 0); \ -} - -static void secp256k1_scalar_reduce_512(secp256k1_scalar_t *r, const uint64_t *l) { -#ifdef USE_ASM_X86_64 - /* Reduce 512 bits into 385. */ - uint64_t m0, m1, m2, m3, m4, m5, m6; - uint64_t p0, p1, p2, p3, p4; - uint64_t c; - - __asm__ __volatile__( - /* Preload. */ - "movq 32(%%rsi), %%r11\n" - "movq 40(%%rsi), %%r12\n" - "movq 48(%%rsi), %%r13\n" - "movq 56(%%rsi), %%r14\n" - /* Initialize r8,r9,r10 */ - "movq 0(%%rsi), %%r8\n" - "movq $0, %%r9\n" - "movq $0, %%r10\n" - /* (r8,r9) += n0 * c0 */ - "movq %8, %%rax\n" - "mulq %%r11\n" - "addq %%rax, %%r8\n" - "adcq %%rdx, %%r9\n" - /* extract m0 */ - "movq %%r8, %q0\n" - "movq $0, %%r8\n" - /* (r9,r10) += l1 */ - "addq 8(%%rsi), %%r9\n" - "adcq $0, %%r10\n" - /* (r9,r10,r8) += n1 * c0 */ - "movq %8, %%rax\n" - "mulq %%r12\n" - "addq %%rax, %%r9\n" - "adcq %%rdx, %%r10\n" - "adcq $0, %%r8\n" - /* (r9,r10,r8) += n0 * c1 */ - "movq %9, %%rax\n" - "mulq %%r11\n" - "addq %%rax, %%r9\n" - "adcq %%rdx, %%r10\n" - "adcq $0, %%r8\n" - /* extract m1 */ - "movq %%r9, %q1\n" - "movq $0, %%r9\n" - /* (r10,r8,r9) += l2 */ - "addq 16(%%rsi), %%r10\n" - "adcq $0, %%r8\n" - "adcq $0, %%r9\n" - /* (r10,r8,r9) += n2 * c0 */ - "movq %8, %%rax\n" - "mulq %%r13\n" - "addq %%rax, %%r10\n" - "adcq %%rdx, %%r8\n" - "adcq $0, %%r9\n" - /* (r10,r8,r9) += n1 * c1 */ - "movq %9, %%rax\n" - "mulq %%r12\n" - "addq %%rax, %%r10\n" - "adcq %%rdx, %%r8\n" - "adcq $0, %%r9\n" - /* (r10,r8,r9) += n0 */ - "addq %%r11, %%r10\n" - "adcq $0, %%r8\n" - "adcq $0, %%r9\n" - /* extract m2 */ - "movq %%r10, %q2\n" - "movq $0, %%r10\n" - /* (r8,r9,r10) += l3 */ - "addq 24(%%rsi), %%r8\n" - "adcq $0, %%r9\n" - "adcq $0, %%r10\n" - /* (r8,r9,r10) += n3 * c0 */ - "movq %8, %%rax\n" - "mulq %%r14\n" - "addq %%rax, %%r8\n" - "adcq %%rdx, %%r9\n" - "adcq $0, %%r10\n" - /* (r8,r9,r10) += n2 * c1 */ - "movq %9, %%rax\n" - "mulq %%r13\n" - "addq %%rax, %%r8\n" - "adcq %%rdx, %%r9\n" - "adcq $0, %%r10\n" - /* (r8,r9,r10) += n1 */ - "addq %%r12, %%r8\n" - "adcq $0, %%r9\n" - "adcq $0, %%r10\n" - /* extract m3 */ - "movq %%r8, %q3\n" - "movq $0, %%r8\n" - /* (r9,r10,r8) += n3 * c1 */ - "movq %9, %%rax\n" - "mulq %%r14\n" - "addq %%rax, %%r9\n" - "adcq %%rdx, %%r10\n" - "adcq $0, %%r8\n" - /* (r9,r10,r8) += n2 */ - "addq %%r13, %%r9\n" - "adcq $0, %%r10\n" - "adcq $0, %%r8\n" - /* extract m4 */ - "movq %%r9, %q4\n" - /* (r10,r8) += n3 */ - "addq %%r14, %%r10\n" - "adcq $0, %%r8\n" - /* extract m5 */ - "movq %%r10, %q5\n" - /* extract m6 */ - "movq %%r8, %q6\n" - : "=g"(m0), "=g"(m1), "=g"(m2), "=g"(m3), "=g"(m4), "=g"(m5), "=g"(m6) - : "S"(l), "n"(SECP256K1_N_C_0), "n"(SECP256K1_N_C_1) - : "rax", "rdx", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "cc"); - - /* Reduce 385 bits into 258. */ - __asm__ __volatile__( - /* Preload */ - "movq %q9, %%r11\n" - "movq %q10, %%r12\n" - "movq %q11, %%r13\n" - /* Initialize (r8,r9,r10) */ - "movq %q5, %%r8\n" - "movq $0, %%r9\n" - "movq $0, %%r10\n" - /* (r8,r9) += m4 * c0 */ - "movq %12, %%rax\n" - "mulq %%r11\n" - "addq %%rax, %%r8\n" - "adcq %%rdx, %%r9\n" - /* extract p0 */ - "movq %%r8, %q0\n" - "movq $0, %%r8\n" - /* (r9,r10) += m1 */ - "addq %q6, %%r9\n" - "adcq $0, %%r10\n" - /* (r9,r10,r8) += m5 * c0 */ - "movq %12, %%rax\n" - "mulq %%r12\n" - "addq %%rax, %%r9\n" - "adcq %%rdx, %%r10\n" - "adcq $0, %%r8\n" - /* (r9,r10,r8) += m4 * c1 */ - "movq %13, %%rax\n" - "mulq %%r11\n" - "addq %%rax, %%r9\n" - "adcq %%rdx, %%r10\n" - "adcq $0, %%r8\n" - /* extract p1 */ - "movq %%r9, %q1\n" - "movq $0, %%r9\n" - /* (r10,r8,r9) += m2 */ - "addq %q7, %%r10\n" - "adcq $0, %%r8\n" - "adcq $0, %%r9\n" - /* (r10,r8,r9) += m6 * c0 */ - "movq %12, %%rax\n" - "mulq %%r13\n" - "addq %%rax, %%r10\n" - "adcq %%rdx, %%r8\n" - "adcq $0, %%r9\n" - /* (r10,r8,r9) += m5 * c1 */ - "movq %13, %%rax\n" - "mulq %%r12\n" - "addq %%rax, %%r10\n" - "adcq %%rdx, %%r8\n" - "adcq $0, %%r9\n" - /* (r10,r8,r9) += m4 */ - "addq %%r11, %%r10\n" - "adcq $0, %%r8\n" - "adcq $0, %%r9\n" - /* extract p2 */ - "movq %%r10, %q2\n" - /* (r8,r9) += m3 */ - "addq %q8, %%r8\n" - "adcq $0, %%r9\n" - /* (r8,r9) += m6 * c1 */ - "movq %13, %%rax\n" - "mulq %%r13\n" - "addq %%rax, %%r8\n" - "adcq %%rdx, %%r9\n" - /* (r8,r9) += m5 */ - "addq %%r12, %%r8\n" - "adcq $0, %%r9\n" - /* extract p3 */ - "movq %%r8, %q3\n" - /* (r9) += m6 */ - "addq %%r13, %%r9\n" - /* extract p4 */ - "movq %%r9, %q4\n" - : "=&g"(p0), "=&g"(p1), "=&g"(p2), "=g"(p3), "=g"(p4) - : "g"(m0), "g"(m1), "g"(m2), "g"(m3), "g"(m4), "g"(m5), "g"(m6), "n"(SECP256K1_N_C_0), "n"(SECP256K1_N_C_1) - : "rax", "rdx", "r8", "r9", "r10", "r11", "r12", "r13", "cc"); - - /* Reduce 258 bits into 256. */ - __asm__ __volatile__( - /* Preload */ - "movq %q5, %%r10\n" - /* (rax,rdx) = p4 * c0 */ - "movq %7, %%rax\n" - "mulq %%r10\n" - /* (rax,rdx) += p0 */ - "addq %q1, %%rax\n" - "adcq $0, %%rdx\n" - /* extract r0 */ - "movq %%rax, 0(%q6)\n" - /* Move to (r8,r9) */ - "movq %%rdx, %%r8\n" - "movq $0, %%r9\n" - /* (r8,r9) += p1 */ - "addq %q2, %%r8\n" - "adcq $0, %%r9\n" - /* (r8,r9) += p4 * c1 */ - "movq %8, %%rax\n" - "mulq %%r10\n" - "addq %%rax, %%r8\n" - "adcq %%rdx, %%r9\n" - /* Extract r1 */ - "movq %%r8, 8(%q6)\n" - "movq $0, %%r8\n" - /* (r9,r8) += p4 */ - "addq %%r10, %%r9\n" - "adcq $0, %%r8\n" - /* (r9,r8) += p2 */ - "addq %q3, %%r9\n" - "adcq $0, %%r8\n" - /* Extract r2 */ - "movq %%r9, 16(%q6)\n" - "movq $0, %%r9\n" - /* (r8,r9) += p3 */ - "addq %q4, %%r8\n" - "adcq $0, %%r9\n" - /* Extract r3 */ - "movq %%r8, 24(%q6)\n" - /* Extract c */ - "movq %%r9, %q0\n" - : "=g"(c) - : "g"(p0), "g"(p1), "g"(p2), "g"(p3), "g"(p4), "D"(r), "n"(SECP256K1_N_C_0), "n"(SECP256K1_N_C_1) - : "rax", "rdx", "r8", "r9", "r10", "cc", "memory"); -#else - uint128_t c; - uint64_t c0, c1, c2; - uint64_t n0 = l[4], n1 = l[5], n2 = l[6], n3 = l[7]; - uint64_t m0, m1, m2, m3, m4, m5; - uint32_t m6; - uint64_t p0, p1, p2, p3; - uint32_t p4; - - /* Reduce 512 bits into 385. */ - /* m[0..6] = l[0..3] + n[0..3] * SECP256K1_N_C. */ - c0 = l[0]; c1 = 0; c2 = 0; - muladd_fast(n0, SECP256K1_N_C_0); - extract_fast(m0); - sumadd_fast(l[1]); - muladd(n1, SECP256K1_N_C_0); - muladd(n0, SECP256K1_N_C_1); - extract(m1); - sumadd(l[2]); - muladd(n2, SECP256K1_N_C_0); - muladd(n1, SECP256K1_N_C_1); - sumadd(n0); - extract(m2); - sumadd(l[3]); - muladd(n3, SECP256K1_N_C_0); - muladd(n2, SECP256K1_N_C_1); - sumadd(n1); - extract(m3); - muladd(n3, SECP256K1_N_C_1); - sumadd(n2); - extract(m4); - sumadd_fast(n3); - extract_fast(m5); - VERIFY_CHECK(c0 <= 1); - m6 = c0; - - /* Reduce 385 bits into 258. */ - /* p[0..4] = m[0..3] + m[4..6] * SECP256K1_N_C. */ - c0 = m0; c1 = 0; c2 = 0; - muladd_fast(m4, SECP256K1_N_C_0); - extract_fast(p0); - sumadd_fast(m1); - muladd(m5, SECP256K1_N_C_0); - muladd(m4, SECP256K1_N_C_1); - extract(p1); - sumadd(m2); - muladd(m6, SECP256K1_N_C_0); - muladd(m5, SECP256K1_N_C_1); - sumadd(m4); - extract(p2); - sumadd_fast(m3); - muladd_fast(m6, SECP256K1_N_C_1); - sumadd_fast(m5); - extract_fast(p3); - p4 = c0 + m6; - VERIFY_CHECK(p4 <= 2); - - /* Reduce 258 bits into 256. */ - /* r[0..3] = p[0..3] + p[4] * SECP256K1_N_C. */ - c = p0 + (uint128_t)SECP256K1_N_C_0 * p4; - r->d[0] = c & 0xFFFFFFFFFFFFFFFFULL; c >>= 64; - c += p1 + (uint128_t)SECP256K1_N_C_1 * p4; - r->d[1] = c & 0xFFFFFFFFFFFFFFFFULL; c >>= 64; - c += p2 + (uint128_t)p4; - r->d[2] = c & 0xFFFFFFFFFFFFFFFFULL; c >>= 64; - c += p3; - r->d[3] = c & 0xFFFFFFFFFFFFFFFFULL; c >>= 64; -#endif - - /* Final reduction of r. */ - secp256k1_scalar_reduce(r, c + secp256k1_scalar_check_overflow(r)); -} - -static void secp256k1_scalar_mul_512(uint64_t l[8], const secp256k1_scalar_t *a, const secp256k1_scalar_t *b) { -#ifdef USE_ASM_X86_64 - const uint64_t *pb = b->d; - __asm__ __volatile__( - /* Preload */ - "movq 0(%%rdi), %%r15\n" - "movq 8(%%rdi), %%rbx\n" - "movq 16(%%rdi), %%rcx\n" - "movq 0(%%rdx), %%r11\n" - "movq 8(%%rdx), %%r12\n" - "movq 16(%%rdx), %%r13\n" - "movq 24(%%rdx), %%r14\n" - /* (rax,rdx) = a0 * b0 */ - "movq %%r15, %%rax\n" - "mulq %%r11\n" - /* Extract l0 */ - "movq %%rax, 0(%%rsi)\n" - /* (r8,r9,r10) = (rdx) */ - "movq %%rdx, %%r8\n" - "xorq %%r9, %%r9\n" - "xorq %%r10, %%r10\n" - /* (r8,r9,r10) += a0 * b1 */ - "movq %%r15, %%rax\n" - "mulq %%r12\n" - "addq %%rax, %%r8\n" - "adcq %%rdx, %%r9\n" - "adcq $0, %%r10\n" - /* (r8,r9,r10) += a1 * b0 */ - "movq %%rbx, %%rax\n" - "mulq %%r11\n" - "addq %%rax, %%r8\n" - "adcq %%rdx, %%r9\n" - "adcq $0, %%r10\n" - /* Extract l1 */ - "movq %%r8, 8(%%rsi)\n" - "xorq %%r8, %%r8\n" - /* (r9,r10,r8) += a0 * b2 */ - "movq %%r15, %%rax\n" - "mulq %%r13\n" - "addq %%rax, %%r9\n" - "adcq %%rdx, %%r10\n" - "adcq $0, %%r8\n" - /* (r9,r10,r8) += a1 * b1 */ - "movq %%rbx, %%rax\n" - "mulq %%r12\n" - "addq %%rax, %%r9\n" - "adcq %%rdx, %%r10\n" - "adcq $0, %%r8\n" - /* (r9,r10,r8) += a2 * b0 */ - "movq %%rcx, %%rax\n" - "mulq %%r11\n" - "addq %%rax, %%r9\n" - "adcq %%rdx, %%r10\n" - "adcq $0, %%r8\n" - /* Extract l2 */ - "movq %%r9, 16(%%rsi)\n" - "xorq %%r9, %%r9\n" - /* (r10,r8,r9) += a0 * b3 */ - "movq %%r15, %%rax\n" - "mulq %%r14\n" - "addq %%rax, %%r10\n" - "adcq %%rdx, %%r8\n" - "adcq $0, %%r9\n" - /* Preload a3 */ - "movq 24(%%rdi), %%r15\n" - /* (r10,r8,r9) += a1 * b2 */ - "movq %%rbx, %%rax\n" - "mulq %%r13\n" - "addq %%rax, %%r10\n" - "adcq %%rdx, %%r8\n" - "adcq $0, %%r9\n" - /* (r10,r8,r9) += a2 * b1 */ - "movq %%rcx, %%rax\n" - "mulq %%r12\n" - "addq %%rax, %%r10\n" - "adcq %%rdx, %%r8\n" - "adcq $0, %%r9\n" - /* (r10,r8,r9) += a3 * b0 */ - "movq %%r15, %%rax\n" - "mulq %%r11\n" - "addq %%rax, %%r10\n" - "adcq %%rdx, %%r8\n" - "adcq $0, %%r9\n" - /* Extract l3 */ - "movq %%r10, 24(%%rsi)\n" - "xorq %%r10, %%r10\n" - /* (r8,r9,r10) += a1 * b3 */ - "movq %%rbx, %%rax\n" - "mulq %%r14\n" - "addq %%rax, %%r8\n" - "adcq %%rdx, %%r9\n" - "adcq $0, %%r10\n" - /* (r8,r9,r10) += a2 * b2 */ - "movq %%rcx, %%rax\n" - "mulq %%r13\n" - "addq %%rax, %%r8\n" - "adcq %%rdx, %%r9\n" - "adcq $0, %%r10\n" - /* (r8,r9,r10) += a3 * b1 */ - "movq %%r15, %%rax\n" - "mulq %%r12\n" - "addq %%rax, %%r8\n" - "adcq %%rdx, %%r9\n" - "adcq $0, %%r10\n" - /* Extract l4 */ - "movq %%r8, 32(%%rsi)\n" - "xorq %%r8, %%r8\n" - /* (r9,r10,r8) += a2 * b3 */ - "movq %%rcx, %%rax\n" - "mulq %%r14\n" - "addq %%rax, %%r9\n" - "adcq %%rdx, %%r10\n" - "adcq $0, %%r8\n" - /* (r9,r10,r8) += a3 * b2 */ - "movq %%r15, %%rax\n" - "mulq %%r13\n" - "addq %%rax, %%r9\n" - "adcq %%rdx, %%r10\n" - "adcq $0, %%r8\n" - /* Extract l5 */ - "movq %%r9, 40(%%rsi)\n" - /* (r10,r8) += a3 * b3 */ - "movq %%r15, %%rax\n" - "mulq %%r14\n" - "addq %%rax, %%r10\n" - "adcq %%rdx, %%r8\n" - /* Extract l6 */ - "movq %%r10, 48(%%rsi)\n" - /* Extract l7 */ - "movq %%r8, 56(%%rsi)\n" - : "+d"(pb) - : "S"(l), "D"(a->d) - : "rax", "rbx", "rcx", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15", "cc", "memory"); -#else - /* 160 bit accumulator. */ - uint64_t c0 = 0, c1 = 0; - uint32_t c2 = 0; - - /* l[0..7] = a[0..3] * b[0..3]. */ - muladd_fast(a->d[0], b->d[0]); - extract_fast(l[0]); - muladd(a->d[0], b->d[1]); - muladd(a->d[1], b->d[0]); - extract(l[1]); - muladd(a->d[0], b->d[2]); - muladd(a->d[1], b->d[1]); - muladd(a->d[2], b->d[0]); - extract(l[2]); - muladd(a->d[0], b->d[3]); - muladd(a->d[1], b->d[2]); - muladd(a->d[2], b->d[1]); - muladd(a->d[3], b->d[0]); - extract(l[3]); - muladd(a->d[1], b->d[3]); - muladd(a->d[2], b->d[2]); - muladd(a->d[3], b->d[1]); - extract(l[4]); - muladd(a->d[2], b->d[3]); - muladd(a->d[3], b->d[2]); - extract(l[5]); - muladd_fast(a->d[3], b->d[3]); - extract_fast(l[6]); - VERIFY_CHECK(c1 <= 0); - l[7] = c0; -#endif -} - -static void secp256k1_scalar_sqr_512(uint64_t l[8], const secp256k1_scalar_t *a) { -#ifdef USE_ASM_X86_64 - __asm__ __volatile__( - /* Preload */ - "movq 0(%%rdi), %%r11\n" - "movq 8(%%rdi), %%r12\n" - "movq 16(%%rdi), %%r13\n" - "movq 24(%%rdi), %%r14\n" - /* (rax,rdx) = a0 * a0 */ - "movq %%r11, %%rax\n" - "mulq %%r11\n" - /* Extract l0 */ - "movq %%rax, 0(%%rsi)\n" - /* (r8,r9,r10) = (rdx,0) */ - "movq %%rdx, %%r8\n" - "xorq %%r9, %%r9\n" - "xorq %%r10, %%r10\n" - /* (r8,r9,r10) += 2 * a0 * a1 */ - "movq %%r11, %%rax\n" - "mulq %%r12\n" - "addq %%rax, %%r8\n" - "adcq %%rdx, %%r9\n" - "adcq $0, %%r10\n" - "addq %%rax, %%r8\n" - "adcq %%rdx, %%r9\n" - "adcq $0, %%r10\n" - /* Extract l1 */ - "movq %%r8, 8(%%rsi)\n" - "xorq %%r8, %%r8\n" - /* (r9,r10,r8) += 2 * a0 * a2 */ - "movq %%r11, %%rax\n" - "mulq %%r13\n" - "addq %%rax, %%r9\n" - "adcq %%rdx, %%r10\n" - "adcq $0, %%r8\n" - "addq %%rax, %%r9\n" - "adcq %%rdx, %%r10\n" - "adcq $0, %%r8\n" - /* (r9,r10,r8) += a1 * a1 */ - "movq %%r12, %%rax\n" - "mulq %%r12\n" - "addq %%rax, %%r9\n" - "adcq %%rdx, %%r10\n" - "adcq $0, %%r8\n" - /* Extract l2 */ - "movq %%r9, 16(%%rsi)\n" - "xorq %%r9, %%r9\n" - /* (r10,r8,r9) += 2 * a0 * a3 */ - "movq %%r11, %%rax\n" - "mulq %%r14\n" - "addq %%rax, %%r10\n" - "adcq %%rdx, %%r8\n" - "adcq $0, %%r9\n" - "addq %%rax, %%r10\n" - "adcq %%rdx, %%r8\n" - "adcq $0, %%r9\n" - /* (r10,r8,r9) += 2 * a1 * a2 */ - "movq %%r12, %%rax\n" - "mulq %%r13\n" - "addq %%rax, %%r10\n" - "adcq %%rdx, %%r8\n" - "adcq $0, %%r9\n" - "addq %%rax, %%r10\n" - "adcq %%rdx, %%r8\n" - "adcq $0, %%r9\n" - /* Extract l3 */ - "movq %%r10, 24(%%rsi)\n" - "xorq %%r10, %%r10\n" - /* (r8,r9,r10) += 2 * a1 * a3 */ - "movq %%r12, %%rax\n" - "mulq %%r14\n" - "addq %%rax, %%r8\n" - "adcq %%rdx, %%r9\n" - "adcq $0, %%r10\n" - "addq %%rax, %%r8\n" - "adcq %%rdx, %%r9\n" - "adcq $0, %%r10\n" - /* (r8,r9,r10) += a2 * a2 */ - "movq %%r13, %%rax\n" - "mulq %%r13\n" - "addq %%rax, %%r8\n" - "adcq %%rdx, %%r9\n" - "adcq $0, %%r10\n" - /* Extract l4 */ - "movq %%r8, 32(%%rsi)\n" - "xorq %%r8, %%r8\n" - /* (r9,r10,r8) += 2 * a2 * a3 */ - "movq %%r13, %%rax\n" - "mulq %%r14\n" - "addq %%rax, %%r9\n" - "adcq %%rdx, %%r10\n" - "adcq $0, %%r8\n" - "addq %%rax, %%r9\n" - "adcq %%rdx, %%r10\n" - "adcq $0, %%r8\n" - /* Extract l5 */ - "movq %%r9, 40(%%rsi)\n" - /* (r10,r8) += a3 * a3 */ - "movq %%r14, %%rax\n" - "mulq %%r14\n" - "addq %%rax, %%r10\n" - "adcq %%rdx, %%r8\n" - /* Extract l6 */ - "movq %%r10, 48(%%rsi)\n" - /* Extract l7 */ - "movq %%r8, 56(%%rsi)\n" - : - : "S"(l), "D"(a->d) - : "rax", "rdx", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "cc", "memory"); -#else - /* 160 bit accumulator. */ - uint64_t c0 = 0, c1 = 0; - uint32_t c2 = 0; - - /* l[0..7] = a[0..3] * b[0..3]. */ - muladd_fast(a->d[0], a->d[0]); - extract_fast(l[0]); - muladd2(a->d[0], a->d[1]); - extract(l[1]); - muladd2(a->d[0], a->d[2]); - muladd(a->d[1], a->d[1]); - extract(l[2]); - muladd2(a->d[0], a->d[3]); - muladd2(a->d[1], a->d[2]); - extract(l[3]); - muladd2(a->d[1], a->d[3]); - muladd(a->d[2], a->d[2]); - extract(l[4]); - muladd2(a->d[2], a->d[3]); - extract(l[5]); - muladd_fast(a->d[3], a->d[3]); - extract_fast(l[6]); - VERIFY_CHECK(c1 == 0); - l[7] = c0; -#endif -} - -#undef sumadd -#undef sumadd_fast -#undef muladd -#undef muladd_fast -#undef muladd2 -#undef extract -#undef extract_fast - -static void secp256k1_scalar_mul(secp256k1_scalar_t *r, const secp256k1_scalar_t *a, const secp256k1_scalar_t *b) { - uint64_t l[8]; - secp256k1_scalar_mul_512(l, a, b); - secp256k1_scalar_reduce_512(r, l); -} - -static void secp256k1_scalar_sqr(secp256k1_scalar_t *r, const secp256k1_scalar_t *a) { - uint64_t l[8]; - secp256k1_scalar_sqr_512(l, a); - secp256k1_scalar_reduce_512(r, l); -} - -static void secp256k1_scalar_split_128(secp256k1_scalar_t *r1, secp256k1_scalar_t *r2, const secp256k1_scalar_t *a) { - r1->d[0] = a->d[0]; - r1->d[1] = a->d[1]; - r1->d[2] = 0; - r1->d[3] = 0; - r2->d[0] = a->d[2]; - r2->d[1] = a->d[3]; - r2->d[2] = 0; - r2->d[3] = 0; -} - -SECP256K1_INLINE static int secp256k1_scalar_eq(const secp256k1_scalar_t *a, const secp256k1_scalar_t *b) { - return ((a->d[0] ^ b->d[0]) | (a->d[1] ^ b->d[1]) | (a->d[2] ^ b->d[2]) | (a->d[3] ^ b->d[3])) == 0; -} - -SECP256K1_INLINE static void secp256k1_scalar_mul_shift_var(secp256k1_scalar_t *r, const secp256k1_scalar_t *a, const secp256k1_scalar_t *b, unsigned int shift) { - uint64_t l[8]; - unsigned int shiftlimbs; - unsigned int shiftlow; - unsigned int shifthigh; - VERIFY_CHECK(shift >= 256); - secp256k1_scalar_mul_512(l, a, b); - shiftlimbs = shift >> 6; - shiftlow = shift & 0x3F; - shifthigh = 64 - shiftlow; - r->d[0] = shift < 512 ? (l[0 + shiftlimbs] >> shiftlow | (shift < 448 && shiftlow ? (l[1 + shiftlimbs] << shifthigh) : 0)) : 0; - r->d[1] = shift < 448 ? (l[1 + shiftlimbs] >> shiftlow | (shift < 384 && shiftlow ? (l[2 + shiftlimbs] << shifthigh) : 0)) : 0; - r->d[2] = shift < 384 ? (l[2 + shiftlimbs] >> shiftlow | (shift < 320 && shiftlow ? (l[3 + shiftlimbs] << shifthigh) : 0)) : 0; - r->d[3] = shift < 320 ? (l[3 + shiftlimbs] >> shiftlow) : 0; - if ((l[(shift - 1) >> 6] >> ((shift - 1) & 0x3f)) & 1) { - secp256k1_scalar_add_bit(r, 0); - } -} - -#endif diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/scalar_8x32.h b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/scalar_8x32.h deleted file mode 100644 index f17017e24e202557990c94bb809233efcfb018c2..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/scalar_8x32.h +++ /dev/null @@ -1,19 +0,0 @@ -/********************************************************************** - * 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_SCALAR_REPR_ -#define _SECP256K1_SCALAR_REPR_ - -#include <stdint.h> - -/** A scalar modulo the group order of the secp256k1 curve. */ -typedef struct { - uint32_t d[8]; -} secp256k1_scalar_t; - -#define SECP256K1_SCALAR_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {{(d0), (d1), (d2), (d3), (d4), (d5), (d6), (d7)}} - -#endif diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/scalar_8x32_impl.h b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/scalar_8x32_impl.h deleted file mode 100644 index 22b31d41125daeb942d2db22f80089856b611af1..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/scalar_8x32_impl.h +++ /dev/null @@ -1,681 +0,0 @@ -/********************************************************************** - * 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_SCALAR_REPR_IMPL_H_ -#define _SECP256K1_SCALAR_REPR_IMPL_H_ - -/* Limbs of the secp256k1 order. */ -#define SECP256K1_N_0 ((uint32_t)0xD0364141UL) -#define SECP256K1_N_1 ((uint32_t)0xBFD25E8CUL) -#define SECP256K1_N_2 ((uint32_t)0xAF48A03BUL) -#define SECP256K1_N_3 ((uint32_t)0xBAAEDCE6UL) -#define SECP256K1_N_4 ((uint32_t)0xFFFFFFFEUL) -#define SECP256K1_N_5 ((uint32_t)0xFFFFFFFFUL) -#define SECP256K1_N_6 ((uint32_t)0xFFFFFFFFUL) -#define SECP256K1_N_7 ((uint32_t)0xFFFFFFFFUL) - -/* Limbs of 2^256 minus the secp256k1 order. */ -#define SECP256K1_N_C_0 (~SECP256K1_N_0 + 1) -#define SECP256K1_N_C_1 (~SECP256K1_N_1) -#define SECP256K1_N_C_2 (~SECP256K1_N_2) -#define SECP256K1_N_C_3 (~SECP256K1_N_3) -#define SECP256K1_N_C_4 (1) - -/* Limbs of half the secp256k1 order. */ -#define SECP256K1_N_H_0 ((uint32_t)0x681B20A0UL) -#define SECP256K1_N_H_1 ((uint32_t)0xDFE92F46UL) -#define SECP256K1_N_H_2 ((uint32_t)0x57A4501DUL) -#define SECP256K1_N_H_3 ((uint32_t)0x5D576E73UL) -#define SECP256K1_N_H_4 ((uint32_t)0xFFFFFFFFUL) -#define SECP256K1_N_H_5 ((uint32_t)0xFFFFFFFFUL) -#define SECP256K1_N_H_6 ((uint32_t)0xFFFFFFFFUL) -#define SECP256K1_N_H_7 ((uint32_t)0x7FFFFFFFUL) - -SECP256K1_INLINE static void secp256k1_scalar_clear(secp256k1_scalar_t *r) { - r->d[0] = 0; - r->d[1] = 0; - r->d[2] = 0; - r->d[3] = 0; - r->d[4] = 0; - r->d[5] = 0; - r->d[6] = 0; - r->d[7] = 0; -} - -SECP256K1_INLINE static void secp256k1_scalar_set_int(secp256k1_scalar_t *r, unsigned int v) { - r->d[0] = v; - r->d[1] = 0; - r->d[2] = 0; - r->d[3] = 0; - r->d[4] = 0; - r->d[5] = 0; - r->d[6] = 0; - r->d[7] = 0; -} - -SECP256K1_INLINE static unsigned int secp256k1_scalar_get_bits(const secp256k1_scalar_t *a, unsigned int offset, unsigned int count) { - VERIFY_CHECK((offset + count - 1) >> 5 == offset >> 5); - return (a->d[offset >> 5] >> (offset & 0x1F)) & ((1 << count) - 1); -} - -SECP256K1_INLINE static unsigned int secp256k1_scalar_get_bits_var(const secp256k1_scalar_t *a, unsigned int offset, unsigned int count) { - VERIFY_CHECK(count < 32); - VERIFY_CHECK(offset + count <= 256); - if ((offset + count - 1) >> 5 == offset >> 5) { - return secp256k1_scalar_get_bits(a, offset, count); - } else { - VERIFY_CHECK((offset >> 5) + 1 < 8); - return ((a->d[offset >> 5] >> (offset & 0x1F)) | (a->d[(offset >> 5) + 1] << (32 - (offset & 0x1F)))) & ((((uint32_t)1) << count) - 1); - } -} - -SECP256K1_INLINE static int secp256k1_scalar_check_overflow(const secp256k1_scalar_t *a) { - int yes = 0; - int no = 0; - no |= (a->d[7] < SECP256K1_N_7); /* No need for a > check. */ - no |= (a->d[6] < SECP256K1_N_6); /* No need for a > check. */ - no |= (a->d[5] < SECP256K1_N_5); /* No need for a > check. */ - no |= (a->d[4] < SECP256K1_N_4); - yes |= (a->d[4] > SECP256K1_N_4) & ~no; - no |= (a->d[3] < SECP256K1_N_3) & ~yes; - yes |= (a->d[3] > SECP256K1_N_3) & ~no; - no |= (a->d[2] < SECP256K1_N_2) & ~yes; - yes |= (a->d[2] > SECP256K1_N_2) & ~no; - no |= (a->d[1] < SECP256K1_N_1) & ~yes; - yes |= (a->d[1] > SECP256K1_N_1) & ~no; - yes |= (a->d[0] >= SECP256K1_N_0) & ~no; - return yes; -} - -SECP256K1_INLINE static int secp256k1_scalar_reduce(secp256k1_scalar_t *r, uint32_t overflow) { - uint64_t t; - VERIFY_CHECK(overflow <= 1); - t = (uint64_t)r->d[0] + overflow * SECP256K1_N_C_0; - r->d[0] = t & 0xFFFFFFFFUL; t >>= 32; - t += (uint64_t)r->d[1] + overflow * SECP256K1_N_C_1; - r->d[1] = t & 0xFFFFFFFFUL; t >>= 32; - t += (uint64_t)r->d[2] + overflow * SECP256K1_N_C_2; - r->d[2] = t & 0xFFFFFFFFUL; t >>= 32; - t += (uint64_t)r->d[3] + overflow * SECP256K1_N_C_3; - r->d[3] = t & 0xFFFFFFFFUL; t >>= 32; - t += (uint64_t)r->d[4] + overflow * SECP256K1_N_C_4; - r->d[4] = t & 0xFFFFFFFFUL; t >>= 32; - t += (uint64_t)r->d[5]; - r->d[5] = t & 0xFFFFFFFFUL; t >>= 32; - t += (uint64_t)r->d[6]; - r->d[6] = t & 0xFFFFFFFFUL; t >>= 32; - t += (uint64_t)r->d[7]; - r->d[7] = t & 0xFFFFFFFFUL; - return overflow; -} - -static int secp256k1_scalar_add(secp256k1_scalar_t *r, const secp256k1_scalar_t *a, const secp256k1_scalar_t *b) { - int overflow; - uint64_t t = (uint64_t)a->d[0] + b->d[0]; - r->d[0] = t & 0xFFFFFFFFULL; t >>= 32; - t += (uint64_t)a->d[1] + b->d[1]; - r->d[1] = t & 0xFFFFFFFFULL; t >>= 32; - t += (uint64_t)a->d[2] + b->d[2]; - r->d[2] = t & 0xFFFFFFFFULL; t >>= 32; - t += (uint64_t)a->d[3] + b->d[3]; - r->d[3] = t & 0xFFFFFFFFULL; t >>= 32; - t += (uint64_t)a->d[4] + b->d[4]; - r->d[4] = t & 0xFFFFFFFFULL; t >>= 32; - t += (uint64_t)a->d[5] + b->d[5]; - r->d[5] = t & 0xFFFFFFFFULL; t >>= 32; - t += (uint64_t)a->d[6] + b->d[6]; - r->d[6] = t & 0xFFFFFFFFULL; t >>= 32; - t += (uint64_t)a->d[7] + b->d[7]; - r->d[7] = t & 0xFFFFFFFFULL; t >>= 32; - overflow = t + secp256k1_scalar_check_overflow(r); - VERIFY_CHECK(overflow == 0 || overflow == 1); - secp256k1_scalar_reduce(r, overflow); - return overflow; -} - -static void secp256k1_scalar_add_bit(secp256k1_scalar_t *r, unsigned int bit) { - uint64_t t; - VERIFY_CHECK(bit < 256); - t = (uint64_t)r->d[0] + (((uint32_t)((bit >> 5) == 0)) << (bit & 0x1F)); - r->d[0] = t & 0xFFFFFFFFULL; t >>= 32; - t += (uint64_t)r->d[1] + (((uint32_t)((bit >> 5) == 1)) << (bit & 0x1F)); - r->d[1] = t & 0xFFFFFFFFULL; t >>= 32; - t += (uint64_t)r->d[2] + (((uint32_t)((bit >> 5) == 2)) << (bit & 0x1F)); - r->d[2] = t & 0xFFFFFFFFULL; t >>= 32; - t += (uint64_t)r->d[3] + (((uint32_t)((bit >> 5) == 3)) << (bit & 0x1F)); - r->d[3] = t & 0xFFFFFFFFULL; t >>= 32; - t += (uint64_t)r->d[4] + (((uint32_t)((bit >> 5) == 4)) << (bit & 0x1F)); - r->d[4] = t & 0xFFFFFFFFULL; t >>= 32; - t += (uint64_t)r->d[5] + (((uint32_t)((bit >> 5) == 5)) << (bit & 0x1F)); - r->d[5] = t & 0xFFFFFFFFULL; t >>= 32; - t += (uint64_t)r->d[6] + (((uint32_t)((bit >> 5) == 6)) << (bit & 0x1F)); - r->d[6] = t & 0xFFFFFFFFULL; t >>= 32; - t += (uint64_t)r->d[7] + (((uint32_t)((bit >> 5) == 7)) << (bit & 0x1F)); - r->d[7] = t & 0xFFFFFFFFULL; -#ifdef VERIFY - VERIFY_CHECK((t >> 32) == 0); - VERIFY_CHECK(secp256k1_scalar_check_overflow(r) == 0); -#endif -} - -static void secp256k1_scalar_set_b32(secp256k1_scalar_t *r, const unsigned char *b32, int *overflow) { - int over; - r->d[0] = (uint32_t)b32[31] | (uint32_t)b32[30] << 8 | (uint32_t)b32[29] << 16 | (uint32_t)b32[28] << 24; - r->d[1] = (uint32_t)b32[27] | (uint32_t)b32[26] << 8 | (uint32_t)b32[25] << 16 | (uint32_t)b32[24] << 24; - r->d[2] = (uint32_t)b32[23] | (uint32_t)b32[22] << 8 | (uint32_t)b32[21] << 16 | (uint32_t)b32[20] << 24; - r->d[3] = (uint32_t)b32[19] | (uint32_t)b32[18] << 8 | (uint32_t)b32[17] << 16 | (uint32_t)b32[16] << 24; - r->d[4] = (uint32_t)b32[15] | (uint32_t)b32[14] << 8 | (uint32_t)b32[13] << 16 | (uint32_t)b32[12] << 24; - r->d[5] = (uint32_t)b32[11] | (uint32_t)b32[10] << 8 | (uint32_t)b32[9] << 16 | (uint32_t)b32[8] << 24; - r->d[6] = (uint32_t)b32[7] | (uint32_t)b32[6] << 8 | (uint32_t)b32[5] << 16 | (uint32_t)b32[4] << 24; - r->d[7] = (uint32_t)b32[3] | (uint32_t)b32[2] << 8 | (uint32_t)b32[1] << 16 | (uint32_t)b32[0] << 24; - over = secp256k1_scalar_reduce(r, secp256k1_scalar_check_overflow(r)); - if (overflow) { - *overflow = over; - } -} - -static void secp256k1_scalar_get_b32(unsigned char *bin, const secp256k1_scalar_t* a) { - bin[0] = a->d[7] >> 24; bin[1] = a->d[7] >> 16; bin[2] = a->d[7] >> 8; bin[3] = a->d[7]; - bin[4] = a->d[6] >> 24; bin[5] = a->d[6] >> 16; bin[6] = a->d[6] >> 8; bin[7] = a->d[6]; - bin[8] = a->d[5] >> 24; bin[9] = a->d[5] >> 16; bin[10] = a->d[5] >> 8; bin[11] = a->d[5]; - bin[12] = a->d[4] >> 24; bin[13] = a->d[4] >> 16; bin[14] = a->d[4] >> 8; bin[15] = a->d[4]; - bin[16] = a->d[3] >> 24; bin[17] = a->d[3] >> 16; bin[18] = a->d[3] >> 8; bin[19] = a->d[3]; - bin[20] = a->d[2] >> 24; bin[21] = a->d[2] >> 16; bin[22] = a->d[2] >> 8; bin[23] = a->d[2]; - bin[24] = a->d[1] >> 24; bin[25] = a->d[1] >> 16; bin[26] = a->d[1] >> 8; bin[27] = a->d[1]; - bin[28] = a->d[0] >> 24; bin[29] = a->d[0] >> 16; bin[30] = a->d[0] >> 8; bin[31] = a->d[0]; -} - -SECP256K1_INLINE static int secp256k1_scalar_is_zero(const secp256k1_scalar_t *a) { - return (a->d[0] | a->d[1] | a->d[2] | a->d[3] | a->d[4] | a->d[5] | a->d[6] | a->d[7]) == 0; -} - -static void secp256k1_scalar_negate(secp256k1_scalar_t *r, const secp256k1_scalar_t *a) { - uint32_t nonzero = 0xFFFFFFFFUL * (secp256k1_scalar_is_zero(a) == 0); - uint64_t t = (uint64_t)(~a->d[0]) + SECP256K1_N_0 + 1; - r->d[0] = t & nonzero; t >>= 32; - t += (uint64_t)(~a->d[1]) + SECP256K1_N_1; - r->d[1] = t & nonzero; t >>= 32; - t += (uint64_t)(~a->d[2]) + SECP256K1_N_2; - r->d[2] = t & nonzero; t >>= 32; - t += (uint64_t)(~a->d[3]) + SECP256K1_N_3; - r->d[3] = t & nonzero; t >>= 32; - t += (uint64_t)(~a->d[4]) + SECP256K1_N_4; - r->d[4] = t & nonzero; t >>= 32; - t += (uint64_t)(~a->d[5]) + SECP256K1_N_5; - r->d[5] = t & nonzero; t >>= 32; - t += (uint64_t)(~a->d[6]) + SECP256K1_N_6; - r->d[6] = t & nonzero; t >>= 32; - t += (uint64_t)(~a->d[7]) + SECP256K1_N_7; - r->d[7] = t & nonzero; -} - -SECP256K1_INLINE static int secp256k1_scalar_is_one(const secp256k1_scalar_t *a) { - return ((a->d[0] ^ 1) | a->d[1] | a->d[2] | a->d[3] | a->d[4] | a->d[5] | a->d[6] | a->d[7]) == 0; -} - -static int secp256k1_scalar_is_high(const secp256k1_scalar_t *a) { - int yes = 0; - int no = 0; - no |= (a->d[7] < SECP256K1_N_H_7); - yes |= (a->d[7] > SECP256K1_N_H_7) & ~no; - no |= (a->d[6] < SECP256K1_N_H_6) & ~yes; /* No need for a > check. */ - no |= (a->d[5] < SECP256K1_N_H_5) & ~yes; /* No need for a > check. */ - no |= (a->d[4] < SECP256K1_N_H_4) & ~yes; /* No need for a > check. */ - no |= (a->d[3] < SECP256K1_N_H_3) & ~yes; - yes |= (a->d[3] > SECP256K1_N_H_3) & ~no; - no |= (a->d[2] < SECP256K1_N_H_2) & ~yes; - yes |= (a->d[2] > SECP256K1_N_H_2) & ~no; - no |= (a->d[1] < SECP256K1_N_H_1) & ~yes; - yes |= (a->d[1] > SECP256K1_N_H_1) & ~no; - yes |= (a->d[0] > SECP256K1_N_H_0) & ~no; - return yes; -} - -/* Inspired by the macros in OpenSSL's crypto/bn/asm/x86_64-gcc.c. */ - -/** Add a*b to the number defined by (c0,c1,c2). c2 must never overflow. */ -#define muladd(a,b) { \ - uint32_t tl, th; \ - { \ - uint64_t t = (uint64_t)a * b; \ - th = t >> 32; /* at most 0xFFFFFFFE */ \ - tl = t; \ - } \ - c0 += tl; /* overflow is handled on the next line */ \ - th += (c0 < tl) ? 1 : 0; /* at most 0xFFFFFFFF */ \ - c1 += th; /* overflow is handled on the next line */ \ - c2 += (c1 < th) ? 1 : 0; /* never overflows by contract (verified in the next line) */ \ - VERIFY_CHECK((c1 >= th) || (c2 != 0)); \ -} - -/** Add a*b to the number defined by (c0,c1). c1 must never overflow. */ -#define muladd_fast(a,b) { \ - uint32_t tl, th; \ - { \ - uint64_t t = (uint64_t)a * b; \ - th = t >> 32; /* at most 0xFFFFFFFE */ \ - tl = t; \ - } \ - c0 += tl; /* overflow is handled on the next line */ \ - th += (c0 < tl) ? 1 : 0; /* at most 0xFFFFFFFF */ \ - c1 += th; /* never overflows by contract (verified in the next line) */ \ - VERIFY_CHECK(c1 >= th); \ -} - -/** Add 2*a*b to the number defined by (c0,c1,c2). c2 must never overflow. */ -#define muladd2(a,b) { \ - uint32_t tl, th, th2, tl2; \ - { \ - uint64_t t = (uint64_t)a * b; \ - th = t >> 32; /* at most 0xFFFFFFFE */ \ - tl = t; \ - } \ - th2 = th + th; /* at most 0xFFFFFFFE (in case th was 0x7FFFFFFF) */ \ - c2 += (th2 < th) ? 1 : 0; /* never overflows by contract (verified the next line) */ \ - VERIFY_CHECK((th2 >= th) || (c2 != 0)); \ - tl2 = tl + tl; /* at most 0xFFFFFFFE (in case the lowest 63 bits of tl were 0x7FFFFFFF) */ \ - th2 += (tl2 < tl) ? 1 : 0; /* at most 0xFFFFFFFF */ \ - c0 += tl2; /* overflow is handled on the next line */ \ - th2 += (c0 < tl2) ? 1 : 0; /* second overflow is handled on the next line */ \ - c2 += (c0 < tl2) & (th2 == 0); /* never overflows by contract (verified the next line) */ \ - VERIFY_CHECK((c0 >= tl2) || (th2 != 0) || (c2 != 0)); \ - c1 += th2; /* overflow is handled on the next line */ \ - c2 += (c1 < th2) ? 1 : 0; /* never overflows by contract (verified the next line) */ \ - VERIFY_CHECK((c1 >= th2) || (c2 != 0)); \ -} - -/** Add a to the number defined by (c0,c1,c2). c2 must never overflow. */ -#define sumadd(a) { \ - unsigned int over; \ - c0 += (a); /* overflow is handled on the next line */ \ - over = (c0 < (a)) ? 1 : 0; \ - c1 += over; /* overflow is handled on the next line */ \ - c2 += (c1 < over) ? 1 : 0; /* never overflows by contract */ \ -} - -/** Add a to the number defined by (c0,c1). c1 must never overflow, c2 must be zero. */ -#define sumadd_fast(a) { \ - c0 += (a); /* overflow is handled on the next line */ \ - c1 += (c0 < (a)) ? 1 : 0; /* never overflows by contract (verified the next line) */ \ - VERIFY_CHECK((c1 != 0) | (c0 >= (a))); \ - VERIFY_CHECK(c2 == 0); \ -} - -/** Extract the lowest 32 bits of (c0,c1,c2) into n, and left shift the number 32 bits. */ -#define extract(n) { \ - (n) = c0; \ - c0 = c1; \ - c1 = c2; \ - c2 = 0; \ -} - -/** Extract the lowest 32 bits of (c0,c1,c2) into n, and left shift the number 32 bits. c2 is required to be zero. */ -#define extract_fast(n) { \ - (n) = c0; \ - c0 = c1; \ - c1 = 0; \ - VERIFY_CHECK(c2 == 0); \ -} - -static void secp256k1_scalar_reduce_512(secp256k1_scalar_t *r, const uint32_t *l) { - uint64_t c; - uint32_t n0 = l[8], n1 = l[9], n2 = l[10], n3 = l[11], n4 = l[12], n5 = l[13], n6 = l[14], n7 = l[15]; - uint32_t m0, m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12; - uint32_t p0, p1, p2, p3, p4, p5, p6, p7, p8; - - /* 96 bit accumulator. */ - uint32_t c0, c1, c2; - - /* Reduce 512 bits into 385. */ - /* m[0..12] = l[0..7] + n[0..7] * SECP256K1_N_C. */ - c0 = l[0]; c1 = 0; c2 = 0; - muladd_fast(n0, SECP256K1_N_C_0); - extract_fast(m0); - sumadd_fast(l[1]); - muladd(n1, SECP256K1_N_C_0); - muladd(n0, SECP256K1_N_C_1); - extract(m1); - sumadd(l[2]); - muladd(n2, SECP256K1_N_C_0); - muladd(n1, SECP256K1_N_C_1); - muladd(n0, SECP256K1_N_C_2); - extract(m2); - sumadd(l[3]); - muladd(n3, SECP256K1_N_C_0); - muladd(n2, SECP256K1_N_C_1); - muladd(n1, SECP256K1_N_C_2); - muladd(n0, SECP256K1_N_C_3); - extract(m3); - sumadd(l[4]); - muladd(n4, SECP256K1_N_C_0); - muladd(n3, SECP256K1_N_C_1); - muladd(n2, SECP256K1_N_C_2); - muladd(n1, SECP256K1_N_C_3); - sumadd(n0); - extract(m4); - sumadd(l[5]); - muladd(n5, SECP256K1_N_C_0); - muladd(n4, SECP256K1_N_C_1); - muladd(n3, SECP256K1_N_C_2); - muladd(n2, SECP256K1_N_C_3); - sumadd(n1); - extract(m5); - sumadd(l[6]); - muladd(n6, SECP256K1_N_C_0); - muladd(n5, SECP256K1_N_C_1); - muladd(n4, SECP256K1_N_C_2); - muladd(n3, SECP256K1_N_C_3); - sumadd(n2); - extract(m6); - sumadd(l[7]); - muladd(n7, SECP256K1_N_C_0); - muladd(n6, SECP256K1_N_C_1); - muladd(n5, SECP256K1_N_C_2); - muladd(n4, SECP256K1_N_C_3); - sumadd(n3); - extract(m7); - muladd(n7, SECP256K1_N_C_1); - muladd(n6, SECP256K1_N_C_2); - muladd(n5, SECP256K1_N_C_3); - sumadd(n4); - extract(m8); - muladd(n7, SECP256K1_N_C_2); - muladd(n6, SECP256K1_N_C_3); - sumadd(n5); - extract(m9); - muladd(n7, SECP256K1_N_C_3); - sumadd(n6); - extract(m10); - sumadd_fast(n7); - extract_fast(m11); - VERIFY_CHECK(c0 <= 1); - m12 = c0; - - /* Reduce 385 bits into 258. */ - /* p[0..8] = m[0..7] + m[8..12] * SECP256K1_N_C. */ - c0 = m0; c1 = 0; c2 = 0; - muladd_fast(m8, SECP256K1_N_C_0); - extract_fast(p0); - sumadd_fast(m1); - muladd(m9, SECP256K1_N_C_0); - muladd(m8, SECP256K1_N_C_1); - extract(p1); - sumadd(m2); - muladd(m10, SECP256K1_N_C_0); - muladd(m9, SECP256K1_N_C_1); - muladd(m8, SECP256K1_N_C_2); - extract(p2); - sumadd(m3); - muladd(m11, SECP256K1_N_C_0); - muladd(m10, SECP256K1_N_C_1); - muladd(m9, SECP256K1_N_C_2); - muladd(m8, SECP256K1_N_C_3); - extract(p3); - sumadd(m4); - muladd(m12, SECP256K1_N_C_0); - muladd(m11, SECP256K1_N_C_1); - muladd(m10, SECP256K1_N_C_2); - muladd(m9, SECP256K1_N_C_3); - sumadd(m8); - extract(p4); - sumadd(m5); - muladd(m12, SECP256K1_N_C_1); - muladd(m11, SECP256K1_N_C_2); - muladd(m10, SECP256K1_N_C_3); - sumadd(m9); - extract(p5); - sumadd(m6); - muladd(m12, SECP256K1_N_C_2); - muladd(m11, SECP256K1_N_C_3); - sumadd(m10); - extract(p6); - sumadd_fast(m7); - muladd_fast(m12, SECP256K1_N_C_3); - sumadd_fast(m11); - extract_fast(p7); - p8 = c0 + m12; - VERIFY_CHECK(p8 <= 2); - - /* Reduce 258 bits into 256. */ - /* r[0..7] = p[0..7] + p[8] * SECP256K1_N_C. */ - c = p0 + (uint64_t)SECP256K1_N_C_0 * p8; - r->d[0] = c & 0xFFFFFFFFUL; c >>= 32; - c += p1 + (uint64_t)SECP256K1_N_C_1 * p8; - r->d[1] = c & 0xFFFFFFFFUL; c >>= 32; - c += p2 + (uint64_t)SECP256K1_N_C_2 * p8; - r->d[2] = c & 0xFFFFFFFFUL; c >>= 32; - c += p3 + (uint64_t)SECP256K1_N_C_3 * p8; - r->d[3] = c & 0xFFFFFFFFUL; c >>= 32; - c += p4 + (uint64_t)p8; - r->d[4] = c & 0xFFFFFFFFUL; c >>= 32; - c += p5; - r->d[5] = c & 0xFFFFFFFFUL; c >>= 32; - c += p6; - r->d[6] = c & 0xFFFFFFFFUL; c >>= 32; - c += p7; - r->d[7] = c & 0xFFFFFFFFUL; c >>= 32; - - /* Final reduction of r. */ - secp256k1_scalar_reduce(r, c + secp256k1_scalar_check_overflow(r)); -} - -static void secp256k1_scalar_mul_512(uint32_t *l, const secp256k1_scalar_t *a, const secp256k1_scalar_t *b) { - /* 96 bit accumulator. */ - uint32_t c0 = 0, c1 = 0, c2 = 0; - - /* l[0..15] = a[0..7] * b[0..7]. */ - muladd_fast(a->d[0], b->d[0]); - extract_fast(l[0]); - muladd(a->d[0], b->d[1]); - muladd(a->d[1], b->d[0]); - extract(l[1]); - muladd(a->d[0], b->d[2]); - muladd(a->d[1], b->d[1]); - muladd(a->d[2], b->d[0]); - extract(l[2]); - muladd(a->d[0], b->d[3]); - muladd(a->d[1], b->d[2]); - muladd(a->d[2], b->d[1]); - muladd(a->d[3], b->d[0]); - extract(l[3]); - muladd(a->d[0], b->d[4]); - muladd(a->d[1], b->d[3]); - muladd(a->d[2], b->d[2]); - muladd(a->d[3], b->d[1]); - muladd(a->d[4], b->d[0]); - extract(l[4]); - muladd(a->d[0], b->d[5]); - muladd(a->d[1], b->d[4]); - muladd(a->d[2], b->d[3]); - muladd(a->d[3], b->d[2]); - muladd(a->d[4], b->d[1]); - muladd(a->d[5], b->d[0]); - extract(l[5]); - muladd(a->d[0], b->d[6]); - muladd(a->d[1], b->d[5]); - muladd(a->d[2], b->d[4]); - muladd(a->d[3], b->d[3]); - muladd(a->d[4], b->d[2]); - muladd(a->d[5], b->d[1]); - muladd(a->d[6], b->d[0]); - extract(l[6]); - muladd(a->d[0], b->d[7]); - muladd(a->d[1], b->d[6]); - muladd(a->d[2], b->d[5]); - muladd(a->d[3], b->d[4]); - muladd(a->d[4], b->d[3]); - muladd(a->d[5], b->d[2]); - muladd(a->d[6], b->d[1]); - muladd(a->d[7], b->d[0]); - extract(l[7]); - muladd(a->d[1], b->d[7]); - muladd(a->d[2], b->d[6]); - muladd(a->d[3], b->d[5]); - muladd(a->d[4], b->d[4]); - muladd(a->d[5], b->d[3]); - muladd(a->d[6], b->d[2]); - muladd(a->d[7], b->d[1]); - extract(l[8]); - muladd(a->d[2], b->d[7]); - muladd(a->d[3], b->d[6]); - muladd(a->d[4], b->d[5]); - muladd(a->d[5], b->d[4]); - muladd(a->d[6], b->d[3]); - muladd(a->d[7], b->d[2]); - extract(l[9]); - muladd(a->d[3], b->d[7]); - muladd(a->d[4], b->d[6]); - muladd(a->d[5], b->d[5]); - muladd(a->d[6], b->d[4]); - muladd(a->d[7], b->d[3]); - extract(l[10]); - muladd(a->d[4], b->d[7]); - muladd(a->d[5], b->d[6]); - muladd(a->d[6], b->d[5]); - muladd(a->d[7], b->d[4]); - extract(l[11]); - muladd(a->d[5], b->d[7]); - muladd(a->d[6], b->d[6]); - muladd(a->d[7], b->d[5]); - extract(l[12]); - muladd(a->d[6], b->d[7]); - muladd(a->d[7], b->d[6]); - extract(l[13]); - muladd_fast(a->d[7], b->d[7]); - extract_fast(l[14]); - VERIFY_CHECK(c1 == 0); - l[15] = c0; -} - -static void secp256k1_scalar_sqr_512(uint32_t *l, const secp256k1_scalar_t *a) { - /* 96 bit accumulator. */ - uint32_t c0 = 0, c1 = 0, c2 = 0; - - /* l[0..15] = a[0..7]^2. */ - muladd_fast(a->d[0], a->d[0]); - extract_fast(l[0]); - muladd2(a->d[0], a->d[1]); - extract(l[1]); - muladd2(a->d[0], a->d[2]); - muladd(a->d[1], a->d[1]); - extract(l[2]); - muladd2(a->d[0], a->d[3]); - muladd2(a->d[1], a->d[2]); - extract(l[3]); - muladd2(a->d[0], a->d[4]); - muladd2(a->d[1], a->d[3]); - muladd(a->d[2], a->d[2]); - extract(l[4]); - muladd2(a->d[0], a->d[5]); - muladd2(a->d[1], a->d[4]); - muladd2(a->d[2], a->d[3]); - extract(l[5]); - muladd2(a->d[0], a->d[6]); - muladd2(a->d[1], a->d[5]); - muladd2(a->d[2], a->d[4]); - muladd(a->d[3], a->d[3]); - extract(l[6]); - muladd2(a->d[0], a->d[7]); - muladd2(a->d[1], a->d[6]); - muladd2(a->d[2], a->d[5]); - muladd2(a->d[3], a->d[4]); - extract(l[7]); - muladd2(a->d[1], a->d[7]); - muladd2(a->d[2], a->d[6]); - muladd2(a->d[3], a->d[5]); - muladd(a->d[4], a->d[4]); - extract(l[8]); - muladd2(a->d[2], a->d[7]); - muladd2(a->d[3], a->d[6]); - muladd2(a->d[4], a->d[5]); - extract(l[9]); - muladd2(a->d[3], a->d[7]); - muladd2(a->d[4], a->d[6]); - muladd(a->d[5], a->d[5]); - extract(l[10]); - muladd2(a->d[4], a->d[7]); - muladd2(a->d[5], a->d[6]); - extract(l[11]); - muladd2(a->d[5], a->d[7]); - muladd(a->d[6], a->d[6]); - extract(l[12]); - muladd2(a->d[6], a->d[7]); - extract(l[13]); - muladd_fast(a->d[7], a->d[7]); - extract_fast(l[14]); - VERIFY_CHECK(c1 == 0); - l[15] = c0; -} - -#undef sumadd -#undef sumadd_fast -#undef muladd -#undef muladd_fast -#undef muladd2 -#undef extract -#undef extract_fast - -static void secp256k1_scalar_mul(secp256k1_scalar_t *r, const secp256k1_scalar_t *a, const secp256k1_scalar_t *b) { - uint32_t l[16]; - secp256k1_scalar_mul_512(l, a, b); - secp256k1_scalar_reduce_512(r, l); -} - -static void secp256k1_scalar_sqr(secp256k1_scalar_t *r, const secp256k1_scalar_t *a) { - uint32_t l[16]; - secp256k1_scalar_sqr_512(l, a); - secp256k1_scalar_reduce_512(r, l); -} - -#ifdef USE_ENDOMORPHISM -static void secp256k1_scalar_split_128(secp256k1_scalar_t *r1, secp256k1_scalar_t *r2, const secp256k1_scalar_t *a) { - r1->d[0] = a->d[0]; - r1->d[1] = a->d[1]; - r1->d[2] = a->d[2]; - r1->d[3] = a->d[3]; - r1->d[4] = 0; - r1->d[5] = 0; - r1->d[6] = 0; - r1->d[7] = 0; - r2->d[0] = a->d[4]; - r2->d[1] = a->d[5]; - r2->d[2] = a->d[6]; - r2->d[3] = a->d[7]; - r2->d[4] = 0; - r2->d[5] = 0; - r2->d[6] = 0; - r2->d[7] = 0; -} -#endif - -SECP256K1_INLINE static int secp256k1_scalar_eq(const secp256k1_scalar_t *a, const secp256k1_scalar_t *b) { - return ((a->d[0] ^ b->d[0]) | (a->d[1] ^ b->d[1]) | (a->d[2] ^ b->d[2]) | (a->d[3] ^ b->d[3]) | (a->d[4] ^ b->d[4]) | (a->d[5] ^ b->d[5]) | (a->d[6] ^ b->d[6]) | (a->d[7] ^ b->d[7])) == 0; -} - -SECP256K1_INLINE static void secp256k1_scalar_mul_shift_var(secp256k1_scalar_t *r, const secp256k1_scalar_t *a, const secp256k1_scalar_t *b, unsigned int shift) { - uint32_t l[16]; - unsigned int shiftlimbs; - unsigned int shiftlow; - unsigned int shifthigh; - VERIFY_CHECK(shift >= 256); - secp256k1_scalar_mul_512(l, a, b); - shiftlimbs = shift >> 5; - shiftlow = shift & 0x1F; - shifthigh = 32 - shiftlow; - r->d[0] = shift < 512 ? (l[0 + shiftlimbs] >> shiftlow | (shift < 480 && shiftlow ? (l[1 + shiftlimbs] << shifthigh) : 0)) : 0; - r->d[1] = shift < 480 ? (l[1 + shiftlimbs] >> shiftlow | (shift < 448 && shiftlow ? (l[2 + shiftlimbs] << shifthigh) : 0)) : 0; - r->d[2] = shift < 448 ? (l[2 + shiftlimbs] >> shiftlow | (shift < 416 && shiftlow ? (l[3 + shiftlimbs] << shifthigh) : 0)) : 0; - r->d[3] = shift < 416 ? (l[3 + shiftlimbs] >> shiftlow | (shift < 384 && shiftlow ? (l[4 + shiftlimbs] << shifthigh) : 0)) : 0; - r->d[4] = shift < 384 ? (l[4 + shiftlimbs] >> shiftlow | (shift < 352 && shiftlow ? (l[5 + shiftlimbs] << shifthigh) : 0)) : 0; - r->d[5] = shift < 352 ? (l[5 + shiftlimbs] >> shiftlow | (shift < 320 && shiftlow ? (l[6 + shiftlimbs] << shifthigh) : 0)) : 0; - r->d[6] = shift < 320 ? (l[6 + shiftlimbs] >> shiftlow | (shift < 288 && shiftlow ? (l[7 + shiftlimbs] << shifthigh) : 0)) : 0; - r->d[7] = shift < 288 ? (l[7 + shiftlimbs] >> shiftlow) : 0; - if ((l[(shift - 1) >> 5] >> ((shift - 1) & 0x1f)) & 1) { - secp256k1_scalar_add_bit(r, 0); - } -} - -#endif diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/scalar_impl.h b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/scalar_impl.h deleted file mode 100644 index 33824983e4d529c345f4d9c0f2ae222d24777b3f..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/scalar_impl.h +++ /dev/null @@ -1,327 +0,0 @@ -/********************************************************************** - * 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_SCALAR_IMPL_H_ -#define _SECP256K1_SCALAR_IMPL_H_ - -#include <string.h> - -#include "group.h" -#include "scalar.h" - -#if defined HAVE_CONFIG_H -#include "libsecp256k1-config.h" -#endif - -#if defined(USE_SCALAR_4X64) -#include "scalar_4x64_impl.h" -#elif defined(USE_SCALAR_8X32) -#include "scalar_8x32_impl.h" -#else -#error "Please select scalar implementation" -#endif - -#ifndef USE_NUM_NONE -static void secp256k1_scalar_get_num(secp256k1_num_t *r, const secp256k1_scalar_t *a) { - unsigned char c[32]; - secp256k1_scalar_get_b32(c, a); - secp256k1_num_set_bin(r, c, 32); -} - -/** secp256k1 curve order, see secp256k1_ecdsa_const_order_as_fe in ecdsa_impl.h */ -static void secp256k1_scalar_order_get_num(secp256k1_num_t *r) { - static const unsigned char order[32] = { - 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 - }; - secp256k1_num_set_bin(r, order, 32); -} -#endif - -static void secp256k1_scalar_inverse(secp256k1_scalar_t *r, const secp256k1_scalar_t *x) { - secp256k1_scalar_t *t; - int i; - /* First compute x ^ (2^N - 1) for some values of N. */ - secp256k1_scalar_t x2, x3, x4, x6, x7, x8, x15, x30, x60, x120, x127; - - secp256k1_scalar_sqr(&x2, x); - secp256k1_scalar_mul(&x2, &x2, x); - - secp256k1_scalar_sqr(&x3, &x2); - secp256k1_scalar_mul(&x3, &x3, x); - - secp256k1_scalar_sqr(&x4, &x3); - secp256k1_scalar_mul(&x4, &x4, x); - - secp256k1_scalar_sqr(&x6, &x4); - secp256k1_scalar_sqr(&x6, &x6); - secp256k1_scalar_mul(&x6, &x6, &x2); - - secp256k1_scalar_sqr(&x7, &x6); - secp256k1_scalar_mul(&x7, &x7, x); - - secp256k1_scalar_sqr(&x8, &x7); - secp256k1_scalar_mul(&x8, &x8, x); - - secp256k1_scalar_sqr(&x15, &x8); - for (i = 0; i < 6; i++) { - secp256k1_scalar_sqr(&x15, &x15); - } - secp256k1_scalar_mul(&x15, &x15, &x7); - - secp256k1_scalar_sqr(&x30, &x15); - for (i = 0; i < 14; i++) { - secp256k1_scalar_sqr(&x30, &x30); - } - secp256k1_scalar_mul(&x30, &x30, &x15); - - secp256k1_scalar_sqr(&x60, &x30); - for (i = 0; i < 29; i++) { - secp256k1_scalar_sqr(&x60, &x60); - } - secp256k1_scalar_mul(&x60, &x60, &x30); - - secp256k1_scalar_sqr(&x120, &x60); - for (i = 0; i < 59; i++) { - secp256k1_scalar_sqr(&x120, &x120); - } - secp256k1_scalar_mul(&x120, &x120, &x60); - - secp256k1_scalar_sqr(&x127, &x120); - for (i = 0; i < 6; i++) { - secp256k1_scalar_sqr(&x127, &x127); - } - secp256k1_scalar_mul(&x127, &x127, &x7); - - /* Then accumulate the final result (t starts at x127). */ - t = &x127; - for (i = 0; i < 2; i++) { /* 0 */ - secp256k1_scalar_sqr(t, t); - } - secp256k1_scalar_mul(t, t, x); /* 1 */ - for (i = 0; i < 4; i++) { /* 0 */ - secp256k1_scalar_sqr(t, t); - } - secp256k1_scalar_mul(t, t, &x3); /* 111 */ - for (i = 0; i < 2; i++) { /* 0 */ - secp256k1_scalar_sqr(t, t); - } - secp256k1_scalar_mul(t, t, x); /* 1 */ - for (i = 0; i < 2; i++) { /* 0 */ - secp256k1_scalar_sqr(t, t); - } - secp256k1_scalar_mul(t, t, x); /* 1 */ - for (i = 0; i < 2; i++) { /* 0 */ - secp256k1_scalar_sqr(t, t); - } - secp256k1_scalar_mul(t, t, x); /* 1 */ - for (i = 0; i < 4; i++) { /* 0 */ - secp256k1_scalar_sqr(t, t); - } - secp256k1_scalar_mul(t, t, &x3); /* 111 */ - for (i = 0; i < 3; i++) { /* 0 */ - secp256k1_scalar_sqr(t, t); - } - secp256k1_scalar_mul(t, t, &x2); /* 11 */ - for (i = 0; i < 4; i++) { /* 0 */ - secp256k1_scalar_sqr(t, t); - } - secp256k1_scalar_mul(t, t, &x3); /* 111 */ - for (i = 0; i < 5; i++) { /* 00 */ - secp256k1_scalar_sqr(t, t); - } - secp256k1_scalar_mul(t, t, &x3); /* 111 */ - for (i = 0; i < 4; i++) { /* 00 */ - secp256k1_scalar_sqr(t, t); - } - secp256k1_scalar_mul(t, t, &x2); /* 11 */ - for (i = 0; i < 2; i++) { /* 0 */ - secp256k1_scalar_sqr(t, t); - } - secp256k1_scalar_mul(t, t, x); /* 1 */ - for (i = 0; i < 2; i++) { /* 0 */ - secp256k1_scalar_sqr(t, t); - } - secp256k1_scalar_mul(t, t, x); /* 1 */ - for (i = 0; i < 5; i++) { /* 0 */ - secp256k1_scalar_sqr(t, t); - } - secp256k1_scalar_mul(t, t, &x4); /* 1111 */ - for (i = 0; i < 2; i++) { /* 0 */ - secp256k1_scalar_sqr(t, t); - } - secp256k1_scalar_mul(t, t, x); /* 1 */ - for (i = 0; i < 3; i++) { /* 00 */ - secp256k1_scalar_sqr(t, t); - } - secp256k1_scalar_mul(t, t, x); /* 1 */ - for (i = 0; i < 4; i++) { /* 000 */ - secp256k1_scalar_sqr(t, t); - } - secp256k1_scalar_mul(t, t, x); /* 1 */ - for (i = 0; i < 2; i++) { /* 0 */ - secp256k1_scalar_sqr(t, t); - } - secp256k1_scalar_mul(t, t, x); /* 1 */ - for (i = 0; i < 10; i++) { /* 0000000 */ - secp256k1_scalar_sqr(t, t); - } - secp256k1_scalar_mul(t, t, &x3); /* 111 */ - for (i = 0; i < 4; i++) { /* 0 */ - secp256k1_scalar_sqr(t, t); - } - secp256k1_scalar_mul(t, t, &x3); /* 111 */ - for (i = 0; i < 9; i++) { /* 0 */ - secp256k1_scalar_sqr(t, t); - } - secp256k1_scalar_mul(t, t, &x8); /* 11111111 */ - for (i = 0; i < 2; i++) { /* 0 */ - secp256k1_scalar_sqr(t, t); - } - secp256k1_scalar_mul(t, t, x); /* 1 */ - for (i = 0; i < 3; i++) { /* 00 */ - secp256k1_scalar_sqr(t, t); - } - secp256k1_scalar_mul(t, t, x); /* 1 */ - for (i = 0; i < 3; i++) { /* 00 */ - secp256k1_scalar_sqr(t, t); - } - secp256k1_scalar_mul(t, t, x); /* 1 */ - for (i = 0; i < 5; i++) { /* 0 */ - secp256k1_scalar_sqr(t, t); - } - secp256k1_scalar_mul(t, t, &x4); /* 1111 */ - for (i = 0; i < 2; i++) { /* 0 */ - secp256k1_scalar_sqr(t, t); - } - secp256k1_scalar_mul(t, t, x); /* 1 */ - for (i = 0; i < 5; i++) { /* 000 */ - secp256k1_scalar_sqr(t, t); - } - secp256k1_scalar_mul(t, t, &x2); /* 11 */ - for (i = 0; i < 4; i++) { /* 00 */ - secp256k1_scalar_sqr(t, t); - } - secp256k1_scalar_mul(t, t, &x2); /* 11 */ - for (i = 0; i < 2; i++) { /* 0 */ - secp256k1_scalar_sqr(t, t); - } - secp256k1_scalar_mul(t, t, x); /* 1 */ - for (i = 0; i < 8; i++) { /* 000000 */ - secp256k1_scalar_sqr(t, t); - } - secp256k1_scalar_mul(t, t, &x2); /* 11 */ - for (i = 0; i < 3; i++) { /* 0 */ - secp256k1_scalar_sqr(t, t); - } - secp256k1_scalar_mul(t, t, &x2); /* 11 */ - for (i = 0; i < 3; i++) { /* 00 */ - secp256k1_scalar_sqr(t, t); - } - secp256k1_scalar_mul(t, t, x); /* 1 */ - for (i = 0; i < 6; i++) { /* 00000 */ - secp256k1_scalar_sqr(t, t); - } - secp256k1_scalar_mul(t, t, x); /* 1 */ - for (i = 0; i < 8; i++) { /* 00 */ - secp256k1_scalar_sqr(t, t); - } - secp256k1_scalar_mul(r, t, &x6); /* 111111 */ -} - -static void secp256k1_scalar_inverse_var(secp256k1_scalar_t *r, const secp256k1_scalar_t *x) { -#if defined(USE_SCALAR_INV_BUILTIN) - secp256k1_scalar_inverse(r, x); -#elif defined(USE_SCALAR_INV_NUM) - unsigned char b[32]; - secp256k1_num_t n, m; - secp256k1_scalar_get_b32(b, x); - secp256k1_num_set_bin(&n, b, 32); - secp256k1_scalar_order_get_num(&m); - secp256k1_num_mod_inverse(&n, &n, &m); - secp256k1_num_get_bin(b, 32, &n); - secp256k1_scalar_set_b32(r, b, NULL); -#else -#error "Please select scalar inverse implementation" -#endif -} - -#ifdef USE_ENDOMORPHISM -/** - * The Secp256k1 curve has an endomorphism, where lambda * (x, y) = (beta * x, y), where - * lambda is {0x53,0x63,0xad,0x4c,0xc0,0x5c,0x30,0xe0,0xa5,0x26,0x1c,0x02,0x88,0x12,0x64,0x5a, - * 0x12,0x2e,0x22,0xea,0x20,0x81,0x66,0x78,0xdf,0x02,0x96,0x7c,0x1b,0x23,0xbd,0x72} - * - * "Guide to Elliptic Curve Cryptography" (Hankerson, Menezes, Vanstone) gives an algorithm - * (algorithm 3.74) to find k1 and k2 given k, such that k1 + k2 * lambda == k mod n, and k1 - * and k2 have a small size. - * It relies on constants a1, b1, a2, b2. These constants for the value of lambda above are: - * - * - a1 = {0x30,0x86,0xd2,0x21,0xa7,0xd4,0x6b,0xcd,0xe8,0x6c,0x90,0xe4,0x92,0x84,0xeb,0x15} - * - b1 = -{0xe4,0x43,0x7e,0xd6,0x01,0x0e,0x88,0x28,0x6f,0x54,0x7f,0xa9,0x0a,0xbf,0xe4,0xc3} - * - a2 = {0x01,0x14,0xca,0x50,0xf7,0xa8,0xe2,0xf3,0xf6,0x57,0xc1,0x10,0x8d,0x9d,0x44,0xcf,0xd8} - * - b2 = {0x30,0x86,0xd2,0x21,0xa7,0xd4,0x6b,0xcd,0xe8,0x6c,0x90,0xe4,0x92,0x84,0xeb,0x15} - * - * The algorithm then computes c1 = round(b1 * k / n) and c2 = round(b2 * k / n), and gives - * k1 = k - (c1*a1 + c2*a2) and k2 = -(c1*b1 + c2*b2). Instead, we use modular arithmetic, and - * compute k1 as k - k2 * lambda, avoiding the need for constants a1 and a2. - * - * g1, g2 are precomputed constants used to replace division with a rounded multiplication - * when decomposing the scalar for an endomorphism-based point multiplication. - * - * The possibility of using precomputed estimates is mentioned in "Guide to Elliptic Curve - * Cryptography" (Hankerson, Menezes, Vanstone) in section 3.5. - * - * The derivation is described in the paper "Efficient Software Implementation of Public-Key - * Cryptography on Sensor Networks Using the MSP430X Microcontroller" (Gouvea, Oliveira, Lopez), - * Section 4.3 (here we use a somewhat higher-precision estimate): - * d = a1*b2 - b1*a2 - * g1 = round((2^272)*b2/d) - * g2 = round((2^272)*b1/d) - * - * (Note that 'd' is also equal to the curve order here because [a1,b1] and [a2,b2] are found - * as outputs of the Extended Euclidean Algorithm on inputs 'order' and 'lambda'). - * - * The function below splits a in r1 and r2, such that r1 + lambda * r2 == a (mod order). - */ - -static void secp256k1_scalar_split_lambda_var(secp256k1_scalar_t *r1, secp256k1_scalar_t *r2, const secp256k1_scalar_t *a) { - secp256k1_scalar_t c1, c2; - static const secp256k1_scalar_t minus_lambda = SECP256K1_SCALAR_CONST( - 0xAC9C52B3UL, 0x3FA3CF1FUL, 0x5AD9E3FDUL, 0x77ED9BA4UL, - 0xA880B9FCUL, 0x8EC739C2UL, 0xE0CFC810UL, 0xB51283CFUL - ); - static const secp256k1_scalar_t minus_b1 = SECP256K1_SCALAR_CONST( - 0x00000000UL, 0x00000000UL, 0x00000000UL, 0x00000000UL, - 0xE4437ED6UL, 0x010E8828UL, 0x6F547FA9UL, 0x0ABFE4C3UL - ); - static const secp256k1_scalar_t minus_b2 = SECP256K1_SCALAR_CONST( - 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFEUL, - 0x8A280AC5UL, 0x0774346DUL, 0xD765CDA8UL, 0x3DB1562CUL - ); - static const secp256k1_scalar_t g1 = SECP256K1_SCALAR_CONST( - 0x00000000UL, 0x00000000UL, 0x00000000UL, 0x00003086UL, - 0xD221A7D4UL, 0x6BCDE86CUL, 0x90E49284UL, 0xEB153DABUL - ); - static const secp256k1_scalar_t g2 = SECP256K1_SCALAR_CONST( - 0x00000000UL, 0x00000000UL, 0x00000000UL, 0x0000E443UL, - 0x7ED6010EUL, 0x88286F54UL, 0x7FA90ABFUL, 0xE4C42212UL - ); - VERIFY_CHECK(r1 != a); - VERIFY_CHECK(r2 != a); - secp256k1_scalar_mul_shift_var(&c1, a, &g1, 272); - secp256k1_scalar_mul_shift_var(&c2, a, &g2, 272); - secp256k1_scalar_mul(&c1, &c1, &minus_b1); - secp256k1_scalar_mul(&c2, &c2, &minus_b2); - secp256k1_scalar_add(r2, &c1, &c2); - secp256k1_scalar_mul(r1, r2, &minus_lambda); - secp256k1_scalar_add(r1, r1, a); -} -#endif - -#endif diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/secp256k1.c b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/secp256k1.c deleted file mode 100644 index c1320172f065b5d898ee3d35acfb1c03750067ec..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/secp256k1.c +++ /dev/null @@ -1,372 +0,0 @@ -/********************************************************************** - * 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.* - **********************************************************************/ - -#define SECP256K1_BUILD (1) - -#include "include/secp256k1.h" - -#include "util.h" -#include "num_impl.h" -#include "field_impl.h" -#include "scalar_impl.h" -#include "group_impl.h" -#include "ecmult_impl.h" -#include "ecmult_gen_impl.h" -#include "ecdsa_impl.h" -#include "eckey_impl.h" -#include "hash_impl.h" - -void secp256k1_start(unsigned int flags) { - if (flags & SECP256K1_START_SIGN) { - secp256k1_ecmult_gen_start(); - } - if (flags & SECP256K1_START_VERIFY) { - secp256k1_ecmult_start(); - } -} - -void secp256k1_stop(void) { - secp256k1_ecmult_stop(); - secp256k1_ecmult_gen_stop(); -} - -int secp256k1_ecdsa_verify(const unsigned char *msg32, const unsigned char *sig, int siglen, const unsigned char *pubkey, int pubkeylen) { - secp256k1_ge_t q; - secp256k1_ecdsa_sig_t s; - secp256k1_scalar_t m; - int ret = -3; - DEBUG_CHECK(secp256k1_ecmult_consts != NULL); - DEBUG_CHECK(msg32 != NULL); - DEBUG_CHECK(sig != NULL); - DEBUG_CHECK(pubkey != NULL); - - secp256k1_scalar_set_b32(&m, msg32, NULL); - - if (secp256k1_eckey_pubkey_parse(&q, pubkey, pubkeylen)) { - if (secp256k1_ecdsa_sig_parse(&s, sig, siglen)) { - if (secp256k1_ecdsa_sig_verify(&s, &q, &m)) { - /* success is 1, all other values are fail */ - ret = 1; - } else { - ret = 0; - } - } else { - ret = -2; - } - } else { - ret = -1; - } - - return ret; -} - -static int nonce_function_rfc6979(unsigned char *nonce32, const unsigned char *msg32, const unsigned char *key32, unsigned int counter, const void *data) { - secp256k1_rfc6979_hmac_sha256_t rng; - unsigned int i; - secp256k1_rfc6979_hmac_sha256_initialize(&rng, key32, 32, msg32, 32, (const unsigned char*)data, data != NULL ? 32 : 0); - for (i = 0; i <= counter; i++) { - secp256k1_rfc6979_hmac_sha256_generate(&rng, nonce32, 32); - } - secp256k1_rfc6979_hmac_sha256_finalize(&rng); - return 1; -} - -const secp256k1_nonce_function_t secp256k1_nonce_function_rfc6979 = nonce_function_rfc6979; -const secp256k1_nonce_function_t secp256k1_nonce_function_default = nonce_function_rfc6979; - -int secp256k1_ecdsa_sign(const unsigned char *msg32, unsigned char *signature, int *signaturelen, const unsigned char *seckey, secp256k1_nonce_function_t noncefp, const void* noncedata) { - secp256k1_ecdsa_sig_t sig; - secp256k1_scalar_t sec, non, msg; - int ret = 0; - int overflow = 0; - unsigned int count = 0; - DEBUG_CHECK(secp256k1_ecmult_gen_consts != NULL); - DEBUG_CHECK(msg32 != NULL); - DEBUG_CHECK(signature != NULL); - DEBUG_CHECK(signaturelen != NULL); - DEBUG_CHECK(seckey != NULL); - if (noncefp == NULL) { - noncefp = secp256k1_nonce_function_default; - } - - secp256k1_scalar_set_b32(&sec, seckey, &overflow); - /* Fail if the secret key is invalid. */ - if (!overflow && !secp256k1_scalar_is_zero(&sec)) { - secp256k1_scalar_set_b32(&msg, msg32, NULL); - while (1) { - unsigned char nonce32[32]; - ret = noncefp(nonce32, msg32, seckey, count, noncedata); - if (!ret) { - break; - } - secp256k1_scalar_set_b32(&non, nonce32, &overflow); - memset(nonce32, 0, 32); - if (!secp256k1_scalar_is_zero(&non) && !overflow) { - if (secp256k1_ecdsa_sig_sign(&sig, &sec, &msg, &non, NULL)) { - break; - } - } - count++; - } - if (ret) { - ret = secp256k1_ecdsa_sig_serialize(signature, signaturelen, &sig); - } - secp256k1_scalar_clear(&msg); - secp256k1_scalar_clear(&non); - secp256k1_scalar_clear(&sec); - } - if (!ret) { - *signaturelen = 0; - } - return ret; -} - -int secp256k1_ecdsa_sign_compact(const unsigned char *msg32, unsigned char *sig64, const unsigned char *seckey, secp256k1_nonce_function_t noncefp, const void* noncedata, int *recid) { - secp256k1_ecdsa_sig_t sig; - secp256k1_scalar_t sec, non, msg; - int ret = 0; - int overflow = 0; - unsigned int count = 0; - DEBUG_CHECK(secp256k1_ecmult_gen_consts != NULL); - DEBUG_CHECK(msg32 != NULL); - DEBUG_CHECK(sig64 != NULL); - DEBUG_CHECK(seckey != NULL); - if (noncefp == NULL) { - noncefp = secp256k1_nonce_function_default; - } - - secp256k1_scalar_set_b32(&sec, seckey, &overflow); - /* Fail if the secret key is invalid. */ - if (!overflow && !secp256k1_scalar_is_zero(&sec)) { - secp256k1_scalar_set_b32(&msg, msg32, NULL); - while (1) { - unsigned char nonce32[32]; - ret = noncefp(nonce32, msg32, seckey, count, noncedata); - if (!ret) { - break; - } - secp256k1_scalar_set_b32(&non, nonce32, &overflow); - memset(nonce32, 0, 32); - if (!secp256k1_scalar_is_zero(&non) && !overflow) { - if (secp256k1_ecdsa_sig_sign(&sig, &sec, &msg, &non, recid)) { - break; - } - } - count++; - } - if (ret) { - secp256k1_scalar_get_b32(sig64, &sig.r); - secp256k1_scalar_get_b32(sig64 + 32, &sig.s); - } - secp256k1_scalar_clear(&msg); - secp256k1_scalar_clear(&non); - secp256k1_scalar_clear(&sec); - } - if (!ret) { - memset(sig64, 0, 64); - } - return ret; -} - -int secp256k1_ecdsa_recover_compact(const unsigned char *msg32, const unsigned char *sig64, unsigned char *pubkey, int *pubkeylen, int compressed, int recid) { - secp256k1_ge_t q; - secp256k1_ecdsa_sig_t sig; - secp256k1_scalar_t m; - int ret = 0; - int overflow = 0; - DEBUG_CHECK(secp256k1_ecmult_consts != NULL); - DEBUG_CHECK(msg32 != NULL); - DEBUG_CHECK(sig64 != NULL); - DEBUG_CHECK(pubkey != NULL); - DEBUG_CHECK(pubkeylen != NULL); - DEBUG_CHECK(recid >= 0 && recid <= 3); - - secp256k1_scalar_set_b32(&sig.r, sig64, &overflow); - if (!overflow) { - secp256k1_scalar_set_b32(&sig.s, sig64 + 32, &overflow); - if (!overflow) { - secp256k1_scalar_set_b32(&m, msg32, NULL); - - if (secp256k1_ecdsa_sig_recover(&sig, &q, &m, recid)) { - ret = secp256k1_eckey_pubkey_serialize(&q, pubkey, pubkeylen, compressed); - } - } - } - return ret; -} - -int secp256k1_ec_seckey_verify(const unsigned char *seckey) { - secp256k1_scalar_t sec; - int ret; - int overflow; - DEBUG_CHECK(seckey != NULL); - - secp256k1_scalar_set_b32(&sec, seckey, &overflow); - ret = !secp256k1_scalar_is_zero(&sec) && !overflow; - secp256k1_scalar_clear(&sec); - return ret; -} - -int secp256k1_ec_pubkey_verify(const unsigned char *pubkey, int pubkeylen) { - secp256k1_ge_t q; - DEBUG_CHECK(pubkey != NULL); - - return secp256k1_eckey_pubkey_parse(&q, pubkey, pubkeylen); -} - -int secp256k1_ec_pubkey_create(unsigned char *pubkey, int *pubkeylen, const unsigned char *seckey, int compressed) { - secp256k1_gej_t pj; - secp256k1_ge_t p; - secp256k1_scalar_t sec; - int overflow; - int ret = 0; - DEBUG_CHECK(secp256k1_ecmult_gen_consts != NULL); - DEBUG_CHECK(pubkey != NULL); - DEBUG_CHECK(pubkeylen != NULL); - DEBUG_CHECK(seckey != NULL); - - secp256k1_scalar_set_b32(&sec, seckey, &overflow); - if (!overflow) { - secp256k1_ecmult_gen(&pj, &sec); - secp256k1_scalar_clear(&sec); - secp256k1_ge_set_gej(&p, &pj); - ret = secp256k1_eckey_pubkey_serialize(&p, pubkey, pubkeylen, compressed); - } - if (!ret) { - *pubkeylen = 0; - } - return ret; -} - -int secp256k1_ec_pubkey_decompress(unsigned char *pubkey, int *pubkeylen) { - secp256k1_ge_t p; - int ret = 0; - DEBUG_CHECK(pubkey != NULL); - DEBUG_CHECK(pubkeylen != NULL); - - if (secp256k1_eckey_pubkey_parse(&p, pubkey, *pubkeylen)) { - ret = secp256k1_eckey_pubkey_serialize(&p, pubkey, pubkeylen, 0); - } - return ret; -} - -int secp256k1_ec_privkey_tweak_add(unsigned char *seckey, const unsigned char *tweak) { - secp256k1_scalar_t term; - secp256k1_scalar_t sec; - int ret = 0; - int overflow = 0; - DEBUG_CHECK(seckey != NULL); - DEBUG_CHECK(tweak != NULL); - - secp256k1_scalar_set_b32(&term, tweak, &overflow); - secp256k1_scalar_set_b32(&sec, seckey, NULL); - - ret = secp256k1_eckey_privkey_tweak_add(&sec, &term) && !overflow; - if (ret) { - secp256k1_scalar_get_b32(seckey, &sec); - } - - secp256k1_scalar_clear(&sec); - secp256k1_scalar_clear(&term); - return ret; -} - -int secp256k1_ec_pubkey_tweak_add(unsigned char *pubkey, int pubkeylen, const unsigned char *tweak) { - secp256k1_ge_t p; - secp256k1_scalar_t term; - int ret = 0; - int overflow = 0; - DEBUG_CHECK(secp256k1_ecmult_consts != NULL); - DEBUG_CHECK(pubkey != NULL); - DEBUG_CHECK(tweak != NULL); - - secp256k1_scalar_set_b32(&term, tweak, &overflow); - if (!overflow) { - ret = secp256k1_eckey_pubkey_parse(&p, pubkey, pubkeylen); - if (ret) { - ret = secp256k1_eckey_pubkey_tweak_add(&p, &term); - } - if (ret) { - int oldlen = pubkeylen; - ret = secp256k1_eckey_pubkey_serialize(&p, pubkey, &pubkeylen, oldlen <= 33); - VERIFY_CHECK(pubkeylen == oldlen); - } - } - - return ret; -} - -int secp256k1_ec_privkey_tweak_mul(unsigned char *seckey, const unsigned char *tweak) { - secp256k1_scalar_t factor; - secp256k1_scalar_t sec; - int ret = 0; - int overflow = 0; - DEBUG_CHECK(seckey != NULL); - DEBUG_CHECK(tweak != NULL); - - secp256k1_scalar_set_b32(&factor, tweak, &overflow); - secp256k1_scalar_set_b32(&sec, seckey, NULL); - ret = secp256k1_eckey_privkey_tweak_mul(&sec, &factor) && !overflow; - if (ret) { - secp256k1_scalar_get_b32(seckey, &sec); - } - - secp256k1_scalar_clear(&sec); - secp256k1_scalar_clear(&factor); - return ret; -} - -int secp256k1_ec_pubkey_tweak_mul(unsigned char *pubkey, int pubkeylen, const unsigned char *tweak) { - secp256k1_ge_t p; - secp256k1_scalar_t factor; - int ret = 0; - int overflow = 0; - DEBUG_CHECK(secp256k1_ecmult_consts != NULL); - DEBUG_CHECK(pubkey != NULL); - DEBUG_CHECK(tweak != NULL); - - secp256k1_scalar_set_b32(&factor, tweak, &overflow); - if (!overflow) { - ret = secp256k1_eckey_pubkey_parse(&p, pubkey, pubkeylen); - if (ret) { - ret = secp256k1_eckey_pubkey_tweak_mul(&p, &factor); - } - if (ret) { - int oldlen = pubkeylen; - ret = secp256k1_eckey_pubkey_serialize(&p, pubkey, &pubkeylen, oldlen <= 33); - VERIFY_CHECK(pubkeylen == oldlen); - } - } - - return ret; -} - -int secp256k1_ec_privkey_export(const unsigned char *seckey, unsigned char *privkey, int *privkeylen, int compressed) { - secp256k1_scalar_t key; - int ret = 0; - DEBUG_CHECK(seckey != NULL); - DEBUG_CHECK(privkey != NULL); - DEBUG_CHECK(privkeylen != NULL); - - secp256k1_scalar_set_b32(&key, seckey, NULL); - ret = secp256k1_eckey_privkey_serialize(privkey, privkeylen, &key, compressed); - secp256k1_scalar_clear(&key); - return ret; -} - -int secp256k1_ec_privkey_import(unsigned char *seckey, const unsigned char *privkey, int privkeylen) { - secp256k1_scalar_t key; - int ret = 0; - DEBUG_CHECK(seckey != NULL); - DEBUG_CHECK(privkey != NULL); - - ret = secp256k1_eckey_privkey_parse(&key, privkey, privkeylen); - if (ret) { - secp256k1_scalar_get_b32(seckey, &key); - } - secp256k1_scalar_clear(&key); - return ret; -} diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/testrand.h b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/testrand.h deleted file mode 100644 index 041bb92c47aa52b5f4d94357bcf0d1f0115a7d3c..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/testrand.h +++ /dev/null @@ -1,28 +0,0 @@ -/********************************************************************** - * 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_TESTRAND_H_ -#define _SECP256K1_TESTRAND_H_ - -#if defined HAVE_CONFIG_H -#include "libsecp256k1-config.h" -#endif - -/* A non-cryptographic RNG used only for test infrastructure. */ - -/** Seed the pseudorandom number generator for testing. */ -SECP256K1_INLINE static void secp256k1_rand_seed(const unsigned char *seed16); - -/** Generate a pseudorandom 32-bit number. */ -static uint32_t secp256k1_rand32(void); - -/** Generate a pseudorandom 32-byte array. */ -static void secp256k1_rand256(unsigned char *b32); - -/** Generate a pseudorandom 32-byte array with long sequences of zero and one bits. */ -static void secp256k1_rand256_test(unsigned char *b32); - -#endif diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/testrand_impl.h b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/testrand_impl.h deleted file mode 100644 index 21c69f1c51eb45b277290f611521e489a20ee9ff..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/testrand_impl.h +++ /dev/null @@ -1,60 +0,0 @@ -/********************************************************************** - * 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_TESTRAND_IMPL_H_ -#define _SECP256K1_TESTRAND_IMPL_H_ - -#include <stdint.h> -#include <string.h> - -#include "testrand.h" -#include "hash.h" - -static secp256k1_rfc6979_hmac_sha256_t secp256k1_test_rng; -static uint32_t secp256k1_test_rng_precomputed[8]; -static int secp256k1_test_rng_precomputed_used = 8; - -SECP256K1_INLINE static void secp256k1_rand_seed(const unsigned char *seed16) { - secp256k1_rfc6979_hmac_sha256_initialize(&secp256k1_test_rng, (const unsigned char*)"TestRNG", 7, seed16, 16, NULL, 0); -} - -SECP256K1_INLINE static uint32_t secp256k1_rand32(void) { - if (secp256k1_test_rng_precomputed_used == 8) { - secp256k1_rfc6979_hmac_sha256_generate(&secp256k1_test_rng, (unsigned char*)(&secp256k1_test_rng_precomputed[0]), sizeof(secp256k1_test_rng_precomputed)); - secp256k1_test_rng_precomputed_used = 0; - } - return secp256k1_test_rng_precomputed[secp256k1_test_rng_precomputed_used++]; -} - -static void secp256k1_rand256(unsigned char *b32) { - secp256k1_rfc6979_hmac_sha256_generate(&secp256k1_test_rng, b32, 32); -} - -static void secp256k1_rand256_test(unsigned char *b32) { - int bits=0; - uint64_t ent = 0; - int entleft = 0; - memset(b32, 0, 32); - while (bits < 256) { - int now; - uint32_t val; - if (entleft < 12) { - ent |= ((uint64_t)secp256k1_rand32()) << entleft; - entleft += 32; - } - now = 1 + ((ent % 64)*((ent >> 6) % 32)+16)/31; - val = 1 & (ent >> 11); - ent >>= 12; - entleft -= 12; - while (now > 0 && bits < 256) { - b32[bits / 8] |= val << (bits % 8); - now--; - bits++; - } - } -} - -#endif diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/tests.c b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/tests.c deleted file mode 100644 index 6c473a0c1423794c582c7d6a0de2b59543501806..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/tests.c +++ /dev/null @@ -1,1917 +0,0 @@ -/********************************************************************** - * 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.* - **********************************************************************/ - -#if defined HAVE_CONFIG_H -#include "libsecp256k1-config.h" -#endif - -#include <stdio.h> -#include <stdlib.h> - -#include <time.h> - -#include "secp256k1.c" -#include "testrand_impl.h" - -#ifdef ENABLE_OPENSSL_TESTS -#include "openssl/bn.h" -#include "openssl/ec.h" -#include "openssl/ecdsa.h" -#include "openssl/obj_mac.h" -#endif - -static int count = 64; - -void random_field_element_test(secp256k1_fe_t *fe) { - do { - unsigned char b32[32]; - secp256k1_rand256_test(b32); - if (secp256k1_fe_set_b32(fe, b32)) { - break; - } - } while(1); -} - -void random_field_element_magnitude(secp256k1_fe_t *fe) { - secp256k1_fe_t zero; - int n = secp256k1_rand32() % 9; - secp256k1_fe_normalize(fe); - if (n == 0) { - return; - } - secp256k1_fe_clear(&zero); - secp256k1_fe_negate(&zero, &zero, 0); - secp256k1_fe_mul_int(&zero, n - 1); - secp256k1_fe_add(fe, &zero); -#ifdef VERIFY - CHECK(fe->magnitude == n); -#endif -} - -void random_group_element_test(secp256k1_ge_t *ge) { - secp256k1_fe_t fe; - do { - random_field_element_test(&fe); - if (secp256k1_ge_set_xo_var(ge, &fe, secp256k1_rand32() & 1)) { - break; - } - } while(1); -} - -void random_group_element_jacobian_test(secp256k1_gej_t *gej, const secp256k1_ge_t *ge) { - secp256k1_fe_t z2, z3; - do { - random_field_element_test(&gej->z); - if (!secp256k1_fe_is_zero(&gej->z)) { - break; - } - } while(1); - secp256k1_fe_sqr(&z2, &gej->z); - secp256k1_fe_mul(&z3, &z2, &gej->z); - secp256k1_fe_mul(&gej->x, &ge->x, &z2); - secp256k1_fe_mul(&gej->y, &ge->y, &z3); - gej->infinity = ge->infinity; -} - -void random_scalar_order_test(secp256k1_scalar_t *num) { - do { - unsigned char b32[32]; - int overflow = 0; - secp256k1_rand256_test(b32); - secp256k1_scalar_set_b32(num, b32, &overflow); - if (overflow || secp256k1_scalar_is_zero(num)) { - continue; - } - break; - } while(1); -} - -void random_scalar_order(secp256k1_scalar_t *num) { - do { - unsigned char b32[32]; - int overflow = 0; - secp256k1_rand256(b32); - secp256k1_scalar_set_b32(num, b32, &overflow); - if (overflow || secp256k1_scalar_is_zero(num)) { - continue; - } - break; - } while(1); -} - -/***** HASH TESTS *****/ - -void run_sha256_tests(void) { - static const char *inputs[8] = { - "", "abc", "message digest", "secure hash algorithm", "SHA256 is considered to be safe", - "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", - "For this sample, this 63-byte string will be used as input data", - "This is exactly 64 bytes long, not counting the terminating byte" - }; - static const unsigned char outputs[8][32] = { - {0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, 0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55}, - {0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea, 0x41, 0x41, 0x40, 0xde, 0x5d, 0xae, 0x22, 0x23, 0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c, 0xb4, 0x10, 0xff, 0x61, 0xf2, 0x00, 0x15, 0xad}, - {0xf7, 0x84, 0x6f, 0x55, 0xcf, 0x23, 0xe1, 0x4e, 0xeb, 0xea, 0xb5, 0xb4, 0xe1, 0x55, 0x0c, 0xad, 0x5b, 0x50, 0x9e, 0x33, 0x48, 0xfb, 0xc4, 0xef, 0xa3, 0xa1, 0x41, 0x3d, 0x39, 0x3c, 0xb6, 0x50}, - {0xf3, 0x0c, 0xeb, 0x2b, 0xb2, 0x82, 0x9e, 0x79, 0xe4, 0xca, 0x97, 0x53, 0xd3, 0x5a, 0x8e, 0xcc, 0x00, 0x26, 0x2d, 0x16, 0x4c, 0xc0, 0x77, 0x08, 0x02, 0x95, 0x38, 0x1c, 0xbd, 0x64, 0x3f, 0x0d}, - {0x68, 0x19, 0xd9, 0x15, 0xc7, 0x3f, 0x4d, 0x1e, 0x77, 0xe4, 0xe1, 0xb5, 0x2d, 0x1f, 0xa0, 0xf9, 0xcf, 0x9b, 0xea, 0xea, 0xd3, 0x93, 0x9f, 0x15, 0x87, 0x4b, 0xd9, 0x88, 0xe2, 0xa2, 0x36, 0x30}, - {0x24, 0x8d, 0x6a, 0x61, 0xd2, 0x06, 0x38, 0xb8, 0xe5, 0xc0, 0x26, 0x93, 0x0c, 0x3e, 0x60, 0x39, 0xa3, 0x3c, 0xe4, 0x59, 0x64, 0xff, 0x21, 0x67, 0xf6, 0xec, 0xed, 0xd4, 0x19, 0xdb, 0x06, 0xc1}, - {0xf0, 0x8a, 0x78, 0xcb, 0xba, 0xee, 0x08, 0x2b, 0x05, 0x2a, 0xe0, 0x70, 0x8f, 0x32, 0xfa, 0x1e, 0x50, 0xc5, 0xc4, 0x21, 0xaa, 0x77, 0x2b, 0xa5, 0xdb, 0xb4, 0x06, 0xa2, 0xea, 0x6b, 0xe3, 0x42}, - {0xab, 0x64, 0xef, 0xf7, 0xe8, 0x8e, 0x2e, 0x46, 0x16, 0x5e, 0x29, 0xf2, 0xbc, 0xe4, 0x18, 0x26, 0xbd, 0x4c, 0x7b, 0x35, 0x52, 0xf6, 0xb3, 0x82, 0xa9, 0xe7, 0xd3, 0xaf, 0x47, 0xc2, 0x45, 0xf8} - }; - int i; - for (i = 0; i < 8; i++) { - unsigned char out[32]; - secp256k1_sha256_t hasher; - secp256k1_sha256_initialize(&hasher); - secp256k1_sha256_write(&hasher, (const unsigned char*)(inputs[i]), strlen(inputs[i])); - secp256k1_sha256_finalize(&hasher, out); - CHECK(memcmp(out, outputs[i], 32) == 0); - if (strlen(inputs[i]) > 0) { - int split = secp256k1_rand32() % strlen(inputs[i]); - secp256k1_sha256_initialize(&hasher); - secp256k1_sha256_write(&hasher, (const unsigned char*)(inputs[i]), split); - secp256k1_sha256_write(&hasher, (const unsigned char*)(inputs[i] + split), strlen(inputs[i]) - split); - secp256k1_sha256_finalize(&hasher, out); - CHECK(memcmp(out, outputs[i], 32) == 0); - } - } -} - -void run_hmac_sha256_tests(void) { - static const char *keys[6] = { - "\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b", - "\x4a\x65\x66\x65", - "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa", - "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19", - "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa", - "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" - }; - static const char *inputs[6] = { - "\x48\x69\x20\x54\x68\x65\x72\x65", - "\x77\x68\x61\x74\x20\x64\x6f\x20\x79\x61\x20\x77\x61\x6e\x74\x20\x66\x6f\x72\x20\x6e\x6f\x74\x68\x69\x6e\x67\x3f", - "\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd", - "\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd", - "\x54\x65\x73\x74\x20\x55\x73\x69\x6e\x67\x20\x4c\x61\x72\x67\x65\x72\x20\x54\x68\x61\x6e\x20\x42\x6c\x6f\x63\x6b\x2d\x53\x69\x7a\x65\x20\x4b\x65\x79\x20\x2d\x20\x48\x61\x73\x68\x20\x4b\x65\x79\x20\x46\x69\x72\x73\x74", - "\x54\x68\x69\x73\x20\x69\x73\x20\x61\x20\x74\x65\x73\x74\x20\x75\x73\x69\x6e\x67\x20\x61\x20\x6c\x61\x72\x67\x65\x72\x20\x74\x68\x61\x6e\x20\x62\x6c\x6f\x63\x6b\x2d\x73\x69\x7a\x65\x20\x6b\x65\x79\x20\x61\x6e\x64\x20\x61\x20\x6c\x61\x72\x67\x65\x72\x20\x74\x68\x61\x6e\x20\x62\x6c\x6f\x63\x6b\x2d\x73\x69\x7a\x65\x20\x64\x61\x74\x61\x2e\x20\x54\x68\x65\x20\x6b\x65\x79\x20\x6e\x65\x65\x64\x73\x20\x74\x6f\x20\x62\x65\x20\x68\x61\x73\x68\x65\x64\x20\x62\x65\x66\x6f\x72\x65\x20\x62\x65\x69\x6e\x67\x20\x75\x73\x65\x64\x20\x62\x79\x20\x74\x68\x65\x20\x48\x4d\x41\x43\x20\x61\x6c\x67\x6f\x72\x69\x74\x68\x6d\x2e" - }; - static const unsigned char outputs[6][32] = { - {0xb0, 0x34, 0x4c, 0x61, 0xd8, 0xdb, 0x38, 0x53, 0x5c, 0xa8, 0xaf, 0xce, 0xaf, 0x0b, 0xf1, 0x2b, 0x88, 0x1d, 0xc2, 0x00, 0xc9, 0x83, 0x3d, 0xa7, 0x26, 0xe9, 0x37, 0x6c, 0x2e, 0x32, 0xcf, 0xf7}, - {0x5b, 0xdc, 0xc1, 0x46, 0xbf, 0x60, 0x75, 0x4e, 0x6a, 0x04, 0x24, 0x26, 0x08, 0x95, 0x75, 0xc7, 0x5a, 0x00, 0x3f, 0x08, 0x9d, 0x27, 0x39, 0x83, 0x9d, 0xec, 0x58, 0xb9, 0x64, 0xec, 0x38, 0x43}, - {0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8, 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8, 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe}, - {0x82, 0x55, 0x8a, 0x38, 0x9a, 0x44, 0x3c, 0x0e, 0xa4, 0xcc, 0x81, 0x98, 0x99, 0xf2, 0x08, 0x3a, 0x85, 0xf0, 0xfa, 0xa3, 0xe5, 0x78, 0xf8, 0x07, 0x7a, 0x2e, 0x3f, 0xf4, 0x67, 0x29, 0x66, 0x5b}, - {0x60, 0xe4, 0x31, 0x59, 0x1e, 0xe0, 0xb6, 0x7f, 0x0d, 0x8a, 0x26, 0xaa, 0xcb, 0xf5, 0xb7, 0x7f, 0x8e, 0x0b, 0xc6, 0x21, 0x37, 0x28, 0xc5, 0x14, 0x05, 0x46, 0x04, 0x0f, 0x0e, 0xe3, 0x7f, 0x54}, - {0x9b, 0x09, 0xff, 0xa7, 0x1b, 0x94, 0x2f, 0xcb, 0x27, 0x63, 0x5f, 0xbc, 0xd5, 0xb0, 0xe9, 0x44, 0xbf, 0xdc, 0x63, 0x64, 0x4f, 0x07, 0x13, 0x93, 0x8a, 0x7f, 0x51, 0x53, 0x5c, 0x3a, 0x35, 0xe2} - }; - int i; - for (i = 0; i < 6; i++) { - secp256k1_hmac_sha256_t hasher; - unsigned char out[32]; - secp256k1_hmac_sha256_initialize(&hasher, (const unsigned char*)(keys[i]), strlen(keys[i])); - secp256k1_hmac_sha256_write(&hasher, (const unsigned char*)(inputs[i]), strlen(inputs[i])); - secp256k1_hmac_sha256_finalize(&hasher, out); - CHECK(memcmp(out, outputs[i], 32) == 0); - if (strlen(inputs[i]) > 0) { - int split = secp256k1_rand32() % strlen(inputs[i]); - secp256k1_hmac_sha256_initialize(&hasher, (const unsigned char*)(keys[i]), strlen(keys[i])); - secp256k1_hmac_sha256_write(&hasher, (const unsigned char*)(inputs[i]), split); - secp256k1_hmac_sha256_write(&hasher, (const unsigned char*)(inputs[i] + split), strlen(inputs[i]) - split); - secp256k1_hmac_sha256_finalize(&hasher, out); - CHECK(memcmp(out, outputs[i], 32) == 0); - } - } -} - -void run_rfc6979_hmac_sha256_tests(void) { - static const unsigned char key1[32] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x00}; - static const unsigned char msg1[32] = {0x4b, 0xf5, 0x12, 0x2f, 0x34, 0x45, 0x54, 0xc5, 0x3b, 0xde, 0x2e, 0xbb, 0x8c, 0xd2, 0xb7, 0xe3, 0xd1, 0x60, 0x0a, 0xd6, 0x31, 0xc3, 0x85, 0xa5, 0xd7, 0xcc, 0xe2, 0x3c, 0x77, 0x85, 0x45, 0x9a}; - static const unsigned char out1[3][32] = { - {0x4f, 0xe2, 0x95, 0x25, 0xb2, 0x08, 0x68, 0x09, 0x15, 0x9a, 0xcd, 0xf0, 0x50, 0x6e, 0xfb, 0x86, 0xb0, 0xec, 0x93, 0x2c, 0x7b, 0xa4, 0x42, 0x56, 0xab, 0x32, 0x1e, 0x42, 0x1e, 0x67, 0xe9, 0xfb}, - {0x2b, 0xf0, 0xff, 0xf1, 0xd3, 0xc3, 0x78, 0xa2, 0x2d, 0xc5, 0xde, 0x1d, 0x85, 0x65, 0x22, 0x32, 0x5c, 0x65, 0xb5, 0x04, 0x49, 0x1a, 0x0c, 0xbd, 0x01, 0xcb, 0x8f, 0x3a, 0xa6, 0x7f, 0xfd, 0x4a}, - {0xf5, 0x28, 0xb4, 0x10, 0xcb, 0x54, 0x1f, 0x77, 0x00, 0x0d, 0x7a, 0xfb, 0x6c, 0x5b, 0x53, 0xc5, 0xc4, 0x71, 0xea, 0xb4, 0x3e, 0x46, 0x6d, 0x9a, 0xc5, 0x19, 0x0c, 0x39, 0xc8, 0x2f, 0xd8, 0x2e} - }; - - static const unsigned char key2[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, 0xff, 0xff, 0xff, 0xff, 0xff}; - static const unsigned char msg2[32] = {0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, 0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55}; - static const unsigned char out2[3][32] = { - {0x9c, 0x23, 0x6c, 0x16, 0x5b, 0x82, 0xae, 0x0c, 0xd5, 0x90, 0x65, 0x9e, 0x10, 0x0b, 0x6b, 0xab, 0x30, 0x36, 0xe7, 0xba, 0x8b, 0x06, 0x74, 0x9b, 0xaf, 0x69, 0x81, 0xe1, 0x6f, 0x1a, 0x2b, 0x95}, - {0xdf, 0x47, 0x10, 0x61, 0x62, 0x5b, 0xc0, 0xea, 0x14, 0xb6, 0x82, 0xfe, 0xee, 0x2c, 0x9c, 0x02, 0xf2, 0x35, 0xda, 0x04, 0x20, 0x4c, 0x1d, 0x62, 0xa1, 0x53, 0x6c, 0x6e, 0x17, 0xae, 0xd7, 0xa9}, - {0x75, 0x97, 0x88, 0x7c, 0xbd, 0x76, 0x32, 0x1f, 0x32, 0xe3, 0x04, 0x40, 0x67, 0x9a, 0x22, 0xcf, 0x7f, 0x8d, 0x9d, 0x2e, 0xac, 0x39, 0x0e, 0x58, 0x1f, 0xea, 0x09, 0x1c, 0xe2, 0x02, 0xba, 0x94} - }; - - secp256k1_rfc6979_hmac_sha256_t rng; - unsigned char out[32]; - unsigned char zero[1] = {0}; - int i; - - secp256k1_rfc6979_hmac_sha256_initialize(&rng, key1, 32, msg1, 32, NULL, 1); - for (i = 0; i < 3; i++) { - secp256k1_rfc6979_hmac_sha256_generate(&rng, out, 32); - CHECK(memcmp(out, out1[i], 32) == 0); - } - secp256k1_rfc6979_hmac_sha256_finalize(&rng); - - secp256k1_rfc6979_hmac_sha256_initialize(&rng, key1, 32, msg1, 32, zero, 1); - for (i = 0; i < 3; i++) { - secp256k1_rfc6979_hmac_sha256_generate(&rng, out, 32); - CHECK(memcmp(out, out1[i], 32) != 0); - } - secp256k1_rfc6979_hmac_sha256_finalize(&rng); - - secp256k1_rfc6979_hmac_sha256_initialize(&rng, key2, 32, msg2, 32, zero, 0); - for (i = 0; i < 3; i++) { - secp256k1_rfc6979_hmac_sha256_generate(&rng, out, 32); - CHECK(memcmp(out, out2[i], 32) == 0); - } - secp256k1_rfc6979_hmac_sha256_finalize(&rng); -} - -/***** NUM TESTS *****/ - -#ifndef USE_NUM_NONE -void random_num_negate(secp256k1_num_t *num) { - if (secp256k1_rand32() & 1) { - secp256k1_num_negate(num); - } -} - -void random_num_order_test(secp256k1_num_t *num) { - secp256k1_scalar_t sc; - random_scalar_order_test(&sc); - secp256k1_scalar_get_num(num, &sc); -} - -void random_num_order(secp256k1_num_t *num) { - secp256k1_scalar_t sc; - random_scalar_order(&sc); - secp256k1_scalar_get_num(num, &sc); -} - -void test_num_negate(void) { - secp256k1_num_t n1; - secp256k1_num_t n2; - random_num_order_test(&n1); /* n1 = R */ - random_num_negate(&n1); - secp256k1_num_copy(&n2, &n1); /* n2 = R */ - secp256k1_num_sub(&n1, &n2, &n1); /* n1 = n2-n1 = 0 */ - CHECK(secp256k1_num_is_zero(&n1)); - secp256k1_num_copy(&n1, &n2); /* n1 = R */ - secp256k1_num_negate(&n1); /* n1 = -R */ - CHECK(!secp256k1_num_is_zero(&n1)); - secp256k1_num_add(&n1, &n2, &n1); /* n1 = n2+n1 = 0 */ - CHECK(secp256k1_num_is_zero(&n1)); - secp256k1_num_copy(&n1, &n2); /* n1 = R */ - secp256k1_num_negate(&n1); /* n1 = -R */ - CHECK(secp256k1_num_is_neg(&n1) != secp256k1_num_is_neg(&n2)); - secp256k1_num_negate(&n1); /* n1 = R */ - CHECK(secp256k1_num_eq(&n1, &n2)); -} - -void test_num_add_sub(void) { - secp256k1_num_t n1; - secp256k1_num_t n2; - secp256k1_num_t n1p2, n2p1, n1m2, n2m1; - int r = secp256k1_rand32(); - random_num_order_test(&n1); /* n1 = R1 */ - if (r & 1) { - random_num_negate(&n1); - } - random_num_order_test(&n2); /* n2 = R2 */ - if (r & 2) { - random_num_negate(&n2); - } - secp256k1_num_add(&n1p2, &n1, &n2); /* n1p2 = R1 + R2 */ - secp256k1_num_add(&n2p1, &n2, &n1); /* n2p1 = R2 + R1 */ - secp256k1_num_sub(&n1m2, &n1, &n2); /* n1m2 = R1 - R2 */ - secp256k1_num_sub(&n2m1, &n2, &n1); /* n2m1 = R2 - R1 */ - CHECK(secp256k1_num_eq(&n1p2, &n2p1)); - CHECK(!secp256k1_num_eq(&n1p2, &n1m2)); - secp256k1_num_negate(&n2m1); /* n2m1 = -R2 + R1 */ - CHECK(secp256k1_num_eq(&n2m1, &n1m2)); - CHECK(!secp256k1_num_eq(&n2m1, &n1)); - secp256k1_num_add(&n2m1, &n2m1, &n2); /* n2m1 = -R2 + R1 + R2 = R1 */ - CHECK(secp256k1_num_eq(&n2m1, &n1)); - CHECK(!secp256k1_num_eq(&n2p1, &n1)); - secp256k1_num_sub(&n2p1, &n2p1, &n2); /* n2p1 = R2 + R1 - R2 = R1 */ - CHECK(secp256k1_num_eq(&n2p1, &n1)); -} - -void run_num_smalltests(void) { - int i; - for (i = 0; i < 100*count; i++) { - test_num_negate(); - test_num_add_sub(); - } -} -#endif - -/***** SCALAR TESTS *****/ - -void scalar_test(void) { - secp256k1_scalar_t s; - secp256k1_scalar_t s1; - secp256k1_scalar_t s2; -#ifndef USE_NUM_NONE - secp256k1_num_t snum, s1num, s2num; - secp256k1_num_t order, half_order; -#endif - unsigned char c[32]; - - /* Set 's' to a random scalar, with value 'snum'. */ - random_scalar_order_test(&s); - - /* Set 's1' to a random scalar, with value 's1num'. */ - random_scalar_order_test(&s1); - - /* Set 's2' to a random scalar, with value 'snum2', and byte array representation 'c'. */ - random_scalar_order_test(&s2); - secp256k1_scalar_get_b32(c, &s2); - -#ifndef USE_NUM_NONE - secp256k1_scalar_get_num(&snum, &s); - secp256k1_scalar_get_num(&s1num, &s1); - secp256k1_scalar_get_num(&s2num, &s2); - - secp256k1_scalar_order_get_num(&order); - half_order = order; - secp256k1_num_shift(&half_order, 1); -#endif - - { - int i; - /* Test that fetching groups of 4 bits from a scalar and recursing n(i)=16*n(i-1)+p(i) reconstructs it. */ - secp256k1_scalar_t n; - secp256k1_scalar_set_int(&n, 0); - for (i = 0; i < 256; i += 4) { - secp256k1_scalar_t t; - int j; - secp256k1_scalar_set_int(&t, secp256k1_scalar_get_bits(&s, 256 - 4 - i, 4)); - for (j = 0; j < 4; j++) { - secp256k1_scalar_add(&n, &n, &n); - } - secp256k1_scalar_add(&n, &n, &t); - } - CHECK(secp256k1_scalar_eq(&n, &s)); - } - - { - /* Test that fetching groups of randomly-sized bits from a scalar and recursing n(i)=b*n(i-1)+p(i) reconstructs it. */ - secp256k1_scalar_t n; - int i = 0; - secp256k1_scalar_set_int(&n, 0); - while (i < 256) { - secp256k1_scalar_t t; - int j; - int now = (secp256k1_rand32() % 15) + 1; - if (now + i > 256) { - now = 256 - i; - } - secp256k1_scalar_set_int(&t, secp256k1_scalar_get_bits_var(&s, 256 - now - i, now)); - for (j = 0; j < now; j++) { - secp256k1_scalar_add(&n, &n, &n); - } - secp256k1_scalar_add(&n, &n, &t); - i += now; - } - CHECK(secp256k1_scalar_eq(&n, &s)); - } - -#ifndef USE_NUM_NONE - { - /* Test that adding the scalars together is equal to adding their numbers together modulo the order. */ - secp256k1_num_t rnum; - secp256k1_num_t r2num; - secp256k1_scalar_t r; - secp256k1_num_add(&rnum, &snum, &s2num); - secp256k1_num_mod(&rnum, &order); - secp256k1_scalar_add(&r, &s, &s2); - secp256k1_scalar_get_num(&r2num, &r); - CHECK(secp256k1_num_eq(&rnum, &r2num)); - } - - { - /* Test that multipying the scalars is equal to multiplying their numbers modulo the order. */ - secp256k1_scalar_t r; - secp256k1_num_t r2num; - secp256k1_num_t rnum; - secp256k1_num_mul(&rnum, &snum, &s2num); - secp256k1_num_mod(&rnum, &order); - secp256k1_scalar_mul(&r, &s, &s2); - secp256k1_scalar_get_num(&r2num, &r); - CHECK(secp256k1_num_eq(&rnum, &r2num)); - /* The result can only be zero if at least one of the factors was zero. */ - CHECK(secp256k1_scalar_is_zero(&r) == (secp256k1_scalar_is_zero(&s) || secp256k1_scalar_is_zero(&s2))); - /* The results can only be equal to one of the factors if that factor was zero, or the other factor was one. */ - CHECK(secp256k1_num_eq(&rnum, &snum) == (secp256k1_scalar_is_zero(&s) || secp256k1_scalar_is_one(&s2))); - CHECK(secp256k1_num_eq(&rnum, &s2num) == (secp256k1_scalar_is_zero(&s2) || secp256k1_scalar_is_one(&s))); - } - - { - secp256k1_scalar_t neg; - secp256k1_num_t negnum; - secp256k1_num_t negnum2; - /* Check that comparison with zero matches comparison with zero on the number. */ - CHECK(secp256k1_num_is_zero(&snum) == secp256k1_scalar_is_zero(&s)); - /* Check that comparison with the half order is equal to testing for high scalar. */ - CHECK(secp256k1_scalar_is_high(&s) == (secp256k1_num_cmp(&snum, &half_order) > 0)); - secp256k1_scalar_negate(&neg, &s); - secp256k1_num_sub(&negnum, &order, &snum); - secp256k1_num_mod(&negnum, &order); - /* Check that comparison with the half order is equal to testing for high scalar after negation. */ - CHECK(secp256k1_scalar_is_high(&neg) == (secp256k1_num_cmp(&negnum, &half_order) > 0)); - /* Negating should change the high property, unless the value was already zero. */ - CHECK((secp256k1_scalar_is_high(&s) == secp256k1_scalar_is_high(&neg)) == secp256k1_scalar_is_zero(&s)); - secp256k1_scalar_get_num(&negnum2, &neg); - /* Negating a scalar should be equal to (order - n) mod order on the number. */ - CHECK(secp256k1_num_eq(&negnum, &negnum2)); - secp256k1_scalar_add(&neg, &neg, &s); - /* Adding a number to its negation should result in zero. */ - CHECK(secp256k1_scalar_is_zero(&neg)); - secp256k1_scalar_negate(&neg, &neg); - /* Negating zero should still result in zero. */ - CHECK(secp256k1_scalar_is_zero(&neg)); - } - - { - /* Test secp256k1_scalar_mul_shift_var. */ - secp256k1_scalar_t r; - secp256k1_num_t one; - secp256k1_num_t rnum; - secp256k1_num_t rnum2; - unsigned char cone[1] = {0x01}; - unsigned int shift = 256 + (secp256k1_rand32() % 257); - secp256k1_scalar_mul_shift_var(&r, &s1, &s2, shift); - secp256k1_num_mul(&rnum, &s1num, &s2num); - secp256k1_num_shift(&rnum, shift - 1); - secp256k1_num_set_bin(&one, cone, 1); - secp256k1_num_add(&rnum, &rnum, &one); - secp256k1_num_shift(&rnum, 1); - secp256k1_scalar_get_num(&rnum2, &r); - CHECK(secp256k1_num_eq(&rnum, &rnum2)); - } -#endif - - { - /* Test that scalar inverses are equal to the inverse of their number modulo the order. */ - if (!secp256k1_scalar_is_zero(&s)) { - secp256k1_scalar_t inv; -#ifndef USE_NUM_NONE - secp256k1_num_t invnum; - secp256k1_num_t invnum2; -#endif - secp256k1_scalar_inverse(&inv, &s); -#ifndef USE_NUM_NONE - secp256k1_num_mod_inverse(&invnum, &snum, &order); - secp256k1_scalar_get_num(&invnum2, &inv); - CHECK(secp256k1_num_eq(&invnum, &invnum2)); -#endif - secp256k1_scalar_mul(&inv, &inv, &s); - /* Multiplying a scalar with its inverse must result in one. */ - CHECK(secp256k1_scalar_is_one(&inv)); - secp256k1_scalar_inverse(&inv, &inv); - /* Inverting one must result in one. */ - CHECK(secp256k1_scalar_is_one(&inv)); - } - } - - { - /* Test commutativity of add. */ - secp256k1_scalar_t r1, r2; - secp256k1_scalar_add(&r1, &s1, &s2); - secp256k1_scalar_add(&r2, &s2, &s1); - CHECK(secp256k1_scalar_eq(&r1, &r2)); - } - - { - secp256k1_scalar_t r1, r2; - secp256k1_scalar_t b; - int i; - /* Test add_bit. */ - int bit = secp256k1_rand32() % 256; - secp256k1_scalar_set_int(&b, 1); - CHECK(secp256k1_scalar_is_one(&b)); - for (i = 0; i < bit; i++) { - secp256k1_scalar_add(&b, &b, &b); - } - r1 = s1; - r2 = s1; - if (!secp256k1_scalar_add(&r1, &r1, &b)) { - /* No overflow happened. */ - secp256k1_scalar_add_bit(&r2, bit); - CHECK(secp256k1_scalar_eq(&r1, &r2)); - } - } - - { - /* Test commutativity of mul. */ - secp256k1_scalar_t r1, r2; - secp256k1_scalar_mul(&r1, &s1, &s2); - secp256k1_scalar_mul(&r2, &s2, &s1); - CHECK(secp256k1_scalar_eq(&r1, &r2)); - } - - { - /* Test associativity of add. */ - secp256k1_scalar_t r1, r2; - secp256k1_scalar_add(&r1, &s1, &s2); - secp256k1_scalar_add(&r1, &r1, &s); - secp256k1_scalar_add(&r2, &s2, &s); - secp256k1_scalar_add(&r2, &s1, &r2); - CHECK(secp256k1_scalar_eq(&r1, &r2)); - } - - { - /* Test associativity of mul. */ - secp256k1_scalar_t r1, r2; - secp256k1_scalar_mul(&r1, &s1, &s2); - secp256k1_scalar_mul(&r1, &r1, &s); - secp256k1_scalar_mul(&r2, &s2, &s); - secp256k1_scalar_mul(&r2, &s1, &r2); - CHECK(secp256k1_scalar_eq(&r1, &r2)); - } - - { - /* Test distributitivity of mul over add. */ - secp256k1_scalar_t r1, r2, t; - secp256k1_scalar_add(&r1, &s1, &s2); - secp256k1_scalar_mul(&r1, &r1, &s); - secp256k1_scalar_mul(&r2, &s1, &s); - secp256k1_scalar_mul(&t, &s2, &s); - secp256k1_scalar_add(&r2, &r2, &t); - CHECK(secp256k1_scalar_eq(&r1, &r2)); - } - - { - /* Test square. */ - secp256k1_scalar_t r1, r2; - secp256k1_scalar_sqr(&r1, &s1); - secp256k1_scalar_mul(&r2, &s1, &s1); - CHECK(secp256k1_scalar_eq(&r1, &r2)); - } - - { - /* Test multiplicative identity. */ - secp256k1_scalar_t r1, v1; - secp256k1_scalar_set_int(&v1,1); - secp256k1_scalar_mul(&r1, &s1, &v1); - CHECK(secp256k1_scalar_eq(&r1, &s1)); - } - - { - /* Test additive identity. */ - secp256k1_scalar_t r1, v0; - secp256k1_scalar_set_int(&v0,0); - secp256k1_scalar_add(&r1, &s1, &v0); - CHECK(secp256k1_scalar_eq(&r1, &s1)); - } - - { - /* Test zero product property. */ - secp256k1_scalar_t r1, v0; - secp256k1_scalar_set_int(&v0,0); - secp256k1_scalar_mul(&r1, &s1, &v0); - CHECK(secp256k1_scalar_eq(&r1, &v0)); - } - -} - -void run_scalar_tests(void) { - int i; - for (i = 0; i < 128 * count; i++) { - scalar_test(); - } - - { - /* (-1)+1 should be zero. */ - secp256k1_scalar_t s, o; - secp256k1_scalar_set_int(&s, 1); - CHECK(secp256k1_scalar_is_one(&s)); - secp256k1_scalar_negate(&o, &s); - secp256k1_scalar_add(&o, &o, &s); - CHECK(secp256k1_scalar_is_zero(&o)); - secp256k1_scalar_negate(&o, &o); - CHECK(secp256k1_scalar_is_zero(&o)); - } - -#ifndef USE_NUM_NONE - { - /* A scalar with value of the curve order should be 0. */ - secp256k1_num_t order; - secp256k1_scalar_t zero; - unsigned char bin[32]; - int overflow = 0; - secp256k1_scalar_order_get_num(&order); - secp256k1_num_get_bin(bin, 32, &order); - secp256k1_scalar_set_b32(&zero, bin, &overflow); - CHECK(overflow == 1); - CHECK(secp256k1_scalar_is_zero(&zero)); - } -#endif -} - -/***** FIELD TESTS *****/ - -void random_fe(secp256k1_fe_t *x) { - unsigned char bin[32]; - do { - secp256k1_rand256(bin); - if (secp256k1_fe_set_b32(x, bin)) { - return; - } - } while(1); -} - -void random_fe_non_zero(secp256k1_fe_t *nz) { - int tries = 10; - while (--tries >= 0) { - random_fe(nz); - secp256k1_fe_normalize(nz); - if (!secp256k1_fe_is_zero(nz)) { - break; - } - } - /* Infinitesimal probability of spurious failure here */ - CHECK(tries >= 0); -} - -void random_fe_non_square(secp256k1_fe_t *ns) { - secp256k1_fe_t r; - random_fe_non_zero(ns); - if (secp256k1_fe_sqrt_var(&r, ns)) { - secp256k1_fe_negate(ns, ns, 1); - } -} - -int check_fe_equal(const secp256k1_fe_t *a, const secp256k1_fe_t *b) { - secp256k1_fe_t an = *a; - secp256k1_fe_t bn = *b; - secp256k1_fe_normalize_weak(&an); - secp256k1_fe_normalize_var(&bn); - return secp256k1_fe_equal_var(&an, &bn); -} - -int check_fe_inverse(const secp256k1_fe_t *a, const secp256k1_fe_t *ai) { - secp256k1_fe_t x; - secp256k1_fe_t one = SECP256K1_FE_CONST(0, 0, 0, 0, 0, 0, 0, 1); - secp256k1_fe_mul(&x, a, ai); - return check_fe_equal(&x, &one); -} - -void run_field_convert(void) { - static const unsigned char b32[32] = { - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, - 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, - 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, - 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x40 - }; - static const secp256k1_fe_storage_t fes = SECP256K1_FE_STORAGE_CONST( - 0x00010203UL, 0x04050607UL, 0x11121314UL, 0x15161718UL, - 0x22232425UL, 0x26272829UL, 0x33343536UL, 0x37383940UL - ); - static const secp256k1_fe_t fe = SECP256K1_FE_CONST( - 0x00010203UL, 0x04050607UL, 0x11121314UL, 0x15161718UL, - 0x22232425UL, 0x26272829UL, 0x33343536UL, 0x37383940UL - ); - secp256k1_fe_t fe2; - unsigned char b322[32]; - secp256k1_fe_storage_t fes2; - /* Check conversions to fe. */ - CHECK(secp256k1_fe_set_b32(&fe2, b32)); - CHECK(secp256k1_fe_equal_var(&fe, &fe2)); - secp256k1_fe_from_storage(&fe2, &fes); - CHECK(secp256k1_fe_equal_var(&fe, &fe2)); - /* Check conversion from fe. */ - secp256k1_fe_get_b32(b322, &fe); - CHECK(memcmp(b322, b32, 32) == 0); - secp256k1_fe_to_storage(&fes2, &fe); - CHECK(memcmp(&fes2, &fes, sizeof(fes)) == 0); -} - -void run_field_misc(void) { - secp256k1_fe_t x; - secp256k1_fe_t y; - secp256k1_fe_t z; - secp256k1_fe_t q; - secp256k1_fe_t fe5 = SECP256K1_FE_CONST(0, 0, 0, 0, 0, 0, 0, 5); - int i; - for (i = 0; i < 5*count; i++) { - secp256k1_fe_storage_t xs, ys, zs; - random_fe(&x); - random_fe_non_zero(&y); - /* Test the fe equality and comparison operations. */ - CHECK(secp256k1_fe_cmp_var(&x, &x) == 0); - CHECK(secp256k1_fe_equal_var(&x, &x)); - z = x; - secp256k1_fe_add(&z,&y); - secp256k1_fe_normalize(&z); - /* Test storage conversion and conditional moves. */ - secp256k1_fe_to_storage(&xs, &x); - secp256k1_fe_to_storage(&ys, &y); - secp256k1_fe_to_storage(&zs, &z); - secp256k1_fe_storage_cmov(&zs, &xs, 0); - CHECK(memcmp(&xs, &zs, sizeof(xs)) != 0); - secp256k1_fe_storage_cmov(&ys, &xs, 1); - CHECK(memcmp(&xs, &ys, sizeof(xs)) == 0); - secp256k1_fe_from_storage(&x, &xs); - secp256k1_fe_from_storage(&y, &ys); - secp256k1_fe_from_storage(&z, &zs); - /* Test that mul_int, mul, and add agree. */ - secp256k1_fe_add(&y, &x); - secp256k1_fe_add(&y, &x); - z = x; - secp256k1_fe_mul_int(&z, 3); - CHECK(check_fe_equal(&y, &z)); - secp256k1_fe_add(&y, &x); - secp256k1_fe_add(&z, &x); - CHECK(check_fe_equal(&z, &y)); - z = x; - secp256k1_fe_mul_int(&z, 5); - secp256k1_fe_mul(&q, &x, &fe5); - CHECK(check_fe_equal(&z, &q)); - secp256k1_fe_negate(&x, &x, 1); - secp256k1_fe_add(&z, &x); - secp256k1_fe_add(&q, &x); - CHECK(check_fe_equal(&y, &z)); - CHECK(check_fe_equal(&q, &y)); - } -} - -void run_field_inv(void) { - secp256k1_fe_t x, xi, xii; - int i; - for (i = 0; i < 10*count; i++) { - random_fe_non_zero(&x); - secp256k1_fe_inv(&xi, &x); - CHECK(check_fe_inverse(&x, &xi)); - secp256k1_fe_inv(&xii, &xi); - CHECK(check_fe_equal(&x, &xii)); - } -} - -void run_field_inv_var(void) { - secp256k1_fe_t x, xi, xii; - int i; - for (i = 0; i < 10*count; i++) { - random_fe_non_zero(&x); - secp256k1_fe_inv_var(&xi, &x); - CHECK(check_fe_inverse(&x, &xi)); - secp256k1_fe_inv_var(&xii, &xi); - CHECK(check_fe_equal(&x, &xii)); - } -} - -void run_field_inv_all_var(void) { - secp256k1_fe_t x[16], xi[16], xii[16]; - int i; - /* Check it's safe to call for 0 elements */ - secp256k1_fe_inv_all_var(0, xi, x); - for (i = 0; i < count; i++) { - size_t j; - size_t len = (secp256k1_rand32() & 15) + 1; - for (j = 0; j < len; j++) { - random_fe_non_zero(&x[j]); - } - secp256k1_fe_inv_all_var(len, xi, x); - for (j = 0; j < len; j++) { - CHECK(check_fe_inverse(&x[j], &xi[j])); - } - secp256k1_fe_inv_all_var(len, xii, xi); - for (j = 0; j < len; j++) { - CHECK(check_fe_equal(&x[j], &xii[j])); - } - } -} - -void run_sqr(void) { - secp256k1_fe_t x, s; - - { - int i; - secp256k1_fe_set_int(&x, 1); - secp256k1_fe_negate(&x, &x, 1); - - for (i = 1; i <= 512; ++i) { - secp256k1_fe_mul_int(&x, 2); - secp256k1_fe_normalize(&x); - secp256k1_fe_sqr(&s, &x); - } - } -} - -void test_sqrt(const secp256k1_fe_t *a, const secp256k1_fe_t *k) { - secp256k1_fe_t r1, r2; - int v = secp256k1_fe_sqrt_var(&r1, a); - CHECK((v == 0) == (k == NULL)); - - if (k != NULL) { - /* Check that the returned root is +/- the given known answer */ - secp256k1_fe_negate(&r2, &r1, 1); - secp256k1_fe_add(&r1, k); secp256k1_fe_add(&r2, k); - secp256k1_fe_normalize(&r1); secp256k1_fe_normalize(&r2); - CHECK(secp256k1_fe_is_zero(&r1) || secp256k1_fe_is_zero(&r2)); - } -} - -void run_sqrt(void) { - secp256k1_fe_t ns, x, s, t; - int i; - - /* Check sqrt(0) is 0 */ - secp256k1_fe_set_int(&x, 0); - secp256k1_fe_sqr(&s, &x); - test_sqrt(&s, &x); - - /* Check sqrt of small squares (and their negatives) */ - for (i = 1; i <= 100; i++) { - secp256k1_fe_set_int(&x, i); - secp256k1_fe_sqr(&s, &x); - test_sqrt(&s, &x); - secp256k1_fe_negate(&t, &s, 1); - test_sqrt(&t, NULL); - } - - /* Consistency checks for large random values */ - for (i = 0; i < 10; i++) { - int j; - random_fe_non_square(&ns); - for (j = 0; j < count; j++) { - random_fe(&x); - secp256k1_fe_sqr(&s, &x); - test_sqrt(&s, &x); - secp256k1_fe_negate(&t, &s, 1); - test_sqrt(&t, NULL); - secp256k1_fe_mul(&t, &s, &ns); - test_sqrt(&t, NULL); - } - } -} - -/***** GROUP TESTS *****/ - -void ge_equals_ge(const secp256k1_ge_t *a, const secp256k1_ge_t *b) { - CHECK(a->infinity == b->infinity); - if (a->infinity) { - return; - } - CHECK(secp256k1_fe_equal_var(&a->x, &b->x)); - CHECK(secp256k1_fe_equal_var(&b->y, &b->y)); -} - -void ge_equals_gej(const secp256k1_ge_t *a, const secp256k1_gej_t *b) { - secp256k1_fe_t z2s; - secp256k1_fe_t u1, u2, s1, s2; - CHECK(a->infinity == b->infinity); - if (a->infinity) { - return; - } - /* Check a.x * b.z^2 == b.x && a.y * b.z^3 == b.y, to avoid inverses. */ - secp256k1_fe_sqr(&z2s, &b->z); - secp256k1_fe_mul(&u1, &a->x, &z2s); - u2 = b->x; secp256k1_fe_normalize_weak(&u2); - secp256k1_fe_mul(&s1, &a->y, &z2s); secp256k1_fe_mul(&s1, &s1, &b->z); - s2 = b->y; secp256k1_fe_normalize_weak(&s2); - CHECK(secp256k1_fe_equal_var(&u1, &u2)); - CHECK(secp256k1_fe_equal_var(&s1, &s2)); -} - -void test_ge(void) { - int i, i1; - int runs = 4; - /* Points: (infinity, p1, p1, -p1, -p1, p2, p2, -p2, -p2, p3, p3, -p3, -p3, p4, p4, -p4, -p4). - * The second in each pair of identical points uses a random Z coordinate in the Jacobian form. - * All magnitudes are randomized. - * All 17*17 combinations of points are added to eachother, using all applicable methods. - */ - secp256k1_ge_t *ge = (secp256k1_ge_t *)malloc(sizeof(secp256k1_ge_t) * (1 + 4 * runs)); - secp256k1_gej_t *gej = (secp256k1_gej_t *)malloc(sizeof(secp256k1_gej_t) * (1 + 4 * runs)); - secp256k1_gej_set_infinity(&gej[0]); - secp256k1_ge_clear(&ge[0]); - secp256k1_ge_set_gej_var(&ge[0], &gej[0]); - for (i = 0; i < runs; i++) { - int j; - secp256k1_ge_t g; - random_group_element_test(&g); - ge[1 + 4 * i] = g; - ge[2 + 4 * i] = g; - secp256k1_ge_neg(&ge[3 + 4 * i], &g); - secp256k1_ge_neg(&ge[4 + 4 * i], &g); - secp256k1_gej_set_ge(&gej[1 + 4 * i], &ge[1 + 4 * i]); - random_group_element_jacobian_test(&gej[2 + 4 * i], &ge[2 + 4 * i]); - secp256k1_gej_set_ge(&gej[3 + 4 * i], &ge[3 + 4 * i]); - random_group_element_jacobian_test(&gej[4 + 4 * i], &ge[4 + 4 * i]); - for (j = 0; j < 4; j++) { - random_field_element_magnitude(&ge[1 + j + 4 * i].x); - random_field_element_magnitude(&ge[1 + j + 4 * i].y); - random_field_element_magnitude(&gej[1 + j + 4 * i].x); - random_field_element_magnitude(&gej[1 + j + 4 * i].y); - random_field_element_magnitude(&gej[1 + j + 4 * i].z); - } - } - - for (i1 = 0; i1 < 1 + 4 * runs; i1++) { - int i2; - for (i2 = 0; i2 < 1 + 4 * runs; i2++) { - /* Compute reference result using gej + gej (var). */ - secp256k1_gej_t refj, resj; - secp256k1_ge_t ref; - secp256k1_gej_add_var(&refj, &gej[i1], &gej[i2]); - secp256k1_ge_set_gej_var(&ref, &refj); - - /* Test gej + ge (var). */ - secp256k1_gej_add_ge_var(&resj, &gej[i1], &ge[i2]); - ge_equals_gej(&ref, &resj); - - /* Test gej + ge (const). */ - if (i2 != 0) { - /* secp256k1_gej_add_ge does not support its second argument being infinity. */ - secp256k1_gej_add_ge(&resj, &gej[i1], &ge[i2]); - ge_equals_gej(&ref, &resj); - } - - /* Test doubling (var). */ - if ((i1 == 0 && i2 == 0) || ((i1 + 3)/4 == (i2 + 3)/4 && ((i1 + 3)%4)/2 == ((i2 + 3)%4)/2)) { - /* Normal doubling. */ - secp256k1_gej_double_var(&resj, &gej[i1]); - ge_equals_gej(&ref, &resj); - secp256k1_gej_double_var(&resj, &gej[i2]); - ge_equals_gej(&ref, &resj); - } - - /* Test adding opposites. */ - if ((i1 == 0 && i2 == 0) || ((i1 + 3)/4 == (i2 + 3)/4 && ((i1 + 3)%4)/2 != ((i2 + 3)%4)/2)) { - CHECK(secp256k1_ge_is_infinity(&ref)); - } - - /* Test adding infinity. */ - if (i1 == 0) { - CHECK(secp256k1_ge_is_infinity(&ge[i1])); - CHECK(secp256k1_gej_is_infinity(&gej[i1])); - ge_equals_gej(&ref, &gej[i2]); - } - if (i2 == 0) { - CHECK(secp256k1_ge_is_infinity(&ge[i2])); - CHECK(secp256k1_gej_is_infinity(&gej[i2])); - ge_equals_gej(&ref, &gej[i1]); - } - } - } - - /* Test adding all points together in random order equals infinity. */ - { - secp256k1_gej_t sum = SECP256K1_GEJ_CONST_INFINITY; - secp256k1_gej_t *gej_shuffled = (secp256k1_gej_t *)malloc((4 * runs + 1) * sizeof(secp256k1_gej_t)); - for (i = 0; i < 4 * runs + 1; i++) { - gej_shuffled[i] = gej[i]; - } - for (i = 0; i < 4 * runs + 1; i++) { - int swap = i + secp256k1_rand32() % (4 * runs + 1 - i); - if (swap != i) { - secp256k1_gej_t t = gej_shuffled[i]; - gej_shuffled[i] = gej_shuffled[swap]; - gej_shuffled[swap] = t; - } - } - for (i = 0; i < 4 * runs + 1; i++) { - secp256k1_gej_add_var(&sum, &sum, &gej_shuffled[i]); - } - CHECK(secp256k1_gej_is_infinity(&sum)); - free(gej_shuffled); - } - - /* Test batch gej -> ge conversion. */ - { - secp256k1_ge_t *ge_set_all = (secp256k1_ge_t *)malloc((4 * runs + 1) * sizeof(secp256k1_ge_t)); - secp256k1_ge_set_all_gej_var(4 * runs + 1, ge_set_all, gej); - for (i = 0; i < 4 * runs + 1; i++) { - ge_equals_gej(&ge_set_all[i], &gej[i]); - } - free(ge_set_all); - } - - free(ge); - free(gej); -} - -void run_ge(void) { - int i; - for (i = 0; i < count * 32; i++) { - test_ge(); - } -} - -/***** ECMULT TESTS *****/ - -void run_ecmult_chain(void) { - /* random starting point A (on the curve) */ - secp256k1_gej_t a = SECP256K1_GEJ_CONST( - 0x8b30bbe9, 0xae2a9906, 0x96b22f67, 0x0709dff3, - 0x727fd8bc, 0x04d3362c, 0x6c7bf458, 0xe2846004, - 0xa357ae91, 0x5c4a6528, 0x1309edf2, 0x0504740f, - 0x0eb33439, 0x90216b4f, 0x81063cb6, 0x5f2f7e0f - ); - /* two random initial factors xn and gn */ - secp256k1_scalar_t xn = SECP256K1_SCALAR_CONST( - 0x84cc5452, 0xf7fde1ed, 0xb4d38a8c, 0xe9b1b84c, - 0xcef31f14, 0x6e569be9, 0x705d357a, 0x42985407 - ); - secp256k1_scalar_t gn = SECP256K1_SCALAR_CONST( - 0xa1e58d22, 0x553dcd42, 0xb2398062, 0x5d4c57a9, - 0x6e9323d4, 0x2b3152e5, 0xca2c3990, 0xedc7c9de - ); - /* two small multipliers to be applied to xn and gn in every iteration: */ - static const secp256k1_scalar_t xf = SECP256K1_SCALAR_CONST(0, 0, 0, 0, 0, 0, 0, 0x1337); - static const secp256k1_scalar_t gf = SECP256K1_SCALAR_CONST(0, 0, 0, 0, 0, 0, 0, 0x7113); - /* accumulators with the resulting coefficients to A and G */ - secp256k1_scalar_t ae = SECP256K1_SCALAR_CONST(0, 0, 0, 0, 0, 0, 0, 1); - secp256k1_scalar_t ge = SECP256K1_SCALAR_CONST(0, 0, 0, 0, 0, 0, 0, 0); - /* actual points */ - secp256k1_gej_t x = a; - secp256k1_gej_t x2; - int i; - - /* the point being computed */ - x = a; - for (i = 0; i < 200*count; i++) { - /* in each iteration, compute X = xn*X + gn*G; */ - secp256k1_ecmult(&x, &x, &xn, &gn); - /* also compute ae and ge: the actual accumulated factors for A and G */ - /* if X was (ae*A+ge*G), xn*X + gn*G results in (xn*ae*A + (xn*ge+gn)*G) */ - secp256k1_scalar_mul(&ae, &ae, &xn); - secp256k1_scalar_mul(&ge, &ge, &xn); - secp256k1_scalar_add(&ge, &ge, &gn); - /* modify xn and gn */ - secp256k1_scalar_mul(&xn, &xn, &xf); - secp256k1_scalar_mul(&gn, &gn, &gf); - - /* verify */ - if (i == 19999) { - /* expected result after 19999 iterations */ - secp256k1_gej_t rp = SECP256K1_GEJ_CONST( - 0xD6E96687, 0xF9B10D09, 0x2A6F3543, 0x9D86CEBE, - 0xA4535D0D, 0x409F5358, 0x6440BD74, 0xB933E830, - 0xB95CBCA2, 0xC77DA786, 0x539BE8FD, 0x53354D2D, - 0x3B4F566A, 0xE6580454, 0x07ED6015, 0xEE1B2A88 - ); - - secp256k1_gej_neg(&rp, &rp); - secp256k1_gej_add_var(&rp, &rp, &x); - CHECK(secp256k1_gej_is_infinity(&rp)); - } - } - /* redo the computation, but directly with the resulting ae and ge coefficients: */ - secp256k1_ecmult(&x2, &a, &ae, &ge); - secp256k1_gej_neg(&x2, &x2); - secp256k1_gej_add_var(&x2, &x2, &x); - CHECK(secp256k1_gej_is_infinity(&x2)); -} - -void test_point_times_order(const secp256k1_gej_t *point) { - /* X * (point + G) + (order-X) * (pointer + G) = 0 */ - secp256k1_scalar_t x; - secp256k1_scalar_t nx; - secp256k1_gej_t res1, res2; - secp256k1_ge_t res3; - unsigned char pub[65]; - int psize = 65; - random_scalar_order_test(&x); - secp256k1_scalar_negate(&nx, &x); - secp256k1_ecmult(&res1, point, &x, &x); /* calc res1 = x * point + x * G; */ - secp256k1_ecmult(&res2, point, &nx, &nx); /* calc res2 = (order - x) * point + (order - x) * G; */ - secp256k1_gej_add_var(&res1, &res1, &res2); - CHECK(secp256k1_gej_is_infinity(&res1)); - CHECK(secp256k1_gej_is_valid_var(&res1) == 0); - secp256k1_ge_set_gej(&res3, &res1); - CHECK(secp256k1_ge_is_infinity(&res3)); - CHECK(secp256k1_ge_is_valid_var(&res3) == 0); - CHECK(secp256k1_eckey_pubkey_serialize(&res3, pub, &psize, 0) == 0); - psize = 65; - CHECK(secp256k1_eckey_pubkey_serialize(&res3, pub, &psize, 1) == 0); -} - -void run_point_times_order(void) { - int i; - secp256k1_fe_t x = SECP256K1_FE_CONST(0, 0, 0, 0, 0, 0, 0, 2); - static const secp256k1_fe_t xr = SECP256K1_FE_CONST( - 0x7603CB59, 0xB0EF6C63, 0xFE608479, 0x2A0C378C, - 0xDB3233A8, 0x0F8A9A09, 0xA877DEAD, 0x31B38C45 - ); - for (i = 0; i < 500; i++) { - secp256k1_ge_t p; - if (secp256k1_ge_set_xo_var(&p, &x, 1)) { - secp256k1_gej_t j; - CHECK(secp256k1_ge_is_valid_var(&p)); - secp256k1_gej_set_ge(&j, &p); - CHECK(secp256k1_gej_is_valid_var(&j)); - test_point_times_order(&j); - } - secp256k1_fe_sqr(&x, &x); - } - secp256k1_fe_normalize_var(&x); - CHECK(secp256k1_fe_equal_var(&x, &xr)); -} - -void test_wnaf(const secp256k1_scalar_t *number, int w) { - secp256k1_scalar_t x, two, t; - int wnaf[256]; - int zeroes = -1; - int i; - int bits; - secp256k1_scalar_set_int(&x, 0); - secp256k1_scalar_set_int(&two, 2); - bits = secp256k1_ecmult_wnaf(wnaf, number, w); - CHECK(bits <= 256); - for (i = bits-1; i >= 0; i--) { - int v = wnaf[i]; - secp256k1_scalar_mul(&x, &x, &two); - if (v) { - CHECK(zeroes == -1 || zeroes >= w-1); /* check that distance between non-zero elements is at least w-1 */ - zeroes=0; - CHECK((v & 1) == 1); /* check non-zero elements are odd */ - CHECK(v <= (1 << (w-1)) - 1); /* check range below */ - CHECK(v >= -(1 << (w-1)) - 1); /* check range above */ - } else { - CHECK(zeroes != -1); /* check that no unnecessary zero padding exists */ - zeroes++; - } - if (v >= 0) { - secp256k1_scalar_set_int(&t, v); - } else { - secp256k1_scalar_set_int(&t, -v); - secp256k1_scalar_negate(&t, &t); - } - secp256k1_scalar_add(&x, &x, &t); - } - CHECK(secp256k1_scalar_eq(&x, number)); /* check that wnaf represents number */ -} - -void run_wnaf(void) { - int i; - secp256k1_scalar_t n; - for (i = 0; i < count; i++) { - random_scalar_order(&n); - test_wnaf(&n, 4+(i%10)); - } -} - -void random_sign(secp256k1_ecdsa_sig_t *sig, const secp256k1_scalar_t *key, const secp256k1_scalar_t *msg, int *recid) { - secp256k1_scalar_t nonce; - do { - random_scalar_order_test(&nonce); - } while(!secp256k1_ecdsa_sig_sign(sig, key, msg, &nonce, recid)); -} - -void test_ecdsa_sign_verify(void) { - secp256k1_gej_t pubj; - secp256k1_ge_t pub; - secp256k1_scalar_t one; - secp256k1_scalar_t msg, key; - secp256k1_ecdsa_sig_t sig; - int recid; - int getrec; - random_scalar_order_test(&msg); - random_scalar_order_test(&key); - secp256k1_ecmult_gen(&pubj, &key); - secp256k1_ge_set_gej(&pub, &pubj); - getrec = secp256k1_rand32()&1; - random_sign(&sig, &key, &msg, getrec?&recid:NULL); - if (getrec) { - CHECK(recid >= 0 && recid < 4); - } - CHECK(secp256k1_ecdsa_sig_verify(&sig, &pub, &msg)); - secp256k1_scalar_set_int(&one, 1); - secp256k1_scalar_add(&msg, &msg, &one); - CHECK(!secp256k1_ecdsa_sig_verify(&sig, &pub, &msg)); -} - -void run_ecdsa_sign_verify(void) { - int i; - for (i = 0; i < 10*count; i++) { - test_ecdsa_sign_verify(); - } -} - -/** Dummy nonce generation function that just uses a precomputed nonce, and fails if it is not accepted. Use only for testing. */ -static int precomputed_nonce_function(unsigned char *nonce32, const unsigned char *msg32, const unsigned char *key32, unsigned int counter, const void *data) { - (void)msg32; - (void)key32; - memcpy(nonce32, data, 32); - return (counter == 0); -} - -static int nonce_function_test_fail(unsigned char *nonce32, const unsigned char *msg32, const unsigned char *key32, unsigned int counter, const void *data) { - /* Dummy nonce generator that has a fatal error on the first counter value. */ - if (counter == 0) { - return 0; - } - return nonce_function_rfc6979(nonce32, msg32, key32, counter - 1, data); -} - -static int nonce_function_test_retry(unsigned char *nonce32, const unsigned char *msg32, const unsigned char *key32, unsigned int counter, const void *data) { - /* Dummy nonce generator that produces unacceptable nonces for the first several counter values. */ - if (counter < 3) { - memset(nonce32, counter==0 ? 0 : 255, 32); - if (counter == 2) { - nonce32[31]--; - } - return 1; - } - if (counter < 5) { - static const unsigned char order[] = { - 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 - }; - memcpy(nonce32, order, 32); - if (counter == 4) { - nonce32[31]++; - } - return 1; - } - /* Retry rate of 6979 is negligible esp. as we only call this in determinstic tests. */ - /* If someone does fine a case where it retries for secp256k1, we'd like to know. */ - if (counter > 5) { - return 0; - } - return nonce_function_rfc6979(nonce32, msg32, key32, counter - 5, data); -} - -int is_empty_compact_signature(const unsigned char *sig64) { - static const unsigned char res[64] = {0}; - return memcmp(sig64, res, 64) == 0; -} - -void test_ecdsa_end_to_end(void) { - unsigned char extra[32] = {0x00}; - unsigned char privkey[32]; - unsigned char message[32]; - unsigned char privkey2[32]; - unsigned char csignature[64]; - unsigned char signature[72]; - unsigned char signature2[72]; - unsigned char signature3[72]; - unsigned char signature4[72]; - unsigned char pubkey[65]; - unsigned char recpubkey[65]; - unsigned char seckey[300]; - int signaturelen = 72; - int signaturelen2 = 72; - int signaturelen3 = 72; - int signaturelen4 = 72; - int recid = 0; - int recpubkeylen = 0; - int pubkeylen = 65; - int seckeylen = 300; - - /* Generate a random key and message. */ - { - secp256k1_scalar_t msg, key; - random_scalar_order_test(&msg); - random_scalar_order_test(&key); - secp256k1_scalar_get_b32(privkey, &key); - secp256k1_scalar_get_b32(message, &msg); - } - - /* Construct and verify corresponding public key. */ - CHECK(secp256k1_ec_seckey_verify(privkey) == 1); - CHECK(secp256k1_ec_pubkey_create(pubkey, &pubkeylen, privkey, (secp256k1_rand32() & 3) != 0) == 1); - if (secp256k1_rand32() & 1) { - CHECK(secp256k1_ec_pubkey_decompress(pubkey, &pubkeylen)); - } - CHECK(secp256k1_ec_pubkey_verify(pubkey, pubkeylen)); - - /* Verify private key import and export. */ - CHECK(secp256k1_ec_privkey_export(privkey, seckey, &seckeylen, secp256k1_rand32() % 2) == 1); - CHECK(secp256k1_ec_privkey_import(privkey2, seckey, seckeylen) == 1); - CHECK(memcmp(privkey, privkey2, 32) == 0); - - /* Optionally tweak the keys using addition. */ - if (secp256k1_rand32() % 3 == 0) { - int ret1; - int ret2; - unsigned char rnd[32]; - unsigned char pubkey2[65]; - int pubkeylen2 = 65; - secp256k1_rand256_test(rnd); - ret1 = secp256k1_ec_privkey_tweak_add(privkey, rnd); - ret2 = secp256k1_ec_pubkey_tweak_add(pubkey, pubkeylen, rnd); - CHECK(ret1 == ret2); - if (ret1 == 0) { - return; - } - CHECK(secp256k1_ec_pubkey_create(pubkey2, &pubkeylen2, privkey, pubkeylen == 33) == 1); - CHECK(memcmp(pubkey, pubkey2, pubkeylen) == 0); - } - - /* Optionally tweak the keys using multiplication. */ - if (secp256k1_rand32() % 3 == 0) { - int ret1; - int ret2; - unsigned char rnd[32]; - unsigned char pubkey2[65]; - int pubkeylen2 = 65; - secp256k1_rand256_test(rnd); - ret1 = secp256k1_ec_privkey_tweak_mul(privkey, rnd); - ret2 = secp256k1_ec_pubkey_tweak_mul(pubkey, pubkeylen, rnd); - CHECK(ret1 == ret2); - if (ret1 == 0) { - return; - } - CHECK(secp256k1_ec_pubkey_create(pubkey2, &pubkeylen2, privkey, pubkeylen == 33) == 1); - CHECK(memcmp(pubkey, pubkey2, pubkeylen) == 0); - } - - /* Sign. */ - CHECK(secp256k1_ecdsa_sign(message, signature, &signaturelen, privkey, NULL, NULL) == 1); - CHECK(signaturelen > 0); - CHECK(secp256k1_ecdsa_sign(message, signature2, &signaturelen2, privkey, NULL, extra) == 1); - CHECK(signaturelen2 > 0); - extra[31] = 1; - CHECK(secp256k1_ecdsa_sign(message, signature3, &signaturelen3, privkey, NULL, extra) == 1); - CHECK(signaturelen3 > 0); - extra[31] = 0; - extra[0] = 1; - CHECK(secp256k1_ecdsa_sign(message, signature4, &signaturelen4, privkey, NULL, extra) == 1); - CHECK(signaturelen3 > 0); - CHECK((signaturelen != signaturelen2) || (memcmp(signature, signature2, signaturelen) != 0)); - CHECK((signaturelen != signaturelen3) || (memcmp(signature, signature3, signaturelen) != 0)); - CHECK((signaturelen3 != signaturelen2) || (memcmp(signature3, signature2, signaturelen3) != 0)); - CHECK((signaturelen4 != signaturelen3) || (memcmp(signature4, signature3, signaturelen4) != 0)); - CHECK((signaturelen4 != signaturelen2) || (memcmp(signature4, signature2, signaturelen4) != 0)); - CHECK((signaturelen4 != signaturelen) || (memcmp(signature4, signature, signaturelen4) != 0)); - /* Verify. */ - CHECK(secp256k1_ecdsa_verify(message, signature, signaturelen, pubkey, pubkeylen) == 1); - CHECK(secp256k1_ecdsa_verify(message, signature2, signaturelen2, pubkey, pubkeylen) == 1); - CHECK(secp256k1_ecdsa_verify(message, signature3, signaturelen3, pubkey, pubkeylen) == 1); - CHECK(secp256k1_ecdsa_verify(message, signature4, signaturelen4, pubkey, pubkeylen) == 1); - /* Destroy signature and verify again. */ - signature[signaturelen - 1 - secp256k1_rand32() % 20] += 1 + (secp256k1_rand32() % 255); - CHECK(secp256k1_ecdsa_verify(message, signature, signaturelen, pubkey, pubkeylen) != 1); - - /* Compact sign. */ - CHECK(secp256k1_ecdsa_sign_compact(message, csignature, privkey, NULL, NULL, &recid) == 1); - CHECK(!is_empty_compact_signature(csignature)); - /* Recover. */ - CHECK(secp256k1_ecdsa_recover_compact(message, csignature, recpubkey, &recpubkeylen, pubkeylen == 33, recid) == 1); - CHECK(recpubkeylen == pubkeylen); - CHECK(memcmp(pubkey, recpubkey, pubkeylen) == 0); - /* Destroy signature and verify again. */ - csignature[secp256k1_rand32() % 64] += 1 + (secp256k1_rand32() % 255); - CHECK(secp256k1_ecdsa_recover_compact(message, csignature, recpubkey, &recpubkeylen, pubkeylen == 33, recid) != 1 || - memcmp(pubkey, recpubkey, pubkeylen) != 0); - CHECK(recpubkeylen == pubkeylen); - -} - -void test_random_pubkeys(void) { - secp256k1_ge_t elem; - secp256k1_ge_t elem2; - unsigned char in[65]; - /* Generate some randomly sized pubkeys. */ - uint32_t r = secp256k1_rand32(); - int len = (r & 3) == 0 ? 65 : 33; - r>>=2; - if ((r & 3) == 0) { - len = (r & 252) >> 3; - } - r>>=8; - if (len == 65) { - in[0] = (r & 2) ? 4 : (r & 1? 6 : 7); - } else { - in[0] = (r & 1) ? 2 : 3; - } - r>>=2; - if ((r & 7) == 0) { - in[0] = (r & 2040) >> 3; - } - r>>=11; - if (len > 1) { - secp256k1_rand256(&in[1]); - } - if (len > 33) { - secp256k1_rand256(&in[33]); - } - if (secp256k1_eckey_pubkey_parse(&elem, in, len)) { - unsigned char out[65]; - unsigned char firstb; - int res; - int size = len; - firstb = in[0]; - /* If the pubkey can be parsed, it should round-trip... */ - CHECK(secp256k1_eckey_pubkey_serialize(&elem, out, &size, len == 33)); - CHECK(size == len); - CHECK(memcmp(&in[1], &out[1], len-1) == 0); - /* ... except for the type of hybrid inputs. */ - if ((in[0] != 6) && (in[0] != 7)) { - CHECK(in[0] == out[0]); - } - size = 65; - CHECK(secp256k1_eckey_pubkey_serialize(&elem, in, &size, 0)); - CHECK(size == 65); - CHECK(secp256k1_eckey_pubkey_parse(&elem2, in, size)); - ge_equals_ge(&elem,&elem2); - /* Check that the X9.62 hybrid type is checked. */ - in[0] = (r & 1) ? 6 : 7; - res = secp256k1_eckey_pubkey_parse(&elem2, in, size); - if (firstb == 2 || firstb == 3) { - if (in[0] == firstb + 4) { - CHECK(res); - } else { - CHECK(!res); - } - } - if (res) { - ge_equals_ge(&elem,&elem2); - CHECK(secp256k1_eckey_pubkey_serialize(&elem, out, &size, 0)); - CHECK(memcmp(&in[1], &out[1], 64) == 0); - } - } -} - -void run_random_pubkeys(void) { - int i; - for (i = 0; i < 10*count; i++) { - test_random_pubkeys(); - } -} - -void run_ecdsa_end_to_end(void) { - int i; - for (i = 0; i < 64*count; i++) { - test_ecdsa_end_to_end(); - } -} - -/* Tests several edge cases. */ -void test_ecdsa_edge_cases(void) { - const unsigned char msg32[32] = { - 'T', 'h', 'i', 's', ' ', 'i', 's', ' ', - 'a', ' ', 'v', 'e', 'r', 'y', ' ', 's', - 'e', 'c', 'r', 'e', 't', ' ', 'm', 'e', - 's', 's', 'a', 'g', 'e', '.', '.', '.' - }; - const unsigned char sig64[64] = { - /* Generated by signing the above message with nonce 'This is the nonce we will use...' - * and secret key 0 (which is not valid), resulting in recid 0. */ - 0x67, 0xCB, 0x28, 0x5F, 0x9C, 0xD1, 0x94, 0xE8, - 0x40, 0xD6, 0x29, 0x39, 0x7A, 0xF5, 0x56, 0x96, - 0x62, 0xFD, 0xE4, 0x46, 0x49, 0x99, 0x59, 0x63, - 0x17, 0x9A, 0x7D, 0xD1, 0x7B, 0xD2, 0x35, 0x32, - 0x4B, 0x1B, 0x7D, 0xF3, 0x4C, 0xE1, 0xF6, 0x8E, - 0x69, 0x4F, 0xF6, 0xF1, 0x1A, 0xC7, 0x51, 0xDD, - 0x7D, 0xD7, 0x3E, 0x38, 0x7E, 0xE4, 0xFC, 0x86, - 0x6E, 0x1B, 0xE8, 0xEC, 0xC7, 0xDD, 0x95, 0x57 - }; - unsigned char pubkey[65]; - int t; - int pubkeylen = 65; - /* signature (r,s) = (4,4), which can be recovered with all 4 recids. */ - const unsigned char sigb64[64] = { - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, - }; - unsigned char pubkeyb[33]; - int pubkeyblen = 33; - int recid; - - CHECK(!secp256k1_ecdsa_recover_compact(msg32, sig64, pubkey, &pubkeylen, 0, 0)); - CHECK(secp256k1_ecdsa_recover_compact(msg32, sig64, pubkey, &pubkeylen, 0, 1)); - CHECK(!secp256k1_ecdsa_recover_compact(msg32, sig64, pubkey, &pubkeylen, 0, 2)); - CHECK(!secp256k1_ecdsa_recover_compact(msg32, sig64, pubkey, &pubkeylen, 0, 3)); - - for (recid = 0; recid < 4; recid++) { - int i; - int recid2; - /* (4,4) encoded in DER. */ - unsigned char sigbder[8] = {0x30, 0x06, 0x02, 0x01, 0x04, 0x02, 0x01, 0x04}; - unsigned char sigcder_zr[7] = {0x30, 0x05, 0x02, 0x00, 0x02, 0x01, 0x01}; - unsigned char sigcder_zs[7] = {0x30, 0x05, 0x02, 0x01, 0x01, 0x02, 0x00}; - unsigned char sigbderalt1[39] = { - 0x30, 0x25, 0x02, 0x20, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x04, 0x02, 0x01, 0x04, - }; - unsigned char sigbderalt2[39] = { - 0x30, 0x25, 0x02, 0x01, 0x04, 0x02, 0x20, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, - }; - unsigned char sigbderalt3[40] = { - 0x30, 0x26, 0x02, 0x21, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x04, 0x02, 0x01, 0x04, - }; - unsigned char sigbderalt4[40] = { - 0x30, 0x26, 0x02, 0x01, 0x04, 0x02, 0x21, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, - }; - /* (order + r,4) encoded in DER. */ - unsigned char sigbderlong[40] = { - 0x30, 0x26, 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, 0x45, 0x02, 0x01, 0x04 - }; - CHECK(secp256k1_ecdsa_recover_compact(msg32, sigb64, pubkeyb, &pubkeyblen, 1, recid)); - CHECK(secp256k1_ecdsa_verify(msg32, sigbder, sizeof(sigbder), pubkeyb, pubkeyblen) == 1); - for (recid2 = 0; recid2 < 4; recid2++) { - unsigned char pubkey2b[33]; - int pubkey2blen = 33; - CHECK(secp256k1_ecdsa_recover_compact(msg32, sigb64, pubkey2b, &pubkey2blen, 1, recid2)); - /* Verifying with (order + r,4) should always fail. */ - CHECK(secp256k1_ecdsa_verify(msg32, sigbderlong, sizeof(sigbderlong), pubkey2b, pubkey2blen) != 1); - } - /* DER parsing tests. */ - /* Zero length r/s. */ - CHECK(secp256k1_ecdsa_verify(msg32, sigcder_zr, sizeof(sigcder_zr), pubkeyb, pubkeyblen) == -2); - CHECK(secp256k1_ecdsa_verify(msg32, sigcder_zs, sizeof(sigcder_zs), pubkeyb, pubkeyblen) == -2); - /* Leading zeros. */ - CHECK(secp256k1_ecdsa_verify(msg32, sigbderalt1, sizeof(sigbderalt1), pubkeyb, pubkeyblen) == 1); - CHECK(secp256k1_ecdsa_verify(msg32, sigbderalt2, sizeof(sigbderalt2), pubkeyb, pubkeyblen) == 1); - CHECK(secp256k1_ecdsa_verify(msg32, sigbderalt3, sizeof(sigbderalt3), pubkeyb, pubkeyblen) == 1); - CHECK(secp256k1_ecdsa_verify(msg32, sigbderalt4, sizeof(sigbderalt4), pubkeyb, pubkeyblen) == 1); - sigbderalt3[4] = 1; - CHECK(secp256k1_ecdsa_verify(msg32, sigbderalt3, sizeof(sigbderalt3), pubkeyb, pubkeyblen) == -2); - sigbderalt4[7] = 1; - CHECK(secp256k1_ecdsa_verify(msg32, sigbderalt4, sizeof(sigbderalt4), pubkeyb, pubkeyblen) == -2); - /* Damage signature. */ - sigbder[7]++; - CHECK(secp256k1_ecdsa_verify(msg32, sigbder, sizeof(sigbder), pubkeyb, pubkeyblen) == 0); - sigbder[7]--; - CHECK(secp256k1_ecdsa_verify(msg32, sigbder, 6, pubkeyb, pubkeyblen) == -2); - CHECK(secp256k1_ecdsa_verify(msg32, sigbder, sizeof(sigbder)-1, pubkeyb, pubkeyblen) == -2); - for(i = 0; i < 8; i++) { - int c; - unsigned char orig = sigbder[i]; - /*Try every single-byte change.*/ - for (c = 0; c < 256; c++) { - if (c == orig ) { - continue; - } - sigbder[i] = c; - CHECK(secp256k1_ecdsa_verify(msg32, sigbder, sizeof(sigbder), pubkeyb, pubkeyblen) == - (i==4 || i==7) ? 0 : -2 ); - } - sigbder[i] = orig; - } - } - - /* Test the case where ECDSA recomputes a point that is infinity. */ - { - secp256k1_gej_t keyj; - secp256k1_ge_t key; - secp256k1_scalar_t msg; - secp256k1_ecdsa_sig_t sig; - secp256k1_scalar_set_int(&sig.s, 1); - secp256k1_scalar_negate(&sig.s, &sig.s); - secp256k1_scalar_inverse(&sig.s, &sig.s); - secp256k1_scalar_set_int(&sig.r, 1); - secp256k1_ecmult_gen(&keyj, &sig.r); - secp256k1_ge_set_gej(&key, &keyj); - msg = sig.s; - CHECK(secp256k1_ecdsa_sig_verify(&sig, &key, &msg) == 0); - } - - /* Test r/s equal to zero */ - { - /* (1,1) encoded in DER. */ - unsigned char sigcder[8] = {0x30, 0x06, 0x02, 0x01, 0x01, 0x02, 0x01, 0x01}; - unsigned char sigc64[64] = { - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, - }; - unsigned char pubkeyc[65]; - int pubkeyclen = 65; - CHECK(secp256k1_ecdsa_recover_compact(msg32, sigc64, pubkeyc, &pubkeyclen, 0, 0) == 1); - CHECK(secp256k1_ecdsa_verify(msg32, sigcder, sizeof(sigcder), pubkeyc, pubkeyclen) == 1); - sigcder[4] = 0; - sigc64[31] = 0; - CHECK(secp256k1_ecdsa_recover_compact(msg32, sigc64, pubkeyb, &pubkeyblen, 1, 0) == 0); - CHECK(secp256k1_ecdsa_verify(msg32, sigcder, sizeof(sigcder), pubkeyc, pubkeyclen) == 0); - sigcder[4] = 1; - sigcder[7] = 0; - sigc64[31] = 1; - sigc64[63] = 0; - CHECK(secp256k1_ecdsa_recover_compact(msg32, sigc64, pubkeyb, &pubkeyblen, 1, 0) == 0); - CHECK(secp256k1_ecdsa_verify(msg32, sigcder, sizeof(sigcder), pubkeyc, pubkeyclen) == 0); - } - - /*Signature where s would be zero.*/ - { - const unsigned char nonce[32] = { - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, - }; - static const unsigned char nonce2[32] = { - 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,0x40 - }; - const unsigned char key[32] = { - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, - }; - unsigned char msg[32] = { - 0x86, 0x41, 0x99, 0x81, 0x06, 0x23, 0x44, 0x53, - 0xaa, 0x5f, 0x9d, 0x6a, 0x31, 0x78, 0xf4, 0xf7, - 0xb8, 0x12, 0xe0, 0x0b, 0x81, 0x7a, 0x77, 0x62, - 0x65, 0xdf, 0xdd, 0x31, 0xb9, 0x3e, 0x29, 0xa9, - }; - unsigned char sig[72]; - int siglen = 72; - CHECK(secp256k1_ecdsa_sign(msg, sig, &siglen, key, precomputed_nonce_function, nonce) == 0); - CHECK(siglen == 0); - CHECK(secp256k1_ecdsa_sign(msg, sig, &siglen, key, precomputed_nonce_function, nonce2) == 0); - CHECK(siglen == 0); - msg[31] = 0xaa; - siglen = 72; - CHECK(secp256k1_ecdsa_sign(msg, sig, &siglen, key, precomputed_nonce_function, nonce) == 1); - CHECK(siglen > 0); - CHECK(secp256k1_ecdsa_sign(msg, sig, &siglen, key, precomputed_nonce_function, nonce2) == 1); - CHECK(siglen > 0); - siglen = 10; - CHECK(secp256k1_ecdsa_sign(msg, sig, &siglen, key, precomputed_nonce_function, nonce) != 1); - CHECK(siglen == 0); - } - - /* Nonce function corner cases. */ - for (t = 0; t < 2; t++) { - static const unsigned char zero[32] = {0x00}; - int i; - unsigned char key[32]; - unsigned char msg[32]; - unsigned char sig[72]; - unsigned char sig2[72]; - secp256k1_ecdsa_sig_t s[512]; - int siglen = 72; - int siglen2 = 72; - int recid2; - const unsigned char *extra; - extra = t == 0 ? NULL : zero; - memset(msg, 0, 32); - msg[31] = 1; - /* High key results in signature failure. */ - memset(key, 0xFF, 32); - CHECK(secp256k1_ecdsa_sign(msg, sig, &siglen, key, NULL, extra) == 0); - CHECK(siglen == 0); - /* Zero key results in signature failure. */ - memset(key, 0, 32); - CHECK(secp256k1_ecdsa_sign(msg, sig, &siglen, key, NULL, extra) == 0); - CHECK(siglen == 0); - /* Nonce function failure results in signature failure. */ - key[31] = 1; - CHECK(secp256k1_ecdsa_sign(msg, sig, &siglen, key, nonce_function_test_fail, extra) == 0); - CHECK(siglen == 0); - CHECK(secp256k1_ecdsa_sign_compact(msg, sig, key, nonce_function_test_fail, extra, &recid) == 0); - CHECK(is_empty_compact_signature(sig)); - /* The retry loop successfully makes its way to the first good value. */ - siglen = 72; - CHECK(secp256k1_ecdsa_sign(msg, sig, &siglen, key, nonce_function_test_retry, extra) == 1); - CHECK(siglen > 0); - CHECK(secp256k1_ecdsa_sign(msg, sig2, &siglen2, key, nonce_function_rfc6979, extra) == 1); - CHECK(siglen > 0); - CHECK((siglen == siglen2) && (memcmp(sig, sig2, siglen) == 0)); - CHECK(secp256k1_ecdsa_sign_compact(msg, sig, key, nonce_function_test_retry, extra, &recid) == 1); - CHECK(!is_empty_compact_signature(sig)); - CHECK(secp256k1_ecdsa_sign_compact(msg, sig2, key, nonce_function_rfc6979, extra, &recid2) == 1); - CHECK(!is_empty_compact_signature(sig2)); - CHECK((recid == recid2) && (memcmp(sig, sig2, 64) == 0)); - /* The default nonce function is determinstic. */ - siglen = 72; - siglen2 = 72; - CHECK(secp256k1_ecdsa_sign(msg, sig, &siglen, key, NULL, extra) == 1); - CHECK(siglen > 0); - CHECK(secp256k1_ecdsa_sign(msg, sig2, &siglen2, key, NULL, extra) == 1); - CHECK(siglen2 > 0); - CHECK((siglen == siglen2) && (memcmp(sig, sig2, siglen) == 0)); - CHECK(secp256k1_ecdsa_sign_compact(msg, sig, key, NULL, extra, &recid) == 1); - CHECK(!is_empty_compact_signature(sig)); - CHECK(secp256k1_ecdsa_sign_compact(msg, sig2, key, NULL, extra, &recid2) == 1); - CHECK(!is_empty_compact_signature(sig)); - CHECK((recid == recid2) && (memcmp(sig, sig2, 64) == 0)); - /* The default nonce function changes output with different messages. */ - for(i = 0; i < 256; i++) { - int j; - siglen2 = 72; - msg[0] = i; - CHECK(secp256k1_ecdsa_sign(msg, sig2, &siglen2, key, NULL, extra) == 1); - CHECK(!is_empty_compact_signature(sig)); - CHECK(secp256k1_ecdsa_sig_parse(&s[i], sig2, siglen2)); - for (j = 0; j < i; j++) { - CHECK(!secp256k1_scalar_eq(&s[i].r, &s[j].r)); - } - } - msg[0] = 0; - msg[31] = 2; - /* The default nonce function changes output with different keys. */ - for(i = 256; i < 512; i++) { - int j; - siglen2 = 72; - key[0] = i - 256; - CHECK(secp256k1_ecdsa_sign(msg, sig2, &siglen2, key, NULL, extra) == 1); - CHECK(secp256k1_ecdsa_sig_parse(&s[i], sig2, siglen2)); - for (j = 0; j < i; j++) { - CHECK(!secp256k1_scalar_eq(&s[i].r, &s[j].r)); - } - } - key[0] = 0; - } - - /* Privkey export where pubkey is the point at infinity. */ - { - unsigned char privkey[300]; - unsigned char seckey[32] = { - 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, - }; - int outlen = 300; - CHECK(!secp256k1_ec_privkey_export(seckey, privkey, &outlen, 0)); - CHECK(!secp256k1_ec_privkey_export(seckey, privkey, &outlen, 1)); - } -} - -void run_ecdsa_edge_cases(void) { - test_ecdsa_edge_cases(); -} - -#ifdef ENABLE_OPENSSL_TESTS -EC_KEY *get_openssl_key(const secp256k1_scalar_t *key) { - unsigned char privkey[300]; - int privkeylen; - const unsigned char* pbegin = privkey; - int compr = secp256k1_rand32() & 1; - EC_KEY *ec_key = EC_KEY_new_by_curve_name(NID_secp256k1); - CHECK(secp256k1_eckey_privkey_serialize(privkey, &privkeylen, key, compr)); - CHECK(d2i_ECPrivateKey(&ec_key, &pbegin, privkeylen)); - CHECK(EC_KEY_check_key(ec_key)); - return ec_key; -} - -void test_ecdsa_openssl(void) { - secp256k1_gej_t qj; - secp256k1_ge_t q; - secp256k1_ecdsa_sig_t sig; - secp256k1_scalar_t one; - secp256k1_scalar_t msg2; - secp256k1_scalar_t key, msg; - EC_KEY *ec_key; - unsigned int sigsize = 80; - int secp_sigsize = 80; - unsigned char message[32]; - unsigned char signature[80]; - secp256k1_rand256_test(message); - secp256k1_scalar_set_b32(&msg, message, NULL); - random_scalar_order_test(&key); - secp256k1_ecmult_gen(&qj, &key); - secp256k1_ge_set_gej(&q, &qj); - ec_key = get_openssl_key(&key); - CHECK(ec_key); - CHECK(ECDSA_sign(0, message, sizeof(message), signature, &sigsize, ec_key)); - CHECK(secp256k1_ecdsa_sig_parse(&sig, signature, sigsize)); - CHECK(secp256k1_ecdsa_sig_verify(&sig, &q, &msg)); - secp256k1_scalar_set_int(&one, 1); - secp256k1_scalar_add(&msg2, &msg, &one); - CHECK(!secp256k1_ecdsa_sig_verify(&sig, &q, &msg2)); - - random_sign(&sig, &key, &msg, NULL); - CHECK(secp256k1_ecdsa_sig_serialize(signature, &secp_sigsize, &sig)); - CHECK(ECDSA_verify(0, message, sizeof(message), signature, secp_sigsize, ec_key) == 1); - - EC_KEY_free(ec_key); -} - -void run_ecdsa_openssl(void) { - int i; - for (i = 0; i < 10*count; i++) { - test_ecdsa_openssl(); - } -} -#endif - -int main(int argc, char **argv) { - unsigned char seed16[16] = {0}; - unsigned char run32[32] = {0}; - /* find iteration count */ - if (argc > 1) { - count = strtol(argv[1], NULL, 0); - } - - /* find random seed */ - if (argc > 2) { - int pos = 0; - const char* ch = argv[2]; - while (pos < 16 && ch[0] != 0 && ch[1] != 0) { - unsigned short sh; - if (sscanf(ch, "%2hx", &sh)) { - seed16[pos] = sh; - } else { - break; - } - ch += 2; - pos++; - } - } else { - FILE *frand = fopen("/dev/urandom", "r"); - if (!frand || !fread(&seed16, sizeof(seed16), 1, frand)) { - uint64_t t = time(NULL) * (uint64_t)1337; - seed16[0] ^= t; - seed16[1] ^= t >> 8; - seed16[2] ^= t >> 16; - seed16[3] ^= t >> 24; - seed16[4] ^= t >> 32; - seed16[5] ^= t >> 40; - seed16[6] ^= t >> 48; - seed16[7] ^= t >> 56; - } - fclose(frand); - } - secp256k1_rand_seed(seed16); - - printf("test count = %i\n", count); - printf("random seed = %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x\n", seed16[0], seed16[1], seed16[2], seed16[3], seed16[4], seed16[5], seed16[6], seed16[7], seed16[8], seed16[9], seed16[10], seed16[11], seed16[12], seed16[13], seed16[14], seed16[15]); - - /* initialize */ - secp256k1_start(SECP256K1_START_SIGN | SECP256K1_START_VERIFY); - - /* initializing a second time shouldn't cause any harm or memory leaks. */ - secp256k1_start(SECP256K1_START_SIGN | SECP256K1_START_VERIFY); - - run_sha256_tests(); - run_hmac_sha256_tests(); - run_rfc6979_hmac_sha256_tests(); - -#ifndef USE_NUM_NONE - /* num tests */ - run_num_smalltests(); -#endif - - /* scalar tests */ - run_scalar_tests(); - - /* field tests */ - run_field_inv(); - run_field_inv_var(); - run_field_inv_all_var(); - run_field_misc(); - run_field_convert(); - run_sqr(); - run_sqrt(); - - /* group tests */ - run_ge(); - - /* ecmult tests */ - run_wnaf(); - run_point_times_order(); - run_ecmult_chain(); - - /* ecdsa tests */ - run_random_pubkeys(); - run_ecdsa_sign_verify(); - run_ecdsa_end_to_end(); - run_ecdsa_edge_cases(); -#ifdef ENABLE_OPENSSL_TESTS - run_ecdsa_openssl(); -#endif - - secp256k1_rand256(run32); - printf("random run = %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x\n", run32[0], run32[1], run32[2], run32[3], run32[4], run32[5], run32[6], run32[7], run32[8], run32[9], run32[10], run32[11], run32[12], run32[13], run32[14], run32[15]); - - /* shutdown */ - secp256k1_stop(); - - /* shutting down twice shouldn't cause any double frees. */ - secp256k1_stop(); - return 0; -} diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/util.h b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/util.h deleted file mode 100644 index ae98639f7ca31ae4621b497017fb6d9b32b81dba..0000000000000000000000000000000000000000 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/secp256k1/secp256k1/src/util.h +++ /dev/null @@ -1,104 +0,0 @@ -/********************************************************************** - * 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_UTIL_H_ -#define _SECP256K1_UTIL_H_ - -#if defined HAVE_CONFIG_H -#include "libsecp256k1-config.h" -#endif - -#include <stdlib.h> -#include <stdint.h> -#include <stdio.h> - -#ifdef DETERMINISTIC -#define TEST_FAILURE(msg) do { \ - fprintf(stderr, "%s\n", msg); \ - abort(); \ -} while(0); -#else -#define TEST_FAILURE(msg) do { \ - fprintf(stderr, "%s:%d: %s\n", __FILE__, __LINE__, msg); \ - abort(); \ -} while(0) -#endif - -#ifdef HAVE_BUILTIN_EXPECT -#define EXPECT(x,c) __builtin_expect((x),(c)) -#else -#define EXPECT(x,c) (x) -#endif - -#ifdef DETERMINISTIC -#define CHECK(cond) do { \ - if (EXPECT(!(cond), 0)) { \ - TEST_FAILURE("test condition failed"); \ - } \ -} while(0) -#else -#define CHECK(cond) do { \ - if (EXPECT(!(cond), 0)) { \ - TEST_FAILURE("test condition failed: " #cond); \ - } \ -} while(0) -#endif - -/* Like assert(), but safe to use on expressions with side effects. */ -#ifndef NDEBUG -#define DEBUG_CHECK CHECK -#else -#define DEBUG_CHECK(cond) do { (void)(cond); } while(0) -#endif - -/* Like DEBUG_CHECK(), but when VERIFY is defined instead of NDEBUG not defined. */ -#ifdef VERIFY -#define VERIFY_CHECK CHECK -#else -#define VERIFY_CHECK(cond) do { (void)(cond); } while(0) -#endif - -static SECP256K1_INLINE void *checked_malloc(size_t size) { - void *ret = malloc(size); - CHECK(ret != NULL); - return ret; -} - -/* Macro for restrict, when available and not in a VERIFY build. */ -#if defined(SECP256K1_BUILD) && defined(VERIFY) -# define SECP256K1_RESTRICT -#else -# if (!defined(__STDC_VERSION__) || (__STDC_VERSION__ < 199901L) ) -# if SECP256K1_GNUC_PREREQ(3,0) -# define SECP256K1_RESTRICT __restrict__ -# elif (defined(_MSC_VER) && _MSC_VER >= 1400) -# define SECP256K1_RESTRICT __restrict -# else -# define SECP256K1_RESTRICT -# endif -# else -# define SECP256K1_RESTRICT restrict -# endif -#endif - -#if defined(_WIN32) -# define I64FORMAT "I64d" -# define I64uFORMAT "I64u" -#else -# define I64FORMAT "lld" -# define I64uFORMAT "llu" -#endif - -#if defined(HAVE___INT128) -# if defined(__GNUC__) -# define SECP256K1_GNUC_EXT __extension__ -# else -# define SECP256K1_GNUC_EXT -# endif -SECP256K1_GNUC_EXT typedef unsigned __int128 uint128_t; -#endif - -#endif diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/stack.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/stack.go index 9667de10fbfb03e5ec1ef16c67e385de3611890d..764d658fd53d77638e407e93f7473ba1f3d2a015 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/stack.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/stack.go @@ -104,6 +104,10 @@ func (st *Stack) Dup(n int) { // Not an opcode, costs no gas. func (st *Stack) Peek() Word256 { + if st.ptr == 0 { + st.setErr(ErrDataStackUnderflow) + return Zero256 + } return st.data[st.ptr-1] } diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/test/fake_app_state.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/test/fake_app_state.go index a0a65cf553bbd8151178a751db20dd55b65bbb83..1a328b992201a5bb976801279f3e4a3f6747924f 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/test/fake_app_state.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/test/fake_app_state.go @@ -9,7 +9,6 @@ import ( type FakeAppState struct { accounts map[string]*Account storage map[string]Word256 - logs []*Log } func (fas *FakeAppState) GetAccount(addr Word256) *Account { @@ -69,10 +68,6 @@ func (fas *FakeAppState) SetStorage(addr Word256, key Word256, value Word256) { fas.storage[addr.String()+key.String()] = value } -func (fas *FakeAppState) AddLog(log *Log) { - fas.logs = append(fas.logs, log) -} - // Creates a 20 byte address and bumps the nonce. func createAddress(creator *Account) Word256 { nonce := creator.Nonce diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/test/log_event_test.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/test/log_event_test.go index bb31c603d6397bb7dbc49312670ac5b47c0e5c35..c0fca12dd1ab36e51dfc34d47e340a570e81119f 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/test/log_event_test.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/test/log_event_test.go @@ -36,13 +36,16 @@ func TestLog4(t *testing.T) { ourVm := NewVM(st, newParams(), Zero256, nil) eventSwitch := events.NewEventSwitch() - eventSwitch.Start() - eventId := types.EventStringLogEvent(account2.Address.Postfix(20)) + _, err := eventSwitch.Start() + if err != nil { + t.Errorf("Failed to start eventSwitch: %v", err) + } + eventID := types.EventStringLogEvent(account2.Address.Postfix(20)) doneChan := make(chan struct{}, 1) - eventSwitch.AddListenerForEvent("test", eventId, func(event interface{}) { - logEvent := event.(*Log) + eventSwitch.AddListenerForEvent("test", eventID, func(event types.EventData) { + logEvent := event.(types.EventDataLog) // No need to test address as this event would not happen if it wasn't correct if !reflect.DeepEqual(logEvent.Topics, expectedTopics) { t.Errorf("Event topics are wrong. Got: %v. Expected: %v", logEvent.Topics, expectedTopics) @@ -79,7 +82,7 @@ func TestLog4(t *testing.T) { stop, } - _, err := ourVm.Call(account1, account2, code, []byte{}, 0, &gas) + _, err = ourVm.Call(account1, account2, code, []byte{}, 0, &gas) <-doneChan if err != nil { t.Fatal(err) diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/test/vm_test.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/test/vm_test.go index 684d7324f9f2f20b34dc4620c7adee4788fff6a7..899bb2b7b8b27e57903d42b2a9a03af20ae3a891 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/test/vm_test.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/test/vm_test.go @@ -19,7 +19,6 @@ func newAppState() *FakeAppState { fas := &FakeAppState{ accounts: make(map[string]*Account), storage: make(map[string]Word256), - logs: nil, } // For default permissions fas.accounts[ptypes.GlobalPermissionsAddress256.String()] = &Account{ @@ -158,7 +157,7 @@ func runVMWaitEvents(t *testing.T, ourVm *VM, caller, callee *Account, subscribe evsw.Start() ch := make(chan interface{}) fmt.Printf("subscribe to %x\n", subscribeAddr) - evsw.AddListenerForEvent("test", types.EventStringAccCall(subscribeAddr), func(msg interface{}) { + evsw.AddListenerForEvent("test", types.EventStringAccCall(subscribeAddr), func(msg types.EventData) { ch <- msg }) evc := events.NewEventCache(evsw) @@ -175,9 +174,9 @@ func runVMWaitEvents(t *testing.T, ourVm *VM, caller, callee *Account, subscribe }() msg := <-ch switch ev := msg.(type) { - case types.EventMsgCallTx: + case types.EventDataTx: return ev.Exception - case types.EventMsgCall: + case types.EventDataCall: return ev.Exception case string: return ev diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/types.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/types.go index 5015420599bbd645be41244962d7f6909f4bffa7..26103be6af659c3066f6c5eafe9db342587c4008 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/types.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/types.go @@ -27,15 +27,6 @@ func (acc *Account) String() string { acc.Address, acc.Balance, acc.Code, acc.Nonce) } -// NOTE: This is serialized as an event from vm/vm. -// See: EventStringLogEvent -type Log struct { - Address Word256 `json:"address"` - Topics []Word256 `json:"topics"` - Data []byte `json:"data"` - Height int64 `json:"height"` -} - type AppState interface { // Accounts @@ -48,8 +39,6 @@ type AppState interface { GetStorage(Word256, Word256) Word256 SetStorage(Word256, Word256, Word256) // Setting to Zero is deleting. - // Logs - AddLog(*Log) } type Params struct { diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/vm.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/vm.go index e59212c65e951dcb29276829b1fec3e13afb76b6..38ce23f7919d9bf453d2e40945314ef0a6b5825a 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/vm.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/vm/vm.go @@ -42,7 +42,7 @@ const ( dataStackCapacity = 1024 callStackCapacity = 100 // TODO ensure usage. memoryCapacity = 1024 * 1024 // 1 MB - dbg Debug = false + dbg Debug = true ) func (d Debug) Printf(s string, a ...interface{}) { @@ -98,7 +98,7 @@ func HasPermission(appState AppState, acc *Account, perm ptypes.PermFlag) bool { func (vm *VM) fireCallEvent(exception *string, output *[]byte, caller, callee *Account, input []byte, value int64, gas *int64) { // fire the post call event (including exception if applicable) if vm.evc != nil { - vm.evc.FireEvent(types.EventStringAccCall(callee.Address.Postfix(20)), types.EventMsgCall{ + vm.evc.FireEvent(types.EventStringAccCall(callee.Address.Postfix(20)), types.EventDataCall{ &types.CallData{caller.Address.Postfix(20), callee.Address.Postfix(20), input, value, *gas}, vm.origin.Postfix(20), vm.txid, @@ -691,20 +691,18 @@ func (vm *VM) call(caller, callee *Account, code, input []byte, value int64, gas if !ok { return nil, firstErr(err, ErrMemoryOutOfBounds) } - log := &Log{ - callee.Address, - topics, - data, - vm.params.BlockHeight, - } - vm.appState.AddLog(log) if vm.evc != nil { - eventId := types.EventStringLogEvent(callee.Address.Postfix(20)) - fmt.Printf("eventId: %s\n", eventId) - vm.evc.FireEvent(eventId, log) + eventID := types.EventStringLogEvent(callee.Address.Postfix(20)) + fmt.Printf("eventID: %s\n", eventID) + log := types.EventDataLog{ + callee.Address, + topics, + data, + vm.params.BlockHeight, + } + vm.evc.FireEvent(eventID, log) } - // Using sol-log for this as well since 'log' will print garbage. - dbg.Printf(" => T:%X D:%X\n", log.Topics, log.Data) + dbg.Printf(" => T:%X D:%X\n", topics, data) case CREATE: // 0xF0 if !HasPermission(vm.appState, callee, ptypes.CreateContract) { @@ -770,6 +768,7 @@ func (vm *VM) call(caller, callee *Account, code, input []byte, value int64, gas if err != nil { exception = err.Error() } + // NOTE: these fire call events and not particular events for eg name reg or permissions vm.fireCallEvent(&exception, &ret, callee, &Account{Address: addr}, args, value, gas) } else { // EVM contract diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/wire/reflect.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/wire/reflect.go index efde6162d9466fd3284fd99dcfb1e603a1993e2b..8284594de0a606afa70857495731347bc32657a2 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/wire/reflect.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/wire/reflect.go @@ -93,7 +93,7 @@ var ( ) const ( - rfc2822 = "Mon Jan 02 15:04:05 -0700 2006" + iso8601 = "2006-01-02T15:04:05.000Z" // forced microseconds ) // NOTE: do not access typeInfos directly, but call GetTypeInfo() @@ -419,11 +419,14 @@ func writeReflectBinary(rv reflect.Value, rt reflect.Type, opts Options, w io.Wr if !ok { switch crt.Kind() { case reflect.Ptr: - *err = errors.New(Fmt("Unexpected pointer type %v. Was it registered as a value receiver rather than as a pointer receiver?", crt)) + *err = errors.New(Fmt("Unexpected pointer type %v for registered interface %v. "+ + "Was it registered as a value receiver rather than as a pointer receiver?", crt, rt.Name())) case reflect.Struct: - *err = errors.New(Fmt("Unexpected struct type %v. Was it registered as a pointer receiver rather than as a value receiver?", crt)) + *err = errors.New(Fmt("Unexpected struct type %v for registered interface %v. "+ + "Was it registered as a pointer receiver rather than as a value receiver?", crt, rt.Name())) default: - *err = errors.New(Fmt("Unexpected type %v.", crt)) + *err = errors.New(Fmt("Unexpected type %v for registered interface %v. "+ + "If this is intentional, please register it.", crt, rt.Name())) } return } @@ -585,6 +588,7 @@ func readByteJSON(o interface{}) (typeByte byte, rest interface{}, err error) { // Contract: Caller must ensure that rt is supported // (e.g. is recursively composed of supported native types, and structs and slices.) +// rv and rt refer to the object we're unmarhsaling into, whereas o is the result of naiive json unmarshal (map[string]interface{}) func readReflectJSON(rv reflect.Value, rt reflect.Type, o interface{}, err *error) { // Get typeInfo @@ -727,7 +731,7 @@ func readReflectJSON(rv reflect.Value, rt reflect.Type, o interface{}, err *erro return } log.Info(Fmt("Read time: %v", str)) - t, err_ := time.Parse(rfc2822, str) + t, err_ := time.Parse(iso8601, str) if err_ != nil { *err = err_ return @@ -818,11 +822,14 @@ func writeReflectJSON(rv reflect.Value, rt reflect.Type, w io.Writer, n *int64, if !ok { switch crt.Kind() { case reflect.Ptr: - *err = errors.New(Fmt("Unexpected pointer type %v. Was it registered as a value receiver rather than as a pointer receiver?", crt)) + *err = errors.New(Fmt("Unexpected pointer type %v for registered interface %v. "+ + "Was it registered as a value receiver rather than as a pointer receiver?", crt, rt.Name())) case reflect.Struct: - *err = errors.New(Fmt("Unexpected struct type %v. Was it registered as a pointer receiver rather than as a value receiver?", crt)) + *err = errors.New(Fmt("Unexpected struct type %v for registered interface %v. "+ + "Was it registered as a pointer receiver rather than as a value receiver?", crt, rt.Name())) default: - *err = errors.New(Fmt("Unexpected type %v.", crt)) + *err = errors.New(Fmt("Unexpected type %v for registered interface %v. "+ + "If this is intentional, please register it.", crt, rt.Name())) } return } @@ -901,8 +908,8 @@ func writeReflectJSON(rv reflect.Value, rt reflect.Type, w io.Writer, n *int64, case reflect.Struct: if rt == timeType { // Special case: time.Time - t := rv.Interface().(time.Time) - str := t.Format(rfc2822) + t := rv.Interface().(time.Time).UTC() + str := t.Format(iso8601) jsonBytes, err_ := json.Marshal(str) if err_ != nil { *err = err_ diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/wire/reflect_test.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/wire/reflect_test.go index bfaaa3bee2baa500bc1f6b13984230ad9908af7b..2af5d8a5e5f1fe36c7d7e4f8f8594fda5f747221 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/wire/reflect_test.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/wire/reflect_test.go @@ -51,6 +51,7 @@ var _ = RegisterInterface( ConcreteType{&Viper{}, AnimalTypeViper}, ) +// TODO: add assertions here ... func TestAnimalInterface(t *testing.T) { var foo Animal @@ -100,7 +101,7 @@ func constructBasic() interface{} { SimpleStruct{ String: "String", Bytes: []byte("Bytes"), - Time: time.Unix(123, 0), + Time: time.Unix(123, 456789999), }, } return cat @@ -118,8 +119,8 @@ func validateBasic(o interface{}, t *testing.T) { if string(cat.Bytes) != "Bytes" { t.Errorf("Expected cat.Bytes == 'Bytes', got %X", cat.Bytes) } - if cat.Time.Unix() != 123 { - t.Errorf("Expected cat.Time == 'Unix(123)', got %v", cat.Time) + if cat.Time.UnixNano() != 123456000000 { // Only milliseconds + t.Errorf("Expected cat.Time.UnixNano() == 123456000000, got %v", cat.Time.UnixNano()) } } diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/wire/time.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/wire/time.go index c4a573345e6345d7a1bbd1ab63e12ef7681a9598..b59ea396920148854744a6bad4ee2f95909994be 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/wire/time.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/wire/time.go @@ -3,15 +3,25 @@ package wire import ( "io" "time" + + . "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/common" ) -// Time +/* +Writes nanoseconds since epoch but with millisecond precision. +This is to ease compatibility with Javascript etc. +*/ func WriteTime(t time.Time, w io.Writer, n *int64, err *error) { - WriteInt64(t.UnixNano(), w, n, err) + nanosecs := t.UnixNano() + millisecs := nanosecs / 1000000 + WriteInt64(millisecs*1000000, w, n, err) } func ReadTime(r io.Reader, n *int64, err *error) time.Time { t := ReadInt64(r, n, err) + if t%1000000 != 0 { + PanicSanity("Time cannot have sub-millisecond precision") + } return time.Unix(0, t) } diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/wire/version.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/wire/version.go new file mode 100644 index 0000000000000000000000000000000000000000..58953255f86b075c6e088945a8c2bc1e61d9b103 --- /dev/null +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/wire/version.go @@ -0,0 +1,3 @@ +package wire + +const Version = "0.5.0" diff --git a/Godeps/_workspace/src/github.com/tendermint/tendermint/wire/binary.go b/Godeps/_workspace/src/github.com/tendermint/tendermint/wire/wire.go similarity index 97% rename from Godeps/_workspace/src/github.com/tendermint/tendermint/wire/binary.go rename to Godeps/_workspace/src/github.com/tendermint/tendermint/wire/wire.go index 6584558c64c01ba4ae4161fe965a5d1e863aea1a..9054fdb6c6c9f89973f3b1b5a450c6609452fa1c 100644 --- a/Godeps/_workspace/src/github.com/tendermint/tendermint/wire/binary.go +++ b/Godeps/_workspace/src/github.com/tendermint/tendermint/wire/wire.go @@ -71,6 +71,7 @@ func ReadJSONPtr(o interface{}, bytes []byte, err *error) interface{} { return ReadJSONObjectPtr(o, object, err) } +// o is the ultimate destination, object is the result of json unmarshal func ReadJSONObject(o interface{}, object interface{}, err *error) interface{} { rv, rt := reflect.ValueOf(o), reflect.TypeOf(o) if rv.Kind() == reflect.Ptr { diff --git a/Godeps/_workspace/src/golang.org/x/net/context/ctxhttp/cancelreq.go b/Godeps/_workspace/src/golang.org/x/net/context/ctxhttp/cancelreq.go new file mode 100644 index 0000000000000000000000000000000000000000..48610e3627701c05e1cbf8e12db219af43cbd108 --- /dev/null +++ b/Godeps/_workspace/src/golang.org/x/net/context/ctxhttp/cancelreq.go @@ -0,0 +1,18 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build go1.5 + +package ctxhttp + +import "net/http" + +func canceler(client *http.Client, req *http.Request) func() { + ch := make(chan struct{}) + req.Cancel = ch + + return func() { + close(ch) + } +} diff --git a/Godeps/_workspace/src/golang.org/x/net/context/ctxhttp/cancelreq_go14.go b/Godeps/_workspace/src/golang.org/x/net/context/ctxhttp/cancelreq_go14.go new file mode 100644 index 0000000000000000000000000000000000000000..56bcbadb85fcc2a69db540797f41511cf16e5a6d --- /dev/null +++ b/Godeps/_workspace/src/golang.org/x/net/context/ctxhttp/cancelreq_go14.go @@ -0,0 +1,23 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build !go1.5 + +package ctxhttp + +import "net/http" + +type requestCanceler interface { + CancelRequest(*http.Request) +} + +func canceler(client *http.Client, req *http.Request) func() { + rc, ok := client.Transport.(requestCanceler) + if !ok { + return func() {} + } + return func() { + rc.CancelRequest(req) + } +} diff --git a/Godeps/_workspace/src/golang.org/x/net/context/ctxhttp/ctxhttp.go b/Godeps/_workspace/src/golang.org/x/net/context/ctxhttp/ctxhttp.go new file mode 100644 index 0000000000000000000000000000000000000000..0e3c1ebfe17f2fa98d633ee0f7f08cca862a1b19 --- /dev/null +++ b/Godeps/_workspace/src/golang.org/x/net/context/ctxhttp/ctxhttp.go @@ -0,0 +1,79 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package ctxhttp provides helper functions for performing context-aware HTTP requests. +package ctxhttp + +import ( + "io" + "net/http" + "net/url" + "strings" + + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/golang.org/x/net/context" +) + +// Do sends an HTTP request with the provided http.Client and returns an HTTP response. +// If the client is nil, http.DefaultClient is used. +// If the context is canceled or times out, ctx.Err() will be returned. +func Do(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) { + if client == nil { + client = http.DefaultClient + } + + // Request cancelation changed in Go 1.5, see cancelreq.go and cancelreq_go14.go. + cancel := canceler(client, req) + + type responseAndError struct { + resp *http.Response + err error + } + result := make(chan responseAndError, 1) + + go func() { + resp, err := client.Do(req) + result <- responseAndError{resp, err} + }() + + select { + case <-ctx.Done(): + cancel() + return nil, ctx.Err() + case r := <-result: + return r.resp, r.err + } +} + +// Get issues a GET request via the Do function. +func Get(ctx context.Context, client *http.Client, url string) (*http.Response, error) { + req, err := http.NewRequest("GET", url, nil) + if err != nil { + return nil, err + } + return Do(ctx, client, req) +} + +// Head issues a HEAD request via the Do function. +func Head(ctx context.Context, client *http.Client, url string) (*http.Response, error) { + req, err := http.NewRequest("HEAD", url, nil) + if err != nil { + return nil, err + } + return Do(ctx, client, req) +} + +// Post issues a POST request via the Do function. +func Post(ctx context.Context, client *http.Client, url string, bodyType string, body io.Reader) (*http.Response, error) { + req, err := http.NewRequest("POST", url, body) + if err != nil { + return nil, err + } + req.Header.Set("Content-Type", bodyType) + return Do(ctx, client, req) +} + +// PostForm issues a POST request via the Do function. +func PostForm(ctx context.Context, client *http.Client, url string, data url.Values) (*http.Response, error) { + return Post(ctx, client, url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode())) +} diff --git a/Godeps/_workspace/src/golang.org/x/net/context/ctxhttp/ctxhttp_test.go b/Godeps/_workspace/src/golang.org/x/net/context/ctxhttp/ctxhttp_test.go new file mode 100644 index 0000000000000000000000000000000000000000..a02a2a97b6248c99260c7aed855d46c19e7d331f --- /dev/null +++ b/Godeps/_workspace/src/golang.org/x/net/context/ctxhttp/ctxhttp_test.go @@ -0,0 +1,72 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package ctxhttp + +import ( + "io/ioutil" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/golang.org/x/net/context" +) + +const ( + requestDuration = 100 * time.Millisecond + requestBody = "ok" +) + +func TestNoTimeout(t *testing.T) { + ctx := context.Background() + resp, err := doRequest(ctx) + + if resp == nil || err != nil { + t.Fatalf("error received from client: %v %v", err, resp) + } +} +func TestCancel(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + go func() { + time.Sleep(requestDuration / 2) + cancel() + }() + + resp, err := doRequest(ctx) + + if resp != nil || err == nil { + t.Fatalf("expected error, didn't get one. resp: %v", resp) + } + if err != ctx.Err() { + t.Fatalf("expected error from context but got: %v", err) + } +} + +func TestCancelAfterRequest(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + + resp, err := doRequest(ctx) + + // Cancel before reading the body. + // Request.Body should still be readable after the context is canceled. + cancel() + + b, err := ioutil.ReadAll(resp.Body) + if err != nil || string(b) != requestBody { + t.Fatalf("could not read body: %q %v", b, err) + } +} + +func doRequest(ctx context.Context) (*http.Response, error) { + var okHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + time.Sleep(requestDuration) + w.Write([]byte(requestBody)) + }) + + serv := httptest.NewServer(okHandler) + defer serv.Close() + + return Get(ctx, nil, serv.URL) +} diff --git a/Godeps/_workspace/src/gopkg.in/bluesuncorp/validator.v5/examples/simple.go b/Godeps/_workspace/src/gopkg.in/bluesuncorp/validator.v5/examples/simple.go new file mode 100644 index 0000000000000000000000000000000000000000..c36bd6868f5b65304f232a1902f2105ea86f7344 --- /dev/null +++ b/Godeps/_workspace/src/gopkg.in/bluesuncorp/validator.v5/examples/simple.go @@ -0,0 +1,85 @@ +package main + +import ( + "fmt" + + "gopkg.in/go-playground/validator.v5" +) + +// User contains user information +type User struct { + FirstName string `validate:"required"` + LastName string `validate:"required"` + Age uint8 `validate:"gte=0,lte=130"` + Email string `validate:"required,email"` + FavouriteColor string `validate:"hexcolor|rgb|rgba"` + Addresses []*Address `validate:"required,dive,required"` // a person can have a home and cottage... +} + +// Address houses a users address information +type Address struct { + Street string `validate:"required"` + City string `validate:"required"` + Planet string `validate:"required"` + Phone string `validate:"required"` +} + +var validate *validator.Validate + +func main() { + + validate = validator.New("validate", validator.BakedInValidators) + + address := &Address{ + Street: "Eavesdown Docks", + Planet: "Persphone", + Phone: "none", + } + + user := &User{ + FirstName: "Badger", + LastName: "Smith", + Age: 135, + Email: "Badger.Smith@gmail.com", + FavouriteColor: "#000", + Addresses: []*Address{address}, + } + + // returns nil or *StructErrors + errs := validate.Struct(user) + + if errs != nil { + + // err will be of type *FieldError + err := errs.Errors["Age"] + fmt.Println(err.Error()) // output: Field validation for "Age" failed on the "lte" tag + fmt.Println(err.Field) // output: Age + fmt.Println(err.Tag) // output: lte + fmt.Println(err.Kind) // output: uint8 + fmt.Println(err.Type) // output: uint8 + fmt.Println(err.Param) // output: 130 + fmt.Println(err.Value) // output: 135 + + // or if you prefer you can use the Flatten function + // NOTE: I find this usefull when using a more hard static approach of checking field errors. + // The above, is best for passing to some generic code to say parse the errors. i.e. I pass errs + // to a routine which loops through the errors, creates and translates the error message into the + // users locale and returns a map of map[string]string // field and error which I then use + // within the HTML rendering. + + flat := errs.Flatten() + fmt.Println(flat) // output: map[Age:Field validation for "Age" failed on the "lte" tag Addresses[0].Address.City:Field validation for "City" failed on the "required" tag] + err = flat["Addresses[0].Address.City"] + fmt.Println(err.Field) // output: City + fmt.Println(err.Tag) // output: required + fmt.Println(err.Kind) // output: string + fmt.Println(err.Type) // output: string + fmt.Println(err.Param) // output: + fmt.Println(err.Value) // output: + + // from here you can create your own error messages in whatever language you wish + return + } + + // save user to database +} diff --git a/circle.yml b/circle.yml index bfa6b4f3983364eb0afe4adf50d176d773b7fb80..9700be15a7e015139a28c5696dfabaef1a942cf6 100644 --- a/circle.yml +++ b/circle.yml @@ -8,7 +8,7 @@ machine: dependencies: pre: - - sudo curl -L -o /usr/bin/docker 'http://s3-external-1.amazonaws.com/circle-downloads/docker-1.6.0-circleci'; chmod 0755 /usr/bin/docker; true + - sudo curl -L -o /usr/bin/docker 'http://s3-external-1.amazonaws.com/circle-downloads/docker-1.8.2-circleci' - sudo service docker start - "sudo apt-get update && sudo apt-get install -y libgmp3-dev" @@ -20,3 +20,11 @@ dependencies: test: override: - go test -v ./... + +deployment: + master: + branch: master + commands: + - docker login -e $DOCKER_EMAIL -u $DOCKER_USER -p $DOCKER_PASS quay.io + - DOCKER/build.sh + - docker push quay.io/eris/erisdb diff --git a/circle.yml~ b/circle.yml~ index db98814fad15c270dfc511080cb84043d584eb0e..268e14477dd4ab374a63facb52bef8ff47040daf 100644 --- a/circle.yml~ +++ b/circle.yml~ @@ -8,9 +8,8 @@ machine: dependencies: pre: - - sudo curl -L -o /usr/bin/docker 'http://s3-external-1.amazonaws.com/circle-downloads/docker-1.6.0-circleci'; chmod 0755 /usr/bin/docker; true + - sudo curl -L -o /usr/bin/docker 'http://s3-external-1.amazonaws.com/circle-downloads/docker-1.8.2-circleci'; chmod 0755 /usr/bin/docker; true - sudo service docker start - - docker login -e $DOCKER_EMAIL -u $DOCKER_USER -p $DOCKER_PASS - "sudo apt-get update && sudo apt-get install -y libgmp3-dev" override: @@ -26,11 +25,6 @@ deployment: master: branch: master commands: - - "export ERISDB_BUILD_BRANCH=$CIRCLE_BRANCH && DOCKER/build.sh" - - docker push eris/erisdb:latest - - docker push eris/erisdb:0.10 - develop: - branch: develop - commands: - - "export ERISDB_BUILD_BRANCH=$CIRCLE_BRANCH && DOCKER/build.sh" - - docker push eris/erisdb:develop + - docker login -e $DOCKER_EMAIL -u $DOCKER_USER -p $DOCKER_PASS quay.io + - DOCKER/build.sh + - docker push quay.io/eris/erisdb diff --git a/erisdb/erisdbss/http.go b/erisdb/erisdbss/http.go index 753b7f0ae47b2a8fdb25e5ca688b0d4270d953b3..bb52a0e34af5cfbaa484a04bfe7d92e25a10eead 100644 --- a/erisdb/erisdbss/http.go +++ b/erisdb/erisdbss/http.go @@ -5,7 +5,8 @@ import ( "encoding/json" "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/gin-gonic/gin" . "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/common" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/state" + stypes "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/state/types" + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/types" "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/wire" "github.com/eris-ltd/eris-db/server" "net/http" @@ -32,8 +33,8 @@ rpc_laddr = "" // TODO more stuff, like tendermint and server config files. Will probably // wait with this until the eris/EPM integration. type RequestData struct { - PrivValidator *state.PrivValidator `json:"priv_validator"` - Genesis *state.GenesisDoc `json:"genesis"` + PrivValidator *types.PrivValidator `json:"priv_validator"` + Genesis *stypes.GenesisDoc `json:"genesis"` MaxDuration uint `json:"max_duration"` } diff --git a/erisdb/erisdbss/server_manager.go b/erisdb/erisdbss/server_manager.go index 701e807112bf6c8e1ec75da26104dbac8592d1c3..5d25ef4ac9072b370b1a3eec25c15bad836f1faa 100644 --- a/erisdb/erisdbss/server_manager.go +++ b/erisdb/erisdbss/server_manager.go @@ -63,7 +63,7 @@ func (this *CmdProcess) Start(doneChan chan<- error) { log.Debug(text) if strings.Index(text, this.token) != -1 { log.Debug("Token found", "token", this.token) - go func(){ + go func() { for scanner.Scan() { text := scanner.Text() log.Debug(text) diff --git a/erisdb/event_cache.go b/erisdb/event_cache.go index b00f435dbe999b669a1f2a8d785a586789567176..81d4bca5d4394d8f852d4cefbfcec1b1c594f1fd 100644 --- a/erisdb/event_cache.go +++ b/erisdb/event_cache.go @@ -5,6 +5,8 @@ import ( ep "github.com/eris-ltd/eris-db/erisdb/pipe" "sync" "time" + + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/types" ) var ( @@ -90,7 +92,7 @@ func (this *EventSubscriptions) add(eventId string) (string, error) { } cache := newEventCache() _, errC := this.eventEmitter.Subscribe(subId, eventId, - func(evt interface{}) { + func(evt types.EventData) { cache.mtx.Lock() defer cache.mtx.Unlock() cache.events = append(cache.events, evt) diff --git a/erisdb/event_cache_test.go b/erisdb/event_cache_test.go index c1532adb07f3498f531c7c605381437d4e47711d..83410eae32ca251670dfceb615e8a64d8aed40c9 100644 --- a/erisdb/event_cache_test.go +++ b/erisdb/event_cache_test.go @@ -3,10 +3,12 @@ package erisdb import ( "encoding/hex" "fmt" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/stretchr/testify/assert" "runtime" "testing" "time" + + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/stretchr/testify/assert" + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/types" ) var mockInterval = 10 * time.Millisecond @@ -14,13 +16,13 @@ var mockInterval = 10 * time.Millisecond type mockSub struct { subId string eventId string - f func(interface{}) + f func(types.EventData) shutdown bool sdChan chan struct{} } // A mock event -func newMockSub(subId, eventId string, f func(interface{})) mockSub { +func newMockSub(subId, eventId string, f func(types.EventData)) mockSub { return mockSub{subId, eventId, f, false, make(chan struct{})} } @@ -32,7 +34,7 @@ func newMockEventEmitter() *mockEventEmitter { return &mockEventEmitter{make(map[string]mockSub)} } -func (this *mockEventEmitter) Subscribe(subId, eventId string, callback func(interface{})) (bool, error) { +func (this *mockEventEmitter) Subscribe(subId, eventId string, callback func(types.EventData)) (bool, error) { if _, ok := this.subs[subId]; ok { return false, nil } @@ -45,7 +47,7 @@ func (this *mockEventEmitter) Subscribe(subId, eventId string, callback func(int go func() { for { if !me.shutdown { - me.f(struct{}{}) + me.f(types.EventDataNewBlock{}) } else { return } diff --git a/erisdb/event_filters.go b/erisdb/event_filters.go index 757a1ccf00bd5e47a6b5611516de640ffb91aafe..0b8c6033fa58a072d8e50a76d3c3c33e25509b60 100644 --- a/erisdb/event_filters.go +++ b/erisdb/event_filters.go @@ -4,8 +4,8 @@ import ( "bytes" "encoding/hex" "fmt" - ep "github.com/eris-ltd/eris-db/erisdb/pipe" "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/types" + ep "github.com/eris-ltd/eris-db/erisdb/pipe" ) // Filter for account code. @@ -41,9 +41,9 @@ func (this *AccountCallTxHashFilter) Configure(fd *ep.FilterData) error { } func (this *AccountCallTxHashFilter) Match(v interface{}) bool { - emct, ok := v.(*types.EventMsgCall) + emct, ok := v.(*types.EventDataCall) if !ok { return false } return this.match(emct.TxID, this.value) -} \ No newline at end of file +} diff --git a/erisdb/methods.go b/erisdb/methods.go index 0609f69ead0322e3f19762fea210a0296808c12c..0b0a370eee5fdb224a8d6f52a686caef700c5ff4 100644 --- a/erisdb/methods.go +++ b/erisdb/methods.go @@ -42,7 +42,7 @@ const ( SIGN_TX = SERVICE_NAME + ".signTx" TRANSACT = SERVICE_NAME + ".transact" TRANSACT_AND_HOLD = SERVICE_NAME + ".transactAndHold" - SEND = SERVICE_NAME + ".send" + SEND = SERVICE_NAME + ".send" SEND_AND_HOLD = SERVICE_NAME + ".sendAndHold" TRANSACT_NAMEREG = SERVICE_NAME + ".transactNameReg" EVENT_SUBSCRIBE = SERVICE_NAME + ".eventSubscribe" // Events diff --git a/erisdb/pipe/accounts.go b/erisdb/pipe/accounts.go index 50ceab0222191997998e15394c47d4ebff1c7494..94dfbad9a9a2aa945f929cbf7cfc79e5cecdded4 100644 --- a/erisdb/pipe/accounts.go +++ b/erisdb/pipe/accounts.go @@ -48,10 +48,8 @@ func (this *accounts) GenPrivAccountFromKey(privKey []byte) (*account.PrivAccoun if len(privKey) != 64 { return nil, fmt.Errorf("Private key is not 64 bytes long.") } - pk := &[64]byte{} - copy(pk[:], privKey) - fmt.Printf("PK BYTES FROM ACCOUNTS: %x\n", pk) - pa := account.GenPrivAccountFromPrivKeyBytes(pk) + fmt.Printf("PK BYTES FROM ACCOUNTS: %x\n", privKey) + pa := account.GenPrivAccountFromPrivKeyBytes(privKey) return pa, nil } diff --git a/erisdb/pipe/consensus.go b/erisdb/pipe/consensus.go index 8f63b835f7ace13935f75e9ef6a0b25be2c7782d..2d5ecdf2489afb568500610d0237309357f92334 100644 --- a/erisdb/pipe/consensus.go +++ b/erisdb/pipe/consensus.go @@ -3,7 +3,7 @@ package pipe import ( cm "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/consensus" "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/p2p" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/state" + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/types" "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/wire" ) @@ -23,7 +23,7 @@ func (this *consensus) State() (*ConsensusState, error) { peerRoundStates := []string{} for _, peer := range this.p2pSwitch.Peers().List() { // TODO: clean this up? - peerState := peer.Data.Get(cm.PeerStateKey).(*cm.PeerState) + peerState := peer.Data.Get(types.PeerStateKey).(*cm.PeerState) peerRoundState := peerState.GetRoundState() peerRoundStateStr := peer.Key + ":" + string(wire.JSONBytes(peerRoundState)) peerRoundStates = append(peerRoundStates, peerRoundStateStr) @@ -34,16 +34,16 @@ func (this *consensus) State() (*ConsensusState, error) { // Get all validators. func (this *consensus) Validators() (*ValidatorList, error) { var blockHeight int - bondedValidators := make([]*state.Validator, 0) - unbondingValidators := make([]*state.Validator, 0) + bondedValidators := make([]*types.Validator, 0) + unbondingValidators := make([]*types.Validator, 0) s := this.consensusState.GetState() blockHeight = s.LastBlockHeight - s.BondedValidators.Iterate(func(index int, val *state.Validator) bool { + s.BondedValidators.Iterate(func(index int, val *types.Validator) bool { bondedValidators = append(bondedValidators, val) return false }) - s.UnbondingValidators.Iterate(func(index int, val *state.Validator) bool { + s.UnbondingValidators.Iterate(func(index int, val *types.Validator) bool { unbondingValidators = append(unbondingValidators, val) return false }) diff --git a/erisdb/pipe/events.go b/erisdb/pipe/events.go index 9171ea5146fe9f397c5b1e73f77e3171b8371a94..f2d15bdb6f16bd3a8ec3bfc0403411b3a3955129 100644 --- a/erisdb/pipe/events.go +++ b/erisdb/pipe/events.go @@ -2,6 +2,7 @@ package pipe import ( evts "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/events" + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/types" ) // TODO improve @@ -16,7 +17,7 @@ func newEvents(eventSwitch *evts.EventSwitch) *events { } // Subscribe to an event. -func (this *events) Subscribe(subId, event string, callback func(interface{})) (bool, error) { +func (this *events) Subscribe(subId, event string, callback func(types.EventData)) (bool, error) { this.eventSwitch.AddListenerForEvent(subId, event, callback) return true, nil } diff --git a/erisdb/pipe/namereg.go b/erisdb/pipe/namereg.go index 267f6be774b3ffe3f66cdb2f0ad7b4ae94c14fe2..1fe22dbb51b3df3a6abd9d2ac9b0d3a555d9bd83 100644 --- a/erisdb/pipe/namereg.go +++ b/erisdb/pipe/namereg.go @@ -56,7 +56,7 @@ func (this *namereg) Entry(key string) (*types.NameRegEntry, error) { return entry, nil } -func (this *namereg) Entries(filters []*FilterData) (*ctypes.ResponseListNames, error) { +func (this *namereg) Entries(filters []*FilterData) (*ctypes.ResultListNames, error) { var blockHeight int var names []*types.NameRegEntry state := this.consensusState.GetState() @@ -72,7 +72,7 @@ func (this *namereg) Entries(filters []*FilterData) (*ctypes.ResponseListNames, } return false }) - return &ctypes.ResponseListNames{blockHeight, names}, nil + return &ctypes.ResultListNames{blockHeight, names}, nil } // Filter for namereg name. This should not be used to get individual entries by name. diff --git a/erisdb/pipe/pipe.go b/erisdb/pipe/pipe.go index 6bfa2ff437b91ca4f205bef09d6f085ed6eea07e..e01a6788315261f6832c883a040c520d5d3d7dd9 100644 --- a/erisdb/pipe/pipe.go +++ b/erisdb/pipe/pipe.go @@ -46,13 +46,13 @@ type ( } EventEmitter interface { - Subscribe(subId, event string, callback func(interface{})) (bool, error) + Subscribe(subId, event string, callback func(types.EventData)) (bool, error) Unsubscribe(subId string) (bool, error) } NameReg interface { Entry(key string) (*types.NameRegEntry, error) - Entries([]*FilterData) (*ctypes.ResponseListNames, error) + Entries([]*FilterData) (*ctypes.ResultListNames, error) } Net interface { @@ -72,7 +72,7 @@ type ( Send(privKey, toAddress []byte, amount int64) (*Receipt, error) SendAndHold(privKey, toAddress []byte, amount int64) (*Receipt, error) Transact(privKey, address, data []byte, gasLimit, fee int64) (*Receipt, error) - TransactAndHold(privKey, address, data []byte, gasLimit, fee int64) (*types.EventMsgCall, error) + TransactAndHold(privKey, address, data []byte, gasLimit, fee int64) (*types.EventDataCall, error) TransactNameReg(privKey []byte, name, data string, amount, fee int64) (*Receipt, error) UnconfirmedTxs() (*UnconfirmedTxs, error) SignTx(tx types.Tx, privAccounts []*account.PrivAccount) (types.Tx, error) @@ -100,7 +100,7 @@ func NewPipe(tNode *node.Node) Pipe { namereg := newNamereg(tNode.ConsensusState()) net := newNetwork(tNode.Switch()) txs := newTransactor(tNode.EventSwitch(), tNode.ConsensusState(), tNode.MempoolReactor(), events) - + return &PipeImpl{ tNode, accounts, diff --git a/erisdb/pipe/transactor.go b/erisdb/pipe/transactor.go index 006e07fb114b64054423eda58846e05bea73bcfe..c406d9c66d775c77bcc54912dbac002f8f8d16cd 100644 --- a/erisdb/pipe/transactor.go +++ b/erisdb/pipe/transactor.go @@ -133,11 +133,9 @@ func (this *transactor) Transact(privKey, address, data []byte, gasLimit, fee in if len(privKey) != 64 { return nil, fmt.Errorf("Private key is not of the right length: %d\n", len(privKey)) } - pk := &[64]byte{} - copy(pk[:], privKey) this.txMtx.Lock() defer this.txMtx.Unlock() - pa := account.GenPrivAccountFromPrivKeyBytes(pk) + pa := account.GenPrivAccountFromPrivKeyBytes(privKey) cache := this.mempoolReactor.Mempool.GetCache() acc := cache.GetAccount(pa.Address) var sequence int @@ -159,7 +157,7 @@ func (this *transactor) Transact(privKey, address, data []byte, gasLimit, fee in Fee: fee, Data: data, } - + // Got ourselves a tx. txS, errS := this.SignTx(tx, []*account.PrivAccount{pa}) if errS != nil { @@ -168,7 +166,7 @@ func (this *transactor) Transact(privKey, address, data []byte, gasLimit, fee in return this.BroadcastTx(txS) } -func (this *transactor) TransactAndHold(privKey, address, data []byte, gasLimit, fee int64) (*types.EventMsgCall, error) { +func (this *transactor) TransactAndHold(privKey, address, data []byte, gasLimit, fee int64) (*types.EventDataCall, error) { rec, tErr := this.Transact(privKey, address, data, gasLimit, fee) if tErr != nil { return nil, tErr @@ -179,10 +177,10 @@ func (this *transactor) TransactAndHold(privKey, address, data []byte, gasLimit, } else { addr = address } - wc := make(chan *types.EventMsgCall) + wc := make(chan *types.EventDataCall) subId := fmt.Sprintf("%X", rec.TxHash) - this.eventEmitter.Subscribe(subId, types.EventStringAccCall(addr), func(evt interface{}) { - event := evt.(types.EventMsgCall) + this.eventEmitter.Subscribe(subId, types.EventStringAccCall(addr), func(evt types.EventData) { + event := evt.(types.EventDataCall) if bytes.Equal(event.TxID, rec.TxHash) { wc <- &event } @@ -191,7 +189,7 @@ func (this *transactor) TransactAndHold(privKey, address, data []byte, gasLimit, timer := time.NewTimer(300 * time.Second) toChan := timer.C - var ret *types.EventMsgCall + var ret *types.EventDataCall var rErr error select { @@ -218,16 +216,16 @@ func (this *transactor) Send(privKey, toAddress []byte, amount int64) (*Receipt, } else { toAddr = toAddress } - + if len(privKey) != 64 { return nil, fmt.Errorf("Private key is not of the right length: %d\n", len(privKey)) } - + pk := &[64]byte{} copy(pk[:], privKey) this.txMtx.Lock() defer this.txMtx.Unlock() - pa := account.GenPrivAccountFromPrivKeyBytes(pk) + pa := account.GenPrivAccountFromPrivKeyBytes(privKey) cache := this.mempoolReactor.Mempool.GetCache() acc := cache.GetAccount(pa.Address) var sequence int @@ -236,22 +234,22 @@ func (this *transactor) Send(privKey, toAddress []byte, amount int64) (*Receipt, } else { sequence = acc.Sequence + 1 } - + tx := types.NewSendTx() - + txInput := &types.TxInput{ Address: pa.Address, Amount: amount, Sequence: sequence, PubKey: pa.PubKey, } - + tx.Inputs = append(tx.Inputs, txInput) - + txOutput := &types.TxOutput{toAddr, amount} - - tx.Outputs = append(tx.Outputs, txOutput); - + + tx.Outputs = append(tx.Outputs, txOutput) + // Got ourselves a tx. txS, errS := this.SignTx(tx, []*account.PrivAccount{pa}) if errS != nil { @@ -265,13 +263,14 @@ func (this *transactor) SendAndHold(privKey, toAddress []byte, amount int64) (*R if tErr != nil { return nil, tErr } - + wc := make(chan *types.SendTx) subId := fmt.Sprintf("%X", rec.TxHash) - - this.eventEmitter.Subscribe(subId, types.EventStringAccOutput(toAddress), func(evt interface{}) { - event := evt.(*types.SendTx) - wc <- event + + this.eventEmitter.Subscribe(subId, types.EventStringAccOutput(toAddress), func(evt types.EventData) { + event := evt.(types.EventDataTx) + tx := event.Tx.(*types.SendTx) + wc <- tx }) timer := time.NewTimer(300 * time.Second) @@ -279,10 +278,7 @@ func (this *transactor) SendAndHold(privKey, toAddress []byte, amount int64) (*R var rErr error - // FOR NOW - pk := &[64]byte{} - copy(pk[:], privKey) - pa := account.GenPrivAccountFromPrivKeyBytes(pk) + pa := account.GenPrivAccountFromPrivKeyBytes(privKey) select { case <-toChan: @@ -302,11 +298,9 @@ func (this *transactor) TransactNameReg(privKey []byte, name, data string, amoun if len(privKey) != 64 { return nil, fmt.Errorf("Private key is not of the right length: %d\n", len(privKey)) } - pk := &[64]byte{} - copy(pk[:], privKey) this.txMtx.Lock() defer this.txMtx.Unlock() - pa := account.GenPrivAccountFromPrivKeyBytes(pk) + pa := account.GenPrivAccountFromPrivKeyBytes(privKey) cache := this.mempoolReactor.Mempool.GetCache() acc := cache.GetAccount(pa.Address) var sequence int diff --git a/erisdb/pipe/types.go b/erisdb/pipe/types.go index d74271289896c716a0402439c7882c40ed64f5da..ea8e6fa96ad9677e50c69edced594bfd07dde2f6 100644 --- a/erisdb/pipe/types.go +++ b/erisdb/pipe/types.go @@ -3,8 +3,6 @@ package pipe import ( "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/account" csus "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/consensus" - ctypes "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/consensus/types" - sm "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/state" "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/types" ) @@ -64,20 +62,20 @@ type ( // ConsensusState ConsensusState struct { - Height int `json:"height"` - Round int `json:"round"` - Step uint8 `json:"step"` - StartTime string `json:"start_time"` - CommitTime string `json:"commit_time"` - Validators []*sm.Validator `json:"validators"` - Proposal *ctypes.Proposal `json:"proposal"` + Height int `json:"height"` + Round int `json:"round"` + Step uint8 `json:"step"` + StartTime string `json:"start_time"` + CommitTime string `json:"commit_time"` + Validators []*types.Validator `json:"validators"` + Proposal *types.Proposal `json:"proposal"` } // Validators ValidatorList struct { - BlockHeight int `json:"block_height"` - BondedValidators []*sm.Validator `json:"bonded_validators"` - UnbondingValidators []*sm.Validator `json:"unbonding_validators"` + BlockHeight int `json:"block_height"` + BondedValidators []*types.Validator `json:"bonded_validators"` + UnbondingValidators []*types.Validator `json:"unbonding_validators"` } // *********************************** Events *********************************** diff --git a/erisdb/restServer.go b/erisdb/restServer.go index e9131b0ec3a5d73afba64d81e201851ecf62c6c4..5585d572559fc2e1c8caebad3889167939df25c7 100644 --- a/erisdb/restServer.go +++ b/erisdb/restServer.go @@ -424,9 +424,9 @@ func (this *RestServer) handleCallCode(c *gin.Context) { } func (this *RestServer) handleTransact(c *gin.Context) { - + _, hold := c.Get("hold") - + param := &TransactParam{} errD := this.codec.Decode(param, c.Request.Body) if errD != nil { @@ -537,7 +537,7 @@ func parseTxModifier(c *gin.Context) { hold := c.Query("hold") if hold == "true" { c.Set("hold", true) - } else if (hold != "") { + } else if hold != "" { if hold != "false" { c.Writer.WriteHeader(400) c.Writer.Write([]byte("tx hold must be either 'true' or 'false', found: " + hold)) diff --git a/erisdb/serve.go b/erisdb/serve.go index 7700315ce91fd92862c300323a9ab8c38a0e634f..cab5a49f555d3768432af66b857cb6d0c8606b4d 100644 --- a/erisdb/serve.go +++ b/erisdb/serve.go @@ -82,7 +82,7 @@ func ServeErisDB(workDir string) (*server.ServeProcess, error) { func startNode(nd *node.Node, ready chan struct{}, shutDown <-chan struct{}) { laddr := tmConfig.GetString("node_laddr") if laddr != "" { - l := p2p.NewDefaultListener("tcp", laddr, false) + l := p2p.NewDefaultListener("tcp", laddr) nd.AddListener(l) } diff --git a/erisdb/wsService.go b/erisdb/wsService.go index bd7414c4d17c0606aabf874ff094b08de0329d01..490d284d3e569289d534852a01f30ddc3bee6c8b 100644 --- a/erisdb/wsService.go +++ b/erisdb/wsService.go @@ -6,6 +6,8 @@ import ( ep "github.com/eris-ltd/eris-db/erisdb/pipe" rpc "github.com/eris-ltd/eris-db/rpc" "github.com/eris-ltd/eris-db/server" + + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/types" ) // Used for ErisDb. Implements WebSocketService. @@ -101,7 +103,7 @@ func (this *ErisDbWsService) EventSubscribe(request *rpc.RPCRequest, requester i if errSID != nil { return nil, rpc.INTERNAL_ERROR, errSID } - callback := func(ret interface{}) { + callback := func(ret types.EventData) { writeErr := this.writeResponse(subId, ret, session) if writeErr != nil { this.pipe.Events().Unsubscribe(subId) diff --git a/server/websocket.go b/server/websocket.go index 377de80ebe01471373abe35263580c1521f0eb1a..b5d4b4caae74308238f48a5b9ba9ea4f25d25e51 100644 --- a/server/websocket.go +++ b/server/websocket.go @@ -223,14 +223,14 @@ func (this *WSSession) readPump() { this.writeCloseChan <- struct{}{} return } - + if msgType != websocket.TextMessage { log.Info("Receiving non text-message from client, closing.") this.writeCloseChan <- struct{}{} return } - - go func(){ + + go func() { // Process the request. this.service.Process(msg, this) }() @@ -274,16 +274,16 @@ func (this *WSSession) writePump() { } case <-this.writeCloseChan: return - // Ticker run out. Time for another ping message. - /* - case <-ticker.C: - if err := this.write(websocket.PingMessage, []byte{}); err != nil { - log.Debug("Failed to write ping message to socket. Closing.") - return - } + // Ticker run out. Time for another ping message. + /* + case <-ticker.C: + if err := this.write(websocket.PingMessage, []byte{}); err != nil { + log.Debug("Failed to write ping message to socket. Closing.") + return + } */ } - + } } diff --git a/test/mock/mock_web_api_test.go b/test/mock/mock_web_api_test.go index 17f636305561bde208000d0a9adc295558695c48..084c85a889522fff16d1265e3d3a3c492cfbb3e7 100644 --- a/test/mock/mock_web_api_test.go +++ b/test/mock/mock_web_api_test.go @@ -180,7 +180,7 @@ func (this *MockSuite) TestGetNameRegEntry() { func (this *MockSuite) TestGetNameRegEntries() { resp := this.get("/namereg") - ret := &ctypes.ResponseListNames{} + ret := &ctypes.ResultListNames{} errD := this.codec.Decode(ret, resp.Body) this.NoError(errD) this.Equal(ret, this.testData.GetNameRegEntries.Output) diff --git a/test/mock/pipe.go b/test/mock/pipe.go index 59eac06e1e46618524d42340ccc310fe3035aad0..85aa484c7297a958110703bd8d47ad0ef092671b 100644 --- a/test/mock/pipe.go +++ b/test/mock/pipe.go @@ -1,11 +1,12 @@ package mock import ( + ep "github.com/eris-ltd/eris-db/erisdb/pipe" + td "github.com/eris-ltd/eris-db/test/testdata/testdata" + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/account" ctypes "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core/types" "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/types" - ep "github.com/eris-ltd/eris-db/erisdb/pipe" - td "github.com/eris-ltd/eris-db/test/testdata/testdata" ) // Base struct. @@ -156,7 +157,7 @@ type events struct { testData *td.TestData } -func (this *events) Subscribe(subId, event string, callback func(interface{})) (bool, error) { +func (this *events) Subscribe(subId, event string, callback func(types.EventData)) (bool, error) { return true, nil } @@ -173,7 +174,7 @@ func (this *namereg) Entry(key string) (*types.NameRegEntry, error) { return this.testData.GetNameRegEntry.Output, nil } -func (this *namereg) Entries(filters []*ep.FilterData) (*ctypes.ResponseListNames, error) { +func (this *namereg) Entries(filters []*ep.FilterData) (*ctypes.ResultListNames, error) { return this.testData.GetNameRegEntries.Output, nil } @@ -239,11 +240,10 @@ func (this *transactor) Transact(privKey, address, data []byte, gasLimit, fee in return this.testData.Transact.Output, nil } -func (this *transactor) TransactAndHold(privKey, address, data []byte, gasLimit, fee int64) (*types.EventMsgCall, error) { +func (this *transactor) TransactAndHold(privKey, address, data []byte, gasLimit, fee int64) (*types.EventDataCall, error) { return nil, nil } - func (this *transactor) Send(privKey, toAddress []byte, amount int64) (*ep.Receipt, error) { return nil, nil } diff --git a/test/server/ws_burst_test.go b/test/server/ws_burst_test.go index 129ddb7d1f908a44021aa8caa4a2e001b111a791..2d62401310e52cd5b3b523eec4466b2336e8b458 100644 --- a/test/server/ws_burst_test.go +++ b/test/server/ws_burst_test.go @@ -102,7 +102,7 @@ func wsClient(doneChan chan bool, errChan chan error) { i++ } client.Close() - time.Sleep(100*time.Millisecond) - + time.Sleep(100 * time.Millisecond) + doneChan <- true } diff --git a/test/testdata/filters/testdata_filters.go b/test/testdata/filters/testdata_filters.go index fd002c972ef6370ebe66ad9686392a8463a34e37..394a16a4e6d773f632cf39addf862c0923aa0392 100644 --- a/test/testdata/filters/testdata_filters.go +++ b/test/testdata/filters/testdata_filters.go @@ -1,9 +1,11 @@ package filters import ( - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/state" edb "github.com/eris-ltd/eris-db/erisdb" ep "github.com/eris-ltd/eris-db/erisdb/pipe" + + stypes "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/state/types" + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/types" ) var testDataJson = `{ @@ -269,10 +271,9 @@ var testDataJson = `{ var serverDuration uint = 100 type ( - ChainData struct { - PrivValidator *state.PrivValidator `json:"priv_validator"` - Genesis *state.GenesisDoc `json:"genesis"` + PrivValidator *types.PrivValidator `json:"priv_validator"` + Genesis *stypes.GenesisDoc `json:"genesis"` } GetAccountData struct { @@ -296,4 +297,4 @@ func LoadTestData() *TestData { panic(err) } return testData -} \ No newline at end of file +} diff --git a/test/testdata/helpers.go b/test/testdata/helpers.go index ee85fa23b3468cbe5c907b76e344e904d50df46a..c45516117701eccafdb7233182538209df2dc2e5 100644 --- a/test/testdata/helpers.go +++ b/test/testdata/helpers.go @@ -2,13 +2,15 @@ package testdata import ( "fmt" - "github.com/tendermint/tendermint/binary" - . "github.com/tendermint/tendermint/common" - "github.com/tendermint/tendermint/state" "github.com/eris-ltd/eris-db/files" "github.com/eris-ltd/eris-db/server" "os" "path" + + . "github.com/tendermint/tendermint/common" + stypes "github.com/tendermint/tendermint/state/types" + "github.com/tendermint/tendermint/types" + "github.com/tendermint/tendermint/wire" ) const TendermintConfigDefault = `# This is a TOML config file. @@ -23,7 +25,7 @@ node_laddr = "" rpc_laddr = "" ` -func CreateTempWorkDir(privValidator *state.PrivValidator, genesis *state.GenesisDoc, folderName string) (string, error) { +func CreateTempWorkDir(privValidator *types.PrivValidator, genesis *stypes.GenesisDoc, folderName string) (string, error) { workDir := path.Join(os.TempDir(), folderName) os.RemoveAll(workDir) @@ -68,7 +70,7 @@ func CreateTempWorkDir(privValidator *state.PrivValidator, genesis *state.Genesi return workDir, nil } -// Used to write json files using tendermints binary package. +// Used to write json files using tendermints wire package. func writeJSON(file string, v interface{}) error { var n int64 var errW error @@ -76,7 +78,7 @@ func writeJSON(file string, v interface{}) error { if errC != nil { return errC } - binary.WriteJSON(v, fo, &n, &errW) + wire.WriteJSON(v, fo, &n, &errW) if errW != nil { return errW } diff --git a/test/testdata/testdata/testdata.go b/test/testdata/testdata/testdata.go index f1bc9452156f10911829d79a4c698b8bde508cde..2b9ff63c0d9388b064de263fc2c48d6c847ec2e7 100644 --- a/test/testdata/testdata/testdata.go +++ b/test/testdata/testdata/testdata.go @@ -3,7 +3,7 @@ package testdata import ( "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/account" ctypes "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/rpc/core/types" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/state" + stypes "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/state/types" "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/types" edb "github.com/eris-ltd/eris-db/erisdb" ep "github.com/eris-ltd/eris-db/erisdb/pipe" @@ -222,7 +222,7 @@ var testDataJson = `{ "GetBlockchainInfo": { "output": { "chain_id": "my_tests", - "genesis_hash": "B901B9254D84CB509492E6C82245C54F1D84856D", + "genesis_hash": "0A8C453DB67BE52D32F9451212E8CE0E172AE56C", "latest_block_height": 0, "latest_block": null } @@ -234,7 +234,7 @@ var testDataJson = `{ }, "GetGenesisHash": { "output": { - "hash": "B901B9254D84CB509492E6C82245C54F1D84856D" + "hash": "0A8C453DB67BE52D32F9451212E8CE0E172AE56C" } }, "GetLatestBlockHeight": { @@ -367,7 +367,7 @@ var testDataJson = `{ "output": { "tx_hash": "BD5D35871770DB04726843A4C07A26CDE69EB860", "creates_contract": 1, - "contract_addr": "9FC1ECFCAE2A554D4D1A000D0D80F748E66359E3" + "contract_addr": "576439CD5C22EB6F3AE1AC1EC5101C5CE1E120D8" } }, "GetUnconfirmedTxs": { @@ -499,7 +499,7 @@ var testDataJson = `{ "input": { "filters": [] }, - "output": { + "output": [11, { "block_height": 1, "names":[ { "name": "testKey", @@ -507,7 +507,7 @@ var testDataJson = `{ "data": "testData", "expires": 250 } ] - } + }] } }` @@ -515,8 +515,8 @@ var serverDuration uint = 100 type ( ChainData struct { - PrivValidator *state.PrivValidator `json:"priv_validator"` - Genesis *state.GenesisDoc `json:"genesis"` + PrivValidator *types.PrivValidator `json:"priv_validator"` + Genesis *stypes.GenesisDoc `json:"genesis"` } GetAccountData struct { @@ -655,8 +655,8 @@ type ( } GetNameRegEntriesData struct { - Input *edb.FilterListParam `json:"input"` - Output *ctypes.ResponseListNames `json:"output"` + Input *edb.FilterListParam `json:"input"` + Output *ctypes.ResultListNames `json:"output"` } /* diff --git a/test/transacting/transacting_tes.go b/test/transacting/transacting_tes.go index 4d5717fc0e1f4bb6d8ed7072b2ffb8884990b5db..e7fa397b82a8d4a623bd22f6ef1eab3237a7d3eb 100644 --- a/test/transacting/transacting_tes.go +++ b/test/transacting/transacting_tes.go @@ -5,10 +5,12 @@ import ( "bytes" "fmt" "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/stretchr/testify/suite" - // "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/tendermint/types" + // "github.com/tendermint/tendermint/types" edb "github.com/eris-ltd/eris-db/erisdb" ess "github.com/eris-ltd/eris-db/erisdb/erisdbss" // ep "github.com/eris-ltd/eris-db/erisdb/pipe" + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/gin-gonic/gin" + "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/log15" "github.com/eris-ltd/eris-db/rpc" "github.com/eris-ltd/eris-db/server" td "github.com/eris-ltd/eris-db/test/testdata/testdata" @@ -16,10 +18,8 @@ import ( "net/http" "os" "path" - "testing" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/gin-gonic/gin" - "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/log15" "runtime" + "testing" ) func init() { @@ -136,4 +136,4 @@ func (this *TxSuite) postJson(endpoint string, v interface{}) *http.Response { func TestQuerySuite(t *testing.T) { suite.Run(t, &TxSuite{}) -} \ No newline at end of file +} diff --git a/test/web_api/query_test.go b/test/web_api/query_test.go index ae18061502a7608bb5d2fa419f3a6813bbeb76d5..3acb0a7ee4033d2c12ae1594a94ca9759af0761f 100644 --- a/test/web_api/query_test.go +++ b/test/web_api/query_test.go @@ -133,4 +133,4 @@ func generateQuery(fda []*ep.FilterData) string { func TestQuerySuite(t *testing.T) { suite.Run(t, &QuerySuite{}) -} \ No newline at end of file +} diff --git a/version/version.go b/version/version.go index 238a83e18c26e2bd6bc0d906ef827ef94781b506..ca329c6361dbe3cfd32aed25d7802674cb22e3bf 100644 --- a/version/version.go +++ b/version/version.go @@ -4,4 +4,4 @@ import ( ) -const Version = "0.11.6" \ No newline at end of file +const Version = "0.12.0"