From 5325bf6507ff34928a83193b128e26e4a33223e5 Mon Sep 17 00:00:00 2001 From: ca333 Date: Mon, 18 Feb 2019 00:05:24 +0100 Subject: [PATCH 001/390] add Makefile for rogue multiOS supported Makefile --- src/cc/Makefile_rogue | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 src/cc/Makefile_rogue diff --git a/src/cc/Makefile_rogue b/src/cc/Makefile_rogue new file mode 100644 index 000000000..7fb3f799f --- /dev/null +++ b/src/cc/Makefile_rogue @@ -0,0 +1,37 @@ +SHELL = /bin/sh +CC = gcc +CC_DARWIN = g++-6 +CC_WIN = x86_64-w64-mingw32-gcc-posix +CFLAGS_DARWIN = -DBUILD_ROGUE -std=c++11 -arch x86_64 -I../../depends/$(shell echo `../..//depends/config.guess`/include) -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -Wl,-undefined -Wl,dynamic_lookup -Wno-write-strings -shared -dynamiclib +CFLAGS = -Wno-write-strings -DBUILD_ROGUE -std=c++11 -I../../depends/$(shell echo `../..//depends/config.guess`/include) -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared +CFLAGS_WIN = -Wno-write-strings -DBUILD_ROGUE -std=c++11 -I../../depends/$(shell echo `../..//depends/config.guess`/include) -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared +DEBUGFLAGS = -O0 -D _DEBUG +RELEASEFLAGS = -O2 -D NDEBUG -combine -fwhole-program +$(info $(OS)) +OS := $(shell uname -s) +$(info $(OS)) +TARGET = librogue.so +TARGET_DARWIN = librogue.dylib +TARGET_WIN = librogue.dll +SOURCES = cclib.cpp +#HEADERS = $(shell echo ../cryptoconditions/include/*.h) -I/usr/local/Cellar/gcc\@6/6.4.0_2/include/c++/6.4.0/ + +all: $(TARGET) + +$(TARGET): $(SOURCES) + $(info Building cclib to src/) +ifeq ($(OS),Darwin) + $(CC_DARWIN) $(CFLAGS_DARWIN) $(DEBUGFLAGS) -o $(TARGET_DARWIN) -c $(SOURCES) -lncurses + cp $(TARGET_DARWIN) ../libcc.dylib +else ifeq ($(OS),Linux) + $(CC) $(CFLAGS) $(DEBUGFLAGS) -o $(TARGET) -c $(SOURCES) -lncurses + cp $(TARGET) ../libcc.so +#else ifeq ($(WIN_HOST),True) - todo: pass ENV var from build.sh if WIN host +else + $(info WINDOWS) + $(CC_WIN) $(CFLAGS_WIN) $(DEBUGFLAGS) -o $(TARGET_WIN) -c $(SOURCES) -lncurses + cp $(TARGET_WIN) ../libcc.dll +endif + +clean: + rm -rf $(TARGET) From 9eb16504de6a35e5a31792954cb266bf96d37912 Mon Sep 17 00:00:00 2001 From: ca333 Date: Mon, 18 Feb 2019 00:08:03 +0100 Subject: [PATCH 002/390] update makerogue --- src/cc/makerogue | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/cc/makerogue b/src/cc/makerogue index 249e646f5..3b47638e9 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -1,8 +1,5 @@ #!/bin/sh cd rogue; -./configure # only need this first time +./configure make; cd .. -gcc -Wno-write-strings -DBUILD_ROGUE -std=c++11 -I../../depends/$(shell echo `../..//depends/config.guess`/include) -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -o librogue.so -c cclib.cpp -#gcc -std=c++11 -fPIC -shared -o librogue.so cclib.o rogue/rogue.so -cp librogue.so ../libcc.so - +make -f Makefile_rogue From c5b8640d9dde49a4b5b7706c545c1afb4eebb7ce Mon Sep 17 00:00:00 2001 From: ca333 Date: Mon, 18 Feb 2019 00:15:35 +0100 Subject: [PATCH 003/390] update OSX makefile --- zcutil/build-mac.sh | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/zcutil/build-mac.sh b/zcutil/build-mac.sh index a3619111f..df4efd05f 100755 --- a/zcutil/build-mac.sh +++ b/zcutil/build-mac.sh @@ -47,14 +47,7 @@ make "$@" -C ./depends/ V=1 NO_QT=1 NO_PROTON=1 WD=$PWD cd src/cc echo $PWD - -if make "$@"; then - echo CCLIB BUILD SUCCESSFUL -else - echo CCLIB BUILD FAILED - exit 1 -fi - +./makerogue cd $WD ./autogen.sh From cfa13caa4c1fe9cddc3c1b267d19e69da37257c1 Mon Sep 17 00:00:00 2001 From: ca333 Date: Mon, 18 Feb 2019 00:16:20 +0100 Subject: [PATCH 004/390] update makerogue --- src/cc/makerogue | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/cc/makerogue b/src/cc/makerogue index 3b47638e9..a38eab6a4 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -2,4 +2,10 @@ cd rogue; ./configure make; cd .. -make -f Makefile_rogue + +if make -f Makefile_rogue "$@"; then + echo ROGUE BUILD SUCCESSFUL +else + echo ROGUE BUILD FAILED + exit 1 +fi From 553b54b61cb32f41a86281dd26fabe2ecce1363f Mon Sep 17 00:00:00 2001 From: ca333 Date: Mon, 18 Feb 2019 12:13:11 +0100 Subject: [PATCH 005/390] roguefy makefile 'roguefy' for komodo linux makefile --- zcutil/build.sh | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/zcutil/build.sh b/zcutil/build.sh index dc312c8e8..7b452a1fc 100755 --- a/zcutil/build.sh +++ b/zcutil/build.sh @@ -103,20 +103,12 @@ ld -v HOST="$HOST" BUILD="$BUILD" NO_PROTON="$PROTON_ARG" "$MAKE" "$@" -C ./depends/ V=1 - #BUILD CCLIB WD=$PWD cd src/cc echo $PWD - -if make "$@"; then - echo CCLIB BUILD SUCCESSFUL -else - echo CCLIB BUILD FAILED - exit 1 -fi - +./makerogue cd $WD ./autogen.sh From 2d98e3a0e58072fac0eb866dfbcf2c36d3c8bc2e Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 00:39:21 -1100 Subject: [PATCH 006/390] Decode all ospreys --- src/cc/rogue_rpc.cpp | 69 ++++++++++++++++++++++++++++++++++---------- 1 file changed, 53 insertions(+), 16 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index c4a142ba1..ac63dea42 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1218,7 +1218,7 @@ UniValue rogue_setname(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { - CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,ind,errflag,dispflag,score,numvouts; CTransaction vintx; uint256 hashBlock; + CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,maxplayers,decoded=0,regslot,ind,errflag,dispflag,score,numvouts; CTransaction vintx; CPubKey pk; uint256 hashBlock,gametxid,tokenid,batontxid; int64_t buyin; std::vector playerdata,keystrokes; std::string symbol,pname; if ( (numvouts= tx.vout.size()) > 1 ) { scriptPubKey = tx.vout[numvouts-1].scriptPubKey; @@ -1229,30 +1229,67 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C funcid = script[1]; if ( (e= script[0]) == EVAL_TOKENS ) { - if ( script[1] == 'c' ) + if ( (funcid= rogue_highlanderopretdecode(gametxid,tokenid,regslot,pk,playerdata,symbol,pname,scriptPubKey)) == 0 ) { - e = EVAL_ROGUE; - funcid = 'Q'; - } - else if ( script[1] == 't' ) - { - e = EVAL_ROGUE; - funcid = 'Q'; - } else return eval->Invalid("illegal tokens funcid"); + if ( (funcid= rogue_registeropretdecode(gametxid,tokenid,playertxid,scriptPubKey)) == 0 ) + { + funcid = 'Q'; + fprintf(stderr,"ht.%d couldnt decode tokens opret\n",height); + } else e = EVAL_ROGUE, decoded = 1; + } else e = EVAL_ROGUE, decoded = 1; } if ( e == EVAL_ROGUE ) { + if ( decoded == 0 ) + { + switch ( funcid ) + { + case 'G': + if ( (funcid= rogue_newgameopreturndecode(buyin,maxplayers,scriptPubKey)) != 'G' ) + return eval->Invalid("couldnt decode newgame opret"); + // validate newgame tx + return(true); + break; + case 'R': + if ( (funcid= rogue_registeropretdecode(gametxid,tokenid,playertxid,scriptPubKey)) != 'R' ) + return eval->Invalid("couldnt decode register opret"); + break; + case 'K': + if ( (funcid= rogue_keystrokesopretdecode(gametxid,batontxid,pk,keystrokes,scriptPubKey)) != 'K' ) + return eval->Invalid("couldnt decode keystrokes opret"); + // validate keystrokes are from the correct pk. might need to add vin + return(true); + break; + case 'H': case 'Q': + if ( (f= rogue_highlanderopretdecode(gametxid,tokenid,regslot,pk,playerdata,symbol,pname,scriptPubKey)) != funcid ) + return eval->Invalid("couldnt decode H/Q opret"); + break; + default: + return eval->Invalid("illegal rogue non-decoded funcid"); + break; + } + } switch ( funcid ) { - case 'G': // newgame - case 'R': // register - case 'K': // keystrokes - case 'H': // win - case 'Q': // bailout - fprintf(stderr,"ht.%d rogue.(%c)\n",height,script[1]); + case 'R': + // validate register: within 60 blocks, not duplicate, etc. + return(true); + break; + case 'H': // fall through + case 'Q': + // make sure any playerdata is reproduced via replay + if ( funcid == 'Q' ) + { + // validate bailout constraints + } + else // 'H' + { + // validate winner constraints + } return(true); break; default: + fprintf(stderr,"ht.%d rogue.(%c)\n",height,script[1]); return eval->Invalid("illegal rogue funcid"); break; } From bec0d4935f6227df401270e3cd779f05657fd65b Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 00:39:56 -1100 Subject: [PATCH 007/390] Playertxid --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index ac63dea42..06d2b63b8 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1218,7 +1218,7 @@ UniValue rogue_setname(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { - CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,maxplayers,decoded=0,regslot,ind,errflag,dispflag,score,numvouts; CTransaction vintx; CPubKey pk; uint256 hashBlock,gametxid,tokenid,batontxid; int64_t buyin; std::vector playerdata,keystrokes; std::string symbol,pname; + CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,maxplayers,decoded=0,regslot,ind,errflag,dispflag,score,numvouts; CTransaction vintx; CPubKey pk; uint256 hashBlock,gametxid,tokenid,batontxid,playertxid; int64_t buyin; std::vector playerdata,keystrokes; std::string symbol,pname; if ( (numvouts= tx.vout.size()) > 1 ) { scriptPubKey = tx.vout[numvouts-1].scriptPubKey; From 0a59b078e15e4b4fb4a63caffc32531b6befb150 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 00:41:45 -1100 Subject: [PATCH 008/390] -proint --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index c4a142ba1..451b3bedb 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1249,7 +1249,7 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C case 'K': // keystrokes case 'H': // win case 'Q': // bailout - fprintf(stderr,"ht.%d rogue.(%c)\n",height,script[1]); + //fprintf(stderr,"ht.%d rogue.(%c)\n",height,script[1]); return(true); break; default: From 562e99fc96d91c8d796580ca3d688d34d8aa6884 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 00:51:21 -1100 Subject: [PATCH 009/390] Do total items --- src/cc/rogue/pack.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue/pack.c b/src/cc/rogue/pack.c index 392159fb5..4858afcdd 100644 --- a/src/cc/rogue/pack.c +++ b/src/cc/rogue/pack.c @@ -250,12 +250,16 @@ pack_char() int32_t num_packitems() { THING *list = pack; - int32_t type = 0,n = 0; + int32_t type = 0,n = 0,total = 0; for (; list != NULL; list = next(list)) { - if (!list->o_packch) + if ( list->o_packch != 0 ) + { n++; + total += list->o_count; + } } + fprintf(stderr,"total.%d vs %d inventory letters\n",total,n); return(n); } From 437af05de66e9e0822c1472eef335425bcb49883 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 00:53:23 -1100 Subject: [PATCH 010/390] Test --- src/cc/rogue/pack.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/pack.c b/src/cc/rogue/pack.c index 4858afcdd..8fc488389 100644 --- a/src/cc/rogue/pack.c +++ b/src/cc/rogue/pack.c @@ -259,7 +259,7 @@ int32_t num_packitems() total += list->o_count; } } - fprintf(stderr,"total.%d vs %d inventory letters\n",total,n); + fprintf(stderr,"total.%d vs %d inventory letters\n",total,n); sleep(1); return(n); } From dae06859f1803ad54733671a512c993cc34a5417 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 00:57:16 -1100 Subject: [PATCH 011/390] -sleep --- src/cc/rogue/pack.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/pack.c b/src/cc/rogue/pack.c index 8fc488389..39dc163b1 100644 --- a/src/cc/rogue/pack.c +++ b/src/cc/rogue/pack.c @@ -259,7 +259,7 @@ int32_t num_packitems() total += list->o_count; } } - fprintf(stderr,"total.%d vs %d inventory letters\n",total,n); sleep(1); + fprintf(stderr,"total.%d vs %d inventory letters\n",total,n); return(n); } From 040d3f8bfeebe26f46104c6000efe8352e03a39d Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 01:04:14 -1100 Subject: [PATCH 012/390] Print --- src/cc/rogue/pack.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue/pack.c b/src/cc/rogue/pack.c index 39dc163b1..1589d4d34 100644 --- a/src/cc/rogue/pack.c +++ b/src/cc/rogue/pack.c @@ -259,14 +259,17 @@ int32_t num_packitems() total += list->o_count; } } - fprintf(stderr,"total.%d vs %d inventory letters\n",total,n); + + char inv_temp[MAXSTR],str[MAXSTR]; + sprintf(str,"total.%d vs %d inventory letters\n",total,n); + add_line(rs,inv_temp,str); return(n); } bool inventory(struct rogue_state *rs,THING *list, int type) { - static char inv_temp[MAXSTR]; + char inv_temp[MAXSTR]; n_objs = 0; for (; list != NULL; list = next(list)) From e4c1ce63964d04147e20bcb4e4643a852ee38bbe Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 01:04:51 -1100 Subject: [PATCH 013/390] struct rogue_state *rs --- src/cc/rogue/pack.c | 4 ++-- src/cc/rogue/rogue.h | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue/pack.c b/src/cc/rogue/pack.c index 1589d4d34..0c967a85b 100644 --- a/src/cc/rogue/pack.c +++ b/src/cc/rogue/pack.c @@ -165,7 +165,7 @@ out: bool pack_room(struct rogue_state *rs,bool from_floor, THING *obj) { - inpack = num_packitems(); + inpack = num_packitems(rs); if (++inpack > MAXPACK) { if (!terse) @@ -247,7 +247,7 @@ pack_char() * the given type. */ -int32_t num_packitems() +int32_t num_packitems(struct rogue_state *rs) { THING *list = pack; int32_t type = 0,n = 0,total = 0; diff --git a/src/cc/rogue/rogue.h b/src/cc/rogue/rogue.h index 905a5ed36..515c1d44a 100644 --- a/src/cc/rogue/rogue.h +++ b/src/cc/rogue/rogue.h @@ -802,7 +802,7 @@ THING *leave_pack(struct rogue_state *rs,THING *obj, bool newobj, bool all); THING *new_item(void); THING *new_thing(struct rogue_state *rs); void end_line(struct rogue_state *rs); -int32_t num_packitems(); +int32_t num_packitems(struct rogue_state *rs); void runners(struct rogue_state *rs,int); void land(struct rogue_state *rs,int); From 63bad40a584d5a8c6206219103960ddd68f21e53 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 01:07:59 -1100 Subject: [PATCH 014/390] Fat --- src/cc/rogue/pack.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue/pack.c b/src/cc/rogue/pack.c index 0c967a85b..7e93dd759 100644 --- a/src/cc/rogue/pack.c +++ b/src/cc/rogue/pack.c @@ -260,9 +260,9 @@ int32_t num_packitems(struct rogue_state *rs) } } - char inv_temp[MAXSTR],str[MAXSTR]; + char str[MAXSTR]; sprintf(str,"total.%d vs %d inventory letters\n",total,n); - add_line(rs,inv_temp,str); + add_line(rs,"%s",str); return(n); } From f9b288af4768d7f4f75a44da02ab1067accbed0a Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 01:11:53 -1100 Subject: [PATCH 015/390] Total < strength*3 --- src/cc/rogue/pack.c | 74 ++++++++++++++++++++++----------------------- 1 file changed, 37 insertions(+), 37 deletions(-) diff --git a/src/cc/rogue/pack.c b/src/cc/rogue/pack.c index 7e93dd759..f8fc98175 100644 --- a/src/cc/rogue/pack.c +++ b/src/cc/rogue/pack.c @@ -157,37 +157,55 @@ out: } } +int32_t num_packitems(struct rogue_state *rs) +{ + THING *list = pack; + int32_t type = 0,n = 0,total = 0; + for (; list != NULL; list = next(list)) + { + if ( list->o_packch != 0 ) + { + n++; + total += list->o_count; + } + } + + char str[MAXSTR]; + sprintf(str,"strength*3 %d vs total.%d vs %d inventory letters\n",pstats.s_str*3,total,n); + add_line(rs,"%s",str); + if ( total > pstats.s_str*3 ) + return(MAXPACK); + return(n); +} + /* * pack_room: * See if there's room in the pack. If not, print out an * appropriate message */ -bool -pack_room(struct rogue_state *rs,bool from_floor, THING *obj) +bool pack_room(struct rogue_state *rs,bool from_floor, THING *obj) { inpack = num_packitems(rs); - if (++inpack > MAXPACK) + if ( ++inpack > MAXPACK ) { - if (!terse) - addmsg(rs,"there's "); - addmsg(rs,"no room"); - if (!terse) - addmsg(rs," in your pack"); - endmsg(rs); - if (from_floor) - move_msg(rs,obj); - inpack = MAXPACK; - return FALSE; + if (!terse) + addmsg(rs,"there's "); + addmsg(rs,"no room"); + if (!terse) + addmsg(rs," in your pack"); + endmsg(rs); + if (from_floor) + move_msg(rs,obj); + inpack = MAXPACK; + return FALSE; } //fprintf(stderr,"inpack.%d vs MAX.%d\n",inpack,MAXPACK), sleep(2); - - if (from_floor) + if ( from_floor != 0 ) { - detach(lvl_obj, obj); - mvaddch(hero.y, hero.x, floor_ch()); - chat(hero.y, hero.x) = (proom->r_flags & ISGONE) ? PASSAGE : FLOOR; + detach(lvl_obj, obj); + mvaddch(hero.y, hero.x, floor_ch()); + chat(hero.y, hero.x) = (proom->r_flags & ISGONE) ? PASSAGE : FLOOR; } - return TRUE; } @@ -247,24 +265,6 @@ pack_char() * the given type. */ -int32_t num_packitems(struct rogue_state *rs) -{ - THING *list = pack; - int32_t type = 0,n = 0,total = 0; - for (; list != NULL; list = next(list)) - { - if ( list->o_packch != 0 ) - { - n++; - total += list->o_count; - } - } - - char str[MAXSTR]; - sprintf(str,"total.%d vs %d inventory letters\n",total,n); - add_line(rs,"%s",str); - return(n); -} bool inventory(struct rogue_state *rs,THING *list, int type) From 575f5b4fd85d91560e6feb27a15934a6cbb51070 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 01:13:31 -1100 Subject: [PATCH 016/390] Disable --- src/cc/rogue_rpc.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 06d2b63b8..f4f45bf25 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1219,6 +1219,7 @@ UniValue rogue_setname(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,maxplayers,decoded=0,regslot,ind,errflag,dispflag,score,numvouts; CTransaction vintx; CPubKey pk; uint256 hashBlock,gametxid,tokenid,batontxid,playertxid; int64_t buyin; std::vector playerdata,keystrokes; std::string symbol,pname; + return(true); if ( (numvouts= tx.vout.size()) > 1 ) { scriptPubKey = tx.vout[numvouts-1].scriptPubKey; @@ -1289,7 +1290,7 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C return(true); break; default: - fprintf(stderr,"ht.%d rogue.(%c)\n",height,script[1]); + //fprintf(stderr,"ht.%d rogue.(%c)\n",height,script[1]); return eval->Invalid("illegal rogue funcid"); break; } From 54319f4bb65ce2ff948b23d58247f15ca515b0d8 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 01:20:28 -1100 Subject: [PATCH 017/390] Test opret validation --- src/cc/rogue_rpc.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 068a959cc..e5381a802 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1219,7 +1219,6 @@ UniValue rogue_setname(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,maxplayers,decoded=0,regslot,ind,errflag,dispflag,score,numvouts; CTransaction vintx; CPubKey pk; uint256 hashBlock,gametxid,tokenid,batontxid,playertxid; int64_t buyin; std::vector playerdata,keystrokes; std::string symbol,pname; - return(true); if ( (numvouts= tx.vout.size()) > 1 ) { scriptPubKey = tx.vout[numvouts-1].scriptPubKey; @@ -1254,6 +1253,7 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C case 'R': if ( (funcid= rogue_registeropretdecode(gametxid,tokenid,playertxid,scriptPubKey)) != 'R' ) return eval->Invalid("couldnt decode register opret"); + // validation is done below break; case 'K': if ( (funcid= rogue_keystrokesopretdecode(gametxid,batontxid,pk,keystrokes,scriptPubKey)) != 'K' ) @@ -1264,6 +1264,7 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C case 'H': case 'Q': if ( (f= rogue_highlanderopretdecode(gametxid,tokenid,regslot,pk,playerdata,symbol,pname,scriptPubKey)) != funcid ) return eval->Invalid("couldnt decode H/Q opret"); + // validation is done below break; default: return eval->Invalid("illegal rogue non-decoded funcid"); From c19cc548ad998128ea19628bcc9294e2746f8103 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 01:22:53 -1100 Subject: [PATCH 018/390] Height exemption --- src/cc/rogue_rpc.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index e5381a802..b1eb36e65 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1246,7 +1246,11 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C { case 'G': if ( (funcid= rogue_newgameopreturndecode(buyin,maxplayers,scriptPubKey)) != 'G' ) - return eval->Invalid("couldnt decode newgame opret"); + { + fprintf(stderr,"height.%d couldnt decode newgame opret\n",height); + if ( height > 20000 ) + return eval->Invalid("couldnt decode newgame opret"); + } // validate newgame tx return(true); break; From 53c35e3c89c1ea5358e75ebf9a6069b5fac6a424 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 01:26:56 -1100 Subject: [PATCH 019/390] Test --- src/cc/rogue_rpc.cpp | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index b1eb36e65..6e6da24f2 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1240,6 +1240,7 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C } if ( e == EVAL_ROGUE ) { + fprintf(stderr,"ht.%d rogue.(%c)\n",height,script[1]); if ( decoded == 0 ) { switch ( funcid ) @@ -1261,7 +1262,11 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C break; case 'K': if ( (funcid= rogue_keystrokesopretdecode(gametxid,batontxid,pk,keystrokes,scriptPubKey)) != 'K' ) - return eval->Invalid("couldnt decode keystrokes opret"); + { + fprintf(stderr,"height.%d couldnt decode keystrokes opret\n",height); + if ( height > 20000 ) + return eval->Invalid("couldnt decode keystrokes opret"); + } // validate keystrokes are from the correct pk. might need to add vin return(true); break; @@ -1286,7 +1291,6 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C return(true); break; default: - //fprintf(stderr,"ht.%d rogue.(%c)\n",height,script[1]); return eval->Invalid("illegal rogue funcid"); break; } From aa26fa0a69c7ba92ab3b2a0ade2c5adf8eac2300 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 01:30:05 -1100 Subject: [PATCH 020/390] Bypass all --- src/cc/rogue_rpc.cpp | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 6e6da24f2..994cbe319 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1257,7 +1257,11 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C break; case 'R': if ( (funcid= rogue_registeropretdecode(gametxid,tokenid,playertxid,scriptPubKey)) != 'R' ) - return eval->Invalid("couldnt decode register opret"); + { + fprintf(stderr,"height.%d couldnt decode register opret\n",height); + if ( height > 20000 ) + return eval->Invalid("couldnt decode register opret"); + } // validation is done below break; case 'K': @@ -1272,7 +1276,11 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C break; case 'H': case 'Q': if ( (f= rogue_highlanderopretdecode(gametxid,tokenid,regslot,pk,playerdata,symbol,pname,scriptPubKey)) != funcid ) - return eval->Invalid("couldnt decode H/Q opret"); + { + fprintf(stderr,"height.%d couldnt decode H/Q opret\n",height); + if ( height > 20000 ) + return eval->Invalid("couldnt decode H/Q opret"); + } // validation is done below break; default: From 535741426479fc5d01d35ef90b74ed6fba2b880c Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 01:35:21 -1100 Subject: [PATCH 021/390] Test --- src/cc/rogue_rpc.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 994cbe319..ef24489ba 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1234,7 +1234,9 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C if ( (funcid= rogue_registeropretdecode(gametxid,tokenid,playertxid,scriptPubKey)) == 0 ) { funcid = 'Q'; - fprintf(stderr,"ht.%d couldnt decode tokens opret\n",height); + fprintf(stderr,"ht.%d couldnt decode tokens opret (%c)\n",height,script[1]); + if ( height < 20000 ) + e = EVAL_ROGUE; } else e = EVAL_ROGUE, decoded = 1; } else e = EVAL_ROGUE, decoded = 1; } From 49d8a2aa5d9b6306776650cfa3e9e3442d1716e6 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 03:20:43 -1100 Subject: [PATCH 022/390] Disable --- src/cc/rogue/pack.c | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/cc/rogue/pack.c b/src/cc/rogue/pack.c index f8fc98175..f28ef891d 100644 --- a/src/cc/rogue/pack.c +++ b/src/cc/rogue/pack.c @@ -169,12 +169,14 @@ int32_t num_packitems(struct rogue_state *rs) total += list->o_count; } } - - char str[MAXSTR]; - sprintf(str,"strength*3 %d vs total.%d vs %d inventory letters\n",pstats.s_str*3,total,n); - add_line(rs,"%s",str); - if ( total > pstats.s_str*3 ) - return(MAXPACK); + if ( 0 ) // crashes playerinfo + { + char str[MAXSTR]; + sprintf(str,"strength*3 %d vs total.%d vs %d inventory letters\n",pstats.s_str*3,total,n); + add_line(rs,"%s",str); + if ( total > pstats.s_str*3 ) + return(MAXPACK); + } return(n); } From f5af7f465f635877aafcea1bc630016e4d86114f Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 03:23:15 -1100 Subject: [PATCH 023/390] Fix player info crash --- src/cc/rogue/pack.c | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/cc/rogue/pack.c b/src/cc/rogue/pack.c index f8fc98175..7fae5452a 100644 --- a/src/cc/rogue/pack.c +++ b/src/cc/rogue/pack.c @@ -169,10 +169,12 @@ int32_t num_packitems(struct rogue_state *rs) total += list->o_count; } } - - char str[MAXSTR]; - sprintf(str,"strength*3 %d vs total.%d vs %d inventory letters\n",pstats.s_str*3,total,n); - add_line(rs,"%s",str); + if ( 0 ) + { + char str[MAXSTR]; + sprintf(str,"strength*3 %d vs total.%d vs %d inventory letters\n",pstats.s_str*3,total,n); + add_line(rs,"%s",str); + } if ( total > pstats.s_str*3 ) return(MAXPACK); return(n); From a4f241718bdec6e7312a479037eba3ad40daa0f9 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 03:24:21 -1100 Subject: [PATCH 024/390] Test --- src/cc/rogue/pack.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue/pack.c b/src/cc/rogue/pack.c index f28ef891d..d482a8a52 100644 --- a/src/cc/rogue/pack.c +++ b/src/cc/rogue/pack.c @@ -169,14 +169,14 @@ int32_t num_packitems(struct rogue_state *rs) total += list->o_count; } } - if ( 0 ) // crashes playerinfo + if ( rs->guiflag != 0 ) { char str[MAXSTR]; sprintf(str,"strength*3 %d vs total.%d vs %d inventory letters\n",pstats.s_str*3,total,n); add_line(rs,"%s",str); - if ( total > pstats.s_str*3 ) - return(MAXPACK); } + if ( total > pstats.s_str*3 ) + return(MAXPACK); return(n); } From 8b35141984d4a25ed761bdf23fb40a1772145b5e Mon Sep 17 00:00:00 2001 From: ca333 Date: Mon, 18 Feb 2019 15:29:59 +0100 Subject: [PATCH 025/390] roguefy WIN makefile --- zcutil/build-win.sh | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/zcutil/build-win.sh b/zcutil/build-win.sh index 5c12893fa..ef0c09549 100755 --- a/zcutil/build-win.sh +++ b/zcutil/build-win.sh @@ -11,6 +11,12 @@ cd "$(dirname "$(readlink -f "$0")")/.." cd depends/ && make HOST=$HOST V=1 NO_QT=1 cd ../ +WD=$PWD +cd src/cc +echo $PWD +./makerogue +cd $WD + ./autogen.sh CONFIG_SITE=$PWD/depends/x86_64-w64-mingw32/share/config.site CXXFLAGS="-DPTW32_STATIC_LIB -DCURL_STATICLIB -DCURVE_ALT_BN128 -fopenmp -pthread" ./configure --prefix="${PREFIX}" --host=x86_64-w64-mingw32 --enable-static --disable-shared sed -i 's/-lboost_system-mt /-lboost_system-mt-s /' configure From cbe32599e4cb46c06a97f8dca6e6cdcd96492573 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 03:35:29 -1100 Subject: [PATCH 026/390] Conditional validate --- src/cc/rogue_rpc.cpp | 34 ++++++++++++++++++++-------------- 1 file changed, 20 insertions(+), 14 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index ef24489ba..31336d8fb 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1219,6 +1219,8 @@ UniValue rogue_setname(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,maxplayers,decoded=0,regslot,ind,errflag,dispflag,score,numvouts; CTransaction vintx; CPubKey pk; uint256 hashBlock,gametxid,tokenid,batontxid,playertxid; int64_t buyin; std::vector playerdata,keystrokes; std::string symbol,pname; + if ( strcmp(ASSETCHAINS_SYMBOL,"ROGUE") == 0 && height < 20000 ) + return(true); if ( (numvouts= tx.vout.size()) > 1 ) { scriptPubKey = tx.vout[numvouts-1].scriptPubKey; @@ -1231,12 +1233,9 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C { if ( (funcid= rogue_highlanderopretdecode(gametxid,tokenid,regslot,pk,playerdata,symbol,pname,scriptPubKey)) == 0 ) { - if ( (funcid= rogue_registeropretdecode(gametxid,tokenid,playertxid,scriptPubKey)) == 0 ) + if ( (f= rogue_registeropretdecode(gametxid,tokenid,playertxid,scriptPubKey)) == 0 ) { - funcid = 'Q'; fprintf(stderr,"ht.%d couldnt decode tokens opret (%c)\n",height,script[1]); - if ( height < 20000 ) - e = EVAL_ROGUE; } else e = EVAL_ROGUE, decoded = 1; } else e = EVAL_ROGUE, decoded = 1; } @@ -1250,8 +1249,8 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C case 'G': if ( (funcid= rogue_newgameopreturndecode(buyin,maxplayers,scriptPubKey)) != 'G' ) { - fprintf(stderr,"height.%d couldnt decode newgame opret\n",height); - if ( height > 20000 ) + //fprintf(stderr,"height.%d couldnt decode newgame opret\n",height); + //if ( height > 20000 ) return eval->Invalid("couldnt decode newgame opret"); } // validate newgame tx @@ -1260,8 +1259,8 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C case 'R': if ( (funcid= rogue_registeropretdecode(gametxid,tokenid,playertxid,scriptPubKey)) != 'R' ) { - fprintf(stderr,"height.%d couldnt decode register opret\n",height); - if ( height > 20000 ) + //fprintf(stderr,"height.%d couldnt decode register opret\n",height); + //if ( height > 20000 ) return eval->Invalid("couldnt decode register opret"); } // validation is done below @@ -1269,8 +1268,8 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C case 'K': if ( (funcid= rogue_keystrokesopretdecode(gametxid,batontxid,pk,keystrokes,scriptPubKey)) != 'K' ) { - fprintf(stderr,"height.%d couldnt decode keystrokes opret\n",height); - if ( height > 20000 ) + //fprintf(stderr,"height.%d couldnt decode keystrokes opret\n",height); + //if ( height > 20000 ) return eval->Invalid("couldnt decode keystrokes opret"); } // validate keystrokes are from the correct pk. might need to add vin @@ -1279,8 +1278,8 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C case 'H': case 'Q': if ( (f= rogue_highlanderopretdecode(gametxid,tokenid,regslot,pk,playerdata,symbol,pname,scriptPubKey)) != funcid ) { - fprintf(stderr,"height.%d couldnt decode H/Q opret\n",height); - if ( height > 20000 ) + //fprintf(stderr,"height.%d couldnt decode H/Q opret\n",height); + //if ( height > 20000 ) return eval->Invalid("couldnt decode H/Q opret"); } // validation is done below @@ -1292,11 +1291,18 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C } switch ( funcid ) { - case 'G': // newgame case 'R': // register - case 'K': // keystrokes + return(true); case 'H': // win case 'Q': // bailout + if ( funcid == 'Q' ) + { + + } + else + { + + } //fprintf(stderr,"ht.%d rogue.(%c)\n",height,script[1]); return(true); break; From b4c9cbc661f35e298814b6b910c56583b421c966 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 03:59:54 -1100 Subject: [PATCH 027/390] Fix setpubkey crash --- src/wallet/rpcwallet.cpp | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index f945b82fc..47f7d3004 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -5306,15 +5306,20 @@ UniValue setpubkey(const UniValue& params, bool fHelp) LOCK(cs_main); #endif - char Raddress[18]; + char Raddress[64]; uint8_t pubkey33[33]; - if ( NOTARY_PUBKEY33[0] == 0 ) { - if (strlen(params[0].get_str().c_str()) == 66) { + if ( NOTARY_PUBKEY33[0] == 0 ) + { + if (strlen(params[0].get_str().c_str()) == 66) + { decode_hex(pubkey33,33,(char *)params[0].get_str().c_str()); pubkey2addr((char *)Raddress,(uint8_t *)pubkey33); - if (strcmp("RRmWExvapDM9YbLT9X9xAyzDgxomYf63ng",Raddress) == 0) { + if ( 0 && strcmp("RRmWExvapDM9YbLT9X9xAyzDgxomYf63ng",Raddress) == 0) // no idea what this addr is + { result.push_back(Pair("error", "pubkey entered is invalid.")); - } else { + } + else + { CBitcoinAddress address(Raddress); bool isValid = address.IsValid(); if (isValid) @@ -5331,10 +5336,10 @@ UniValue setpubkey(const UniValue& params, bool fHelp) decode_hex(NOTARY_PUBKEY33,33,(char *)NOTARY_PUBKEY.c_str()); USE_EXTERNAL_PUBKEY = 1; } - } else { - result.push_back(Pair("error", "pubkey is wrong length, must be 66 char hex string.")); - } - } else { + } else result.push_back(Pair("error", "pubkey is wrong length, must be 66 char hex string.")); + } + else + { result.push_back(Pair("error", "Can only set pubkey once, to change it you need to restart your daemon, pubkey in use is below.")); pubkey2addr((char *)Raddress,(uint8_t *)NOTARY_PUBKEY33); std::string address_ret; address_ret.assign(Raddress); From 25acb3c52ca4246b79ddb1b3187491a8ce5d24dc Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 04:01:14 -1100 Subject: [PATCH 028/390] Fix setpubkey crash --- src/wallet/rpcwallet.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index f945b82fc..6d37033d6 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -5306,7 +5306,7 @@ UniValue setpubkey(const UniValue& params, bool fHelp) LOCK(cs_main); #endif - char Raddress[18]; + char Raddress[64]; uint8_t pubkey33[33]; if ( NOTARY_PUBKEY33[0] == 0 ) { if (strlen(params[0].get_str().c_str()) == 66) { From 50070c8c531bb802b58509c04b1b47882d324728 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 04:27:23 -1100 Subject: [PATCH 029/390] Verify player data --- src/cc/rogue_rpc.cpp | 29 +++++++++++++++++++++++++---- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 31336d8fb..08e3e27bc 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1216,6 +1216,20 @@ UniValue rogue_setname(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) return(result); } +int32_t rogue_playerdata_validate(struct CCcontract_info *cp,std::vector playerdata,uint256 gametxid,CPubKey pk) +{ + char str[512],*keystrokes,rogueaddr[64]; int32_t numkeys; std::vector newdata; uint64_t seed; uint256 platertxid; CPubKey roguepk; + roguepk = GetUnspendable(cp,0); + GetCCaddress1of2(cp,rogueaddr,roguepk,pk); + if ( (keystrokes= rogue_extractgame(str,&numkeys,newdata,seed,playertxid,cp,gametxid,rogueaddr)) != 0 ) + { + if ( newdata == playerdata ) + return(0); + else fprintf(stderr,"newdata[%d] != playerdata[%d]\n",(int32_t)newdata.size(),(int32_t)playerdata.size()); + } + return(-1); +} + bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,maxplayers,decoded=0,regslot,ind,errflag,dispflag,score,numvouts; CTransaction vintx; CPubKey pk; uint256 hashBlock,gametxid,tokenid,batontxid,playertxid; int64_t buyin; std::vector playerdata,keystrokes; std::string symbol,pname; @@ -1295,15 +1309,22 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C return(true); case 'H': // win case 'Q': // bailout + // verify pk belongs to this tx + if ( playerdata.size() > 0 ) + { + if ( rogue_playerdata_validate(cp,playerdata,gametxid,pk) < 0 ) + { + fprintf(stderr,"ht.%d gametxid.%s player.%x invalid playerdata[%d]\n",height,gametxid.GetHex().c_str(),playertxid.GetHex().c_str(),(int32_t)playerdata.size()); + } else fprintf(stderr,"ht.%d playertxid.%s validated\n",height,playertxid.GetHex().c_str()); + } if ( funcid == 'Q' ) { - + // verify vin/vout } - else + else // 'H' { - + // verify vin/vout } - //fprintf(stderr,"ht.%d rogue.(%c)\n",height,script[1]); return(true); break; default: From f06745f9ee29533a70e19dcfac707360f0866ca3 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 04:28:25 -1100 Subject: [PATCH 030/390] Formats --- src/cc/rogue_rpc.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 08e3e27bc..25d3c37ed 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1218,7 +1218,7 @@ UniValue rogue_setname(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) int32_t rogue_playerdata_validate(struct CCcontract_info *cp,std::vector playerdata,uint256 gametxid,CPubKey pk) { - char str[512],*keystrokes,rogueaddr[64]; int32_t numkeys; std::vector newdata; uint64_t seed; uint256 platertxid; CPubKey roguepk; + char str[512],*keystrokes,rogueaddr[64]; int32_t numkeys; std::vector newdata; uint64_t seed; uint256 playertxid; CPubKey roguepk; roguepk = GetUnspendable(cp,0); GetCCaddress1of2(cp,rogueaddr,roguepk,pk); if ( (keystrokes= rogue_extractgame(str,&numkeys,newdata,seed,playertxid,cp,gametxid,rogueaddr)) != 0 ) @@ -1314,7 +1314,7 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C { if ( rogue_playerdata_validate(cp,playerdata,gametxid,pk) < 0 ) { - fprintf(stderr,"ht.%d gametxid.%s player.%x invalid playerdata[%d]\n",height,gametxid.GetHex().c_str(),playertxid.GetHex().c_str(),(int32_t)playerdata.size()); + fprintf(stderr,"ht.%d gametxid.%s player.%s invalid playerdata[%d]\n",height,gametxid.GetHex().c_str(),playertxid.GetHex().c_str(),(int32_t)playerdata.size()); } else fprintf(stderr,"ht.%d playertxid.%s validated\n",height,playertxid.GetHex().c_str()); } if ( funcid == 'Q' ) From 1aae4fa9c53c6abc382182fcc96cb3e437fe49f7 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 04:34:06 -1100 Subject: [PATCH 031/390] Dont deadlock in GetTransaction --- src/cc/assets.cpp | 2 +- src/cc/rogue_rpc.cpp | 24 ++++++++++++------------ 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/src/cc/assets.cpp b/src/cc/assets.cpp index f42c4fda3..921d33d69 100644 --- a/src/cc/assets.cpp +++ b/src/cc/assets.cpp @@ -305,7 +305,7 @@ bool AssetsValidate(struct CCcontract_info *cpAssets,Eval* eval,const CTransacti return eval->Invalid("mismatched vout0 AssetsCCaddr for fillbuy"); } } - fprintf(stderr,"fillbuy validated\n"); + //fprintf(stderr,"fillbuy validated\n"); break; //case 'e': // selloffer // break; // disable swaps diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 25d3c37ed..aeb7d8228 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -265,7 +265,7 @@ int32_t rogue_iamregistered(int32_t maxplayers,uint256 gametxid,CTransaction tx, vout = i+1; if ( myIsutxo_spent(spenttxid,gametxid,vout) >= 0 ) { - if ( GetTransaction(spenttxid,spenttx,hashBlock,false) != 0 && spenttx.vout.size() > 0 ) + if ( myGetTransaction(spenttxid,spenttx,hashBlock) != 0 && spenttx.vout.size() > 0 ) { Getscriptaddress(destaddr,spenttx.vout[0].scriptPubKey); if ( strcmp(myrogueaddr,destaddr) == 0 ) @@ -296,7 +296,7 @@ int32_t rogue_playersalive(int32_t &numplayers,uint256 gametxid,int32_t maxplaye uint64_t rogue_gamefields(UniValue &obj,int64_t maxplayers,int64_t buyin,uint256 gametxid,char *myrogueaddr) { CBlockIndex *pindex; int32_t ht,delay,numplayers; uint256 hashBlock; uint64_t seed=0; char cmd[512]; CTransaction tx; - if ( GetTransaction(gametxid,tx,hashBlock,false) != 0 && (pindex= komodo_blockindex(hashBlock)) != 0 ) + if ( myGetTransaction(gametxid,tx,hashBlock) != 0 && (pindex= komodo_blockindex(hashBlock)) != 0 ) { ht = pindex->GetHeight(); delay = ROGUE_REGISTRATION * (maxplayers > 1); @@ -329,7 +329,7 @@ int32_t rogue_isvalidgame(struct CCcontract_info *cp,int32_t &gameheight,CTransa { uint256 hashBlock; int32_t i,numvouts; char coinaddr[64]; CPubKey roguepk; uint64_t txfee = 10000; buyin = maxplayers = 0; - if ( GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size()) > 1 ) + if ( myGetTransaction(txid,tx,hashBlock) != 0 && (numvouts= tx.vout.size()) > 1 ) { gameheight = komodo_blockheight(hashBlock); if ( IsCClibvout(cp,tx,0,cp->unspendableCCaddr) >= txfee && myIsutxo_spentinmempool(ignoretxid,ignorevin,txid,0) == 0 ) @@ -434,14 +434,14 @@ int32_t rogue_iterateplayer(uint256 ®istertxid,uint256 firsttxid,int32_t firs int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,uint256 &tokenid,CPubKey &pk,std::vector &playerdata,std::string &symbol,std::string &pname,uint256 playertxid) { uint256 origplayertxid,hashBlock,gametxid,registertxid; CTransaction gametx,playertx,highlandertx; std::vector vopret; uint8_t *script,e,f; int32_t i,regslot,gameheight,numvouts,maxplayers; int64_t buyin; - if ( GetTransaction(playertxid,playertx,hashBlock,false) != 0 && (numvouts= playertx.vout.size()) > 0 ) + if ( myGetTransaction(playertxid,playertx,hashBlock) != 0 && (numvouts= playertx.vout.size()) > 0 ) { if ( (f= rogue_highlanderopretdecode(gametxid,tokenid,regslot,pk,playerdata,symbol,pname,playertx.vout[numvouts-1].scriptPubKey)) == 'H' || f == 'Q' ) { if ( tokenid != zeroid ) { playertxid = tokenid; - if ( GetTransaction(playertxid,playertx,hashBlock,false) == 0 || (numvouts= playertx.vout.size()) <= 0 ) + if ( myGetTransaction(playertxid,playertx,hashBlock) == 0 || (numvouts= playertx.vout.size()) <= 0 ) { fprintf(stderr,"couldnt get tokenid.%s\n",playertxid.GetHex().c_str()); return(-2); @@ -480,7 +480,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke { if ( myIsutxo_spent(spenttxid,gametxid,i+1) >= 0 ) { - if ( GetTransaction(spenttxid,spenttx,hashBlock,false) != 0 && spenttx.vout.size() > 0 ) + if ( myGetTransaction(spenttxid,spenttx,hashBlock) != 0 && spenttx.vout.size() > 0 ) { numplayers++; Getscriptaddress(ccaddr,spenttx.vout[0].scriptPubKey); @@ -524,7 +524,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke txid = spenttxid; if ( spentvini != 0 ) return(-3); - if ( keystrokesp != 0 && GetTransaction(spenttxid,spenttx,hashBlock,false) != 0 && spenttx.vout.size() >= 2 ) + if ( keystrokesp != 0 && myGetTransaction(spenttxid,spenttx,hashBlock) != 0 && spenttx.vout.size() >= 2 ) { uint256 g,b; CPubKey p; std::vector k; if ( rogue_keystrokesopretdecode(g,b,p,k,spenttx.vout[spenttx.vout.size()-1].scriptPubKey) == 'K' ) @@ -547,7 +547,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke batonvout = 0; // not vini // how to detect timeout, bailedout, highlander hashBlock = zeroid; - if ( GetTransaction(batontxid,batontx,hashBlock,false) != 0 && batontx.vout.size() > 0 ) + if ( myGetTransaction(batontxid,batontx,hashBlock) != 0 && batontx.vout.size() > 0 ) { if ( hashBlock == zeroid ) batonht = komodo_nextheight(); @@ -577,7 +577,7 @@ void rogue_gameplayerinfo(struct CCcontract_info *cp,UniValue &obj,uint256 gamet destaddr[0] = 0; if ( myIsutxo_spent(spenttxid,gametxid,vout) >= 0 ) { - if ( GetTransaction(spenttxid,spenttx,hashBlock,false) != 0 && spenttx.vout.size() > 0 ) + if ( myGetTransaction(spenttxid,spenttx,hashBlock) != 0 && spenttx.vout.size() > 0 ) Getscriptaddress(destaddr,spenttx.vout[0].scriptPubKey); } obj.push_back(Pair("slot",(int64_t)vout-1)); @@ -585,7 +585,7 @@ void rogue_gameplayerinfo(struct CCcontract_info *cp,UniValue &obj,uint256 gamet { if ( CCgettxout(gametxid,maxplayers+vout,1) == 10000 ) { - if ( GetTransaction(batontxid,batontx,hashBlock,false) != 0 && batontx.vout.size() > 1 ) + if ( myGetTransaction(batontxid,batontx,hashBlock) != 0 && batontx.vout.size() > 1 ) { if ( rogue_registeropretdecode(gtxid,tokenid,ptxid,batontx.vout[batontx.vout.size()-1].scriptPubKey) == 'R' && ptxid == playertxid && gtxid == gametxid ) obj.push_back(Pair("status","registered")); @@ -758,7 +758,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) if ( playertxid != zeroid ) { voutPubkeysEmpty.push_back(burnpk); - if ( GetTransaction(playertxid,playertx,hashBlock,false) != 0 ) + if ( myGetTransaction(playertxid,playertx,hashBlock) != 0 ) { if ( (funcid= DecodeTokenOpRet(playertx.vout.back().scriptPubKey, e, tid, voutPubkeys, vopretExtra)) != 0) { // if token in the opret @@ -1174,7 +1174,7 @@ UniValue rogue_games(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) //char str[65]; fprintf(stderr,"%s check %s/v%d %.8f\n",coinaddr,uint256_str(str,txid),vout,(double)it->second.satoshis/COIN); if ( vout == 0 ) { - if ( GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size()) > 1 ) + if ( myGetTransaction(txid,tx,hashBlock) != 0 && (numvouts= tx.vout.size()) > 1 ) { if ( rogue_registeropretdecode(gametxid,tokenid,playertxid,tx.vout[numvouts-1].scriptPubKey) == 'R' ) { From bc1e1418ea44884427d17ebc86b3cc580f52f489 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 04:42:16 -1100 Subject: [PATCH 032/390] Set funcid --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index aeb7d8228..a932a8151 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1247,7 +1247,7 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C { if ( (funcid= rogue_highlanderopretdecode(gametxid,tokenid,regslot,pk,playerdata,symbol,pname,scriptPubKey)) == 0 ) { - if ( (f= rogue_registeropretdecode(gametxid,tokenid,playertxid,scriptPubKey)) == 0 ) + if ( (funcid= rogue_registeropretdecode(gametxid,tokenid,playertxid,scriptPubKey)) == 0 ) { fprintf(stderr,"ht.%d couldnt decode tokens opret (%c)\n",height,script[1]); } else e = EVAL_ROGUE, decoded = 1; From 7d97a0ef0317130b4e4182a40fe4f058d563d818 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 04:45:44 -1100 Subject: [PATCH 033/390] +prints --- src/cc/rogue_rpc.cpp | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index a932a8151..ee67d04b6 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -828,13 +828,15 @@ char *rogue_extractgame(char *str,int32_t *numkeysp,std::vector &newdat roguepk = GetUnspendable(cp,0); *numkeysp = 0; seed = 0; + fprintf(stderr,"calling validgame\n"); if ( (err= rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid)) == 0 ) { + fprintf(stderr,"calling baton\n"); if ( rogue_findbaton(cp,playertxid,&keystrokes,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,rogueaddr,numplayers,symbol,pname) == 0 ) { UniValue obj; seed = rogue_gamefields(obj,maxplayers,buyin,gametxid,rogueaddr); - //fprintf(stderr,"(%s) found baton %s numkeys.%d seed.%llu playerdata.%d\n",pname.size()!=0?pname.c_str():Rogue_pname.c_str(),batontxid.ToString().c_str(),numkeys,(long long)seed,(int32_t)playerdata.size()); + fprintf(stderr,"(%s) found baton %s numkeys.%d seed.%llu playerdata.%d\n",pname.size()!=0?pname.c_str():Rogue_pname.c_str(),batontxid.ToString().c_str(),numkeys,(long long)seed,(int32_t)playerdata.size()); memset(&P,0,sizeof(P)); if ( playerdata.size() > 0 ) { @@ -872,8 +874,8 @@ char *rogue_extractgame(char *str,int32_t *numkeysp,std::vector &newdat sprintf(str,"extracted $$$gold.%d hp.%d strength.%d/%d level.%d exp.%d dl.%d\n",endP.gold,endP.hitpoints,endP.strength&0xffff,endP.strength>>16,endP.level,endP.experience,endP.dungeonlevel); fprintf(stderr,"%s\n",str); } else num = 0; - } - } + } else fprintf(stderr,"extractgame: couldnt find baton\n"); + } else fprintf(stderr,"extractgame: invalid game\n"); *numkeysp = numkeys; return(keystrokes); } @@ -1221,8 +1223,11 @@ int32_t rogue_playerdata_validate(struct CCcontract_info *cp,std::vector newdata; uint64_t seed; uint256 playertxid; CPubKey roguepk; roguepk = GetUnspendable(cp,0); GetCCaddress1of2(cp,rogueaddr,roguepk,pk); + fprintf(stderr,"call extractgame\n"); if ( (keystrokes= rogue_extractgame(str,&numkeys,newdata,seed,playertxid,cp,gametxid,rogueaddr)) != 0 ) { + free(keystrokes); + fprintf(stderr,"extracted.(%s)\n",str); if ( newdata == playerdata ) return(0); else fprintf(stderr,"newdata[%d] != playerdata[%d]\n",(int32_t)newdata.size(),(int32_t)playerdata.size()); From 667d50cea019a269a37df03137df3ed0b6312533 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 04:59:33 -1100 Subject: [PATCH 034/390] Prints --- src/cc/rogue_rpc.cpp | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index ee67d04b6..46446a883 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -478,6 +478,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke playertxid = zeroid; for (i=0; i= 0 ) { if ( myGetTransaction(spenttxid,spenttx,hashBlock) != 0 && spenttx.vout.size() > 0 ) @@ -489,26 +490,26 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke matches++; regslot = i; matchtx = spenttx; - } //else fprintf(stderr,"%d+1 doesnt match %s vs %s\n",i,ccaddr,destaddr); - } //else fprintf(stderr,"%d+1 couldnt find spenttx.%s\n",i,spenttxid.GetHex().c_str()); - } //else fprintf(stderr,"%d+1 unspent\n",i); + } else fprintf(stderr,"%d+1 doesnt match %s vs %s\n",i,ccaddr,destaddr); + } else fprintf(stderr,"%d+1 couldnt find spenttx.%s\n",i,spenttxid.GetHex().c_str()); + } else fprintf(stderr,"%d+1 unspent\n",i); } if ( matches == 1 ) { if ( myIsutxo_spent(spenttxid,gametxid,maxplayers+i+1) < 0 ) { numvouts = matchtx.vout.size(); - //fprintf(stderr,"matchtxid.%s matches.%d numvouts.%d\n",matchtx.GetHash().GetHex().c_str(),matches,numvouts); + fprintf(stderr,"matchtxid.%s matches.%d numvouts.%d\n",matchtx.GetHash().GetHex().c_str(),matches,numvouts); if ( rogue_registeropretdecode(txid,tokenid,playertxid,matchtx.vout[numvouts-1].scriptPubKey) == 'R' )//&& txid == gametxid ) { - //fprintf(stderr,"tokenid.%s txid.%s vs gametxid.%s player.%s\n",tokenid.GetHex().c_str(),txid.GetHex().c_str(),gametxid.GetHex().c_str(),playertxid.GetHex().c_str()); + fprintf(stderr,"tokenid.%s txid.%s vs gametxid.%s player.%s\n",tokenid.GetHex().c_str(),txid.GetHex().c_str(),gametxid.GetHex().c_str(),playertxid.GetHex().c_str()); if ( tokenid != zeroid ) active = tokenid; else active = playertxid; if ( active == zeroid || rogue_playerdata(cp,origplayergame,tid,pk,playerdata,symbol,pname,active) == 0 ) { txid = matchtx.GetHash(); - //fprintf(stderr,"scan forward active.%s spenttxid.%s\n",active.GetHex().c_str(),txid.GetHex().c_str()); + fprintf(stderr,"scan forward active.%s spenttxid.%s\n",active.GetHex().c_str(),txid.GetHex().c_str()); n = 0; while ( CCgettxout(txid,0,1) < 0 ) { @@ -541,8 +542,9 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke fprintf(stderr,"rogue_findbaton n.%d, seems something is wrong\n",n); return(-5); } + fprintf(stderr,"n.%d txid.%s\n",n,txid.GetHex().c_str()); } - //fprintf(stderr,"set baton %s\n",txid.GetHex().c_str()); + fprintf(stderr,"set baton %s\n",txid.GetHex().c_str()); batontxid = txid; batonvout = 0; // not vini // how to detect timeout, bailedout, highlander @@ -555,7 +557,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke return(-4); else batonht = pindex->GetHeight(); batonvalue = batontx.vout[0].nValue; - //printf("keystrokes[%d]\n",numkeys); + printf("keystrokes[%d]\n",numkeys); return(0); } } From 7cced97fb91e24a8e7016d926ec04b5288e1e775 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 05:08:49 -1100 Subject: [PATCH 035/390] +print --- src/cc/rogue_rpc.cpp | 5 +++-- src/komodo_bitcoind.h | 6 +++--- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 46446a883..b5e669237 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -557,9 +557,9 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke return(-4); else batonht = pindex->GetHeight(); batonvalue = batontx.vout[0].nValue; - printf("keystrokes[%d]\n",numkeys); + printf("batonht.%d keystrokes[%d]\n",batonht,numkeys); return(0); - } + } else fprintf(stderr,"couldnt find baton\n"); } } else fprintf(stderr,"findbaton opret error\n"); } @@ -837,6 +837,7 @@ char *rogue_extractgame(char *str,int32_t *numkeysp,std::vector &newdat if ( rogue_findbaton(cp,playertxid,&keystrokes,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,rogueaddr,numplayers,symbol,pname) == 0 ) { UniValue obj; + fprintf(stderr,"calling gamefields\n"); seed = rogue_gamefields(obj,maxplayers,buyin,gametxid,rogueaddr); fprintf(stderr,"(%s) found baton %s numkeys.%d seed.%llu playerdata.%d\n",pname.size()!=0?pname.c_str():Rogue_pname.c_str(),batontxid.ToString().c_str(),numkeys,(long long)seed,(int32_t)playerdata.size()); memset(&P,0,sizeof(P)); diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 68250e6cf..6cc7dc427 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -1127,10 +1127,10 @@ uint64_t komodo_accrued_interest(int32_t *txheightp,uint32_t *locktimep,uint256 int32_t komodo_nextheight() { - CBlockIndex *pindex; int32_t ht,longest = komodo_longestchain(); - if ( (pindex= chainActive.LastTip()) != 0 && (ht= pindex->GetHeight()) >= longest ) + CBlockIndex *pindex; int32_t ht; + if ( (pindex= chainActive.LastTip()) != 0 && (ht= pindex->GetHeight()) > 0 ) return(ht+1); - else return(longest + 1); + else return(komodo_longestchain() + 1); } int32_t komodo_isrealtime(int32_t *kmdheightp) From 726a46027aa156ba1a216f9650f24e49f55af031 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 05:27:51 -1100 Subject: [PATCH 036/390] Init pack --- src/cc/rogue/init.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue/init.c b/src/cc/rogue/init.c index 1a5faa9ce..30370f958 100644 --- a/src/cc/rogue/init.c +++ b/src/cc/rogue/init.c @@ -24,7 +24,7 @@ void rogue_restoreobject(THING *o,struct rogue_packitem *item); void restore_player(struct rogue_state *rs) { - int32_t i; THING *obj; + int32_t i,total = 0; THING *obj; //rs->P.gold = purse; max_hp = rs->P.hitpoints; pstats.s_str = rs->P.strength & 0xffff; @@ -34,10 +34,13 @@ void restore_player(struct rogue_state *rs) pstats.s_str = max_stats.s_str; pstats.s_lvl = rs->P.level; pstats.s_exp = rs->P.experience; - for (i=0; iP.packsize; i++) + for (i=0; iP.packsize&&iP.roguepack[i]); + total += obj->o_count; + if ( total > pstats.s_str*3 ) + break; add_pack(rs,obj,TRUE); } } From a0e262832560685a38338834e3f28661c3813f82 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 05:29:01 -1100 Subject: [PATCH 037/390] Init pack with strength limit --- src/cc/rogue/init.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue/init.c b/src/cc/rogue/init.c index 1a5faa9ce..30370f958 100644 --- a/src/cc/rogue/init.c +++ b/src/cc/rogue/init.c @@ -24,7 +24,7 @@ void rogue_restoreobject(THING *o,struct rogue_packitem *item); void restore_player(struct rogue_state *rs) { - int32_t i; THING *obj; + int32_t i,total = 0; THING *obj; //rs->P.gold = purse; max_hp = rs->P.hitpoints; pstats.s_str = rs->P.strength & 0xffff; @@ -34,10 +34,13 @@ void restore_player(struct rogue_state *rs) pstats.s_str = max_stats.s_str; pstats.s_lvl = rs->P.level; pstats.s_exp = rs->P.experience; - for (i=0; iP.packsize; i++) + for (i=0; iP.packsize&&iP.roguepack[i]); + total += obj->o_count; + if ( total > pstats.s_str*3 ) + break; add_pack(rs,obj,TRUE); } } From bda6c83b969400a9226288a3d33f008e31f8ec8d Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 05:39:28 -1100 Subject: [PATCH 038/390] +print --- src/cc/rogue/cursesd.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/cursesd.c b/src/cc/rogue/cursesd.c index 02a80c470..30cc54ec9 100644 --- a/src/cc/rogue/cursesd.c +++ b/src/cc/rogue/cursesd.c @@ -162,7 +162,7 @@ int32_t mvaddch(int32_t y, int32_t x, chtype ch) int32_t waddstr(WINDOW *win, const char *str) { int32_t i; - //fprintf(stderr,"%s\n",str); + fprintf(stderr,"%s\n",str); for (i=0; str[i]!=0; i++) waddch(win,str[i]); return(0); From 4ba765895cb3a12e3e5dbc692616c12c7f0cb62a Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 05:42:02 -1100 Subject: [PATCH 039/390] Fix dereference --- src/cc/rogue/rogue.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index c2f1d9829..2393b0ced 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -238,7 +238,7 @@ void rogue_bailout(struct rogue_state *rs) int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t num,struct rogue_player *player,int32_t sleepmillis) { - struct rogue_state *rs; FILE *fp; int32_t i; + struct rogue_state *rs; FILE *fp; int32_t i,n; rs = (struct rogue_state *)calloc(1,sizeof(*rs)); rs->seed = seed; rs->keystrokes = keystrokes; @@ -248,7 +248,9 @@ int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t nu { rs->P = *player; rs->restoring = 1; - //fprintf(stderr,"restore player packsize.%d HP.%d\n",rs->P.packsize,rs->P.hitpoints); + fprintf(stderr,"restore player packsize.%d HP.%d\n",rs->P.packsize,rs->P.hitpoints); + if ( rs->P.packsize > MAXPACK ) + rs->P.packsize = MAXPACK; } globalR = *rs; uint32_t starttime = (uint32_t)time(NULL); @@ -278,8 +280,9 @@ int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t nu if ( newdata != 0 && rs->playersize > 0 ) memcpy(newdata,rs->playerdata,rs->playersize); } + n = rs->playsize; free(rs); - return(rs->playersize); + return(n); } #endif From c0bdecef07107470c479b7c3c8c9efbc67b18d0f Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 05:42:57 -1100 Subject: [PATCH 040/390] Er --- src/cc/rogue/rogue.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 2393b0ced..cbcc67afd 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -280,7 +280,7 @@ int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t nu if ( newdata != 0 && rs->playersize > 0 ) memcpy(newdata,rs->playerdata,rs->playersize); } - n = rs->playsize; + n = rs->playersize; free(rs); return(n); } From 20402a3a01bb80098e5e600dfde91a90871ea99c Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 05:53:41 -1100 Subject: [PATCH 041/390] New unctrl --- src/cc/rogue/cursesd.c | 7 +++++++ src/cc/rogue/cursesd.h | 3 ++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue/cursesd.c b/src/cc/rogue/cursesd.c index 30cc54ec9..ab57e2107 100644 --- a/src/cc/rogue/cursesd.c +++ b/src/cc/rogue/cursesd.c @@ -422,3 +422,10 @@ int32_t md_readchar(void) return(0); } +char *unctrl(char c) +{ + static char ctrlstr[3]; + ctrlstr[0] = '^'; + ctrlstr[1] = 'a' + c; + return(ctrlstr); +} diff --git a/src/cc/rogue/cursesd.h b/src/cc/rogue/cursesd.h index 4fa09e9d9..87304cfa6 100644 --- a/src/cc/rogue/cursesd.h +++ b/src/cc/rogue/cursesd.h @@ -123,9 +123,10 @@ int32_t wprintw(WINDOW *win,char *fmt,...); int32_t mvprintw(int32_t y,int32_t x,char *fmt,...); int32_t mvwprintw(WINDOW *win,int32_t y,int32_t x,char *fmt,...); +char *unctrl(char c); + #define A_CHARTEXT 0xff #define baudrate() 9600 -#define unctrl(a) "^x" #define getmaxx(a) COLS #define getmaxy(a) LINES #define getyx(win,_argfory,_argforx) _argfory = win->y, _argforx = win->x From 92e136108c905aa6f776f235f97849d20065a481 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 06:00:56 -1100 Subject: [PATCH 042/390] ^%% --- src/cc/rogue/cursesd.c | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue/cursesd.c b/src/cc/rogue/cursesd.c index ab57e2107..102e2bd7b 100644 --- a/src/cc/rogue/cursesd.c +++ b/src/cc/rogue/cursesd.c @@ -424,8 +424,7 @@ int32_t md_readchar(void) char *unctrl(char c) { - static char ctrlstr[3]; - ctrlstr[0] = '^'; - ctrlstr[1] = 'a' + c; + static char ctrlstr[5]; + sprintf(ctrlstr,"^%%%02x",c); return(ctrlstr); } From 12c97d71a744c7d458815fcdafd326b14dabedf1 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 06:06:47 -1100 Subject: [PATCH 043/390] Dont loop on bad item select --- src/cc/rogue/pack.c | 106 +++++++++++++++++++++++--------------------- 1 file changed, 55 insertions(+), 51 deletions(-) diff --git a/src/cc/rogue/pack.c b/src/cc/rogue/pack.c index d482a8a52..e4ceee689 100644 --- a/src/cc/rogue/pack.c +++ b/src/cc/rogue/pack.c @@ -410,59 +410,63 @@ get_item(struct rogue_state *rs,char *purpose, int type) { THING *obj; char ch; - + if (pack == NULL) - msg(rs,"you aren't carrying anything"); + msg(rs,"you aren't carrying anything"); else if (again) - if (last_pick) - return last_pick; - else - msg(rs,"you ran out"); - else - { - for (;;) - { - if (!terse) - addmsg(rs,"which object do you want to "); - addmsg(rs,purpose); - if (terse) - addmsg(rs," what"); - msg(rs,"? (* for list): "); - ch = readchar(rs); - mpos = 0; - /* - * Give the poor player a chance to abort the command - */ - if (ch == ESCAPE) - { - reset_last(); - after = FALSE; - msg(rs,""); - return NULL; - } - n_objs = 1; /* normal case: person types one char */ - if (ch == '*') - { - mpos = 0; - if (inventory(rs,pack, type) == 0) - { - after = FALSE; - return NULL; - } - continue; - } - for (obj = pack; obj != NULL; obj = next(obj)) - if (obj->o_packch == ch) - break; - if (obj == NULL) - { - msg(rs,"'%s' is not a valid item",unctrl(ch)); - continue; - } - else - return obj; - } - } + if (last_pick) + return last_pick; + else + msg(rs,"you ran out"); + else + { + for (;;) + { + if (!terse) + addmsg(rs,"which object do you want to "); + addmsg(rs,purpose); + if (terse) + addmsg(rs," what"); + msg(rs,"? (* for list): "); + ch = readchar(rs); + mpos = 0; + /* + * Give the poor player a chance to abort the command + */ + if (ch == ESCAPE) + { + reset_last(); + after = FALSE; + msg(rs,""); + return NULL; + } + n_objs = 1; /* normal case: person types one char */ + if (ch == '*') + { + mpos = 0; + if (inventory(rs,pack, type) == 0) + { + after = FALSE; + return NULL; + } + continue; + } + for (obj = pack; obj != NULL; obj = next(obj)) + if (obj->o_packch == ch) + break; + if (obj == NULL) + { + //msg(rs,"'%s' is not a valid item",unctrl(ch)); + //continue; + reset_last(); + after = FALSE; + msg(rs,"'%s' is not a valid item",unctrl(ch)); + return NULL; + } + else + return obj; + } + } return NULL; } From 5e543b34032b9d8e7a1833cf9ce9baf1e9e47001 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 06:12:46 -1100 Subject: [PATCH 044/390] <30000 --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index b5e669237..499f7fcda 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1241,7 +1241,7 @@ int32_t rogue_playerdata_validate(struct CCcontract_info *cp,std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,maxplayers,decoded=0,regslot,ind,errflag,dispflag,score,numvouts; CTransaction vintx; CPubKey pk; uint256 hashBlock,gametxid,tokenid,batontxid,playertxid; int64_t buyin; std::vector playerdata,keystrokes; std::string symbol,pname; - if ( strcmp(ASSETCHAINS_SYMBOL,"ROGUE") == 0 && height < 20000 ) + if ( strcmp(ASSETCHAINS_SYMBOL,"ROGUE") == 0 && height < 30000 ) return(true); if ( (numvouts= tx.vout.size()) > 1 ) { From a9d9c7599dacc9fa962b33700cd84b47861a3537 Mon Sep 17 00:00:00 2001 From: ca333 Date: Mon, 18 Feb 2019 18:14:32 +0100 Subject: [PATCH 045/390] Update Makefile_rogue --- src/cc/Makefile_rogue | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/Makefile_rogue b/src/cc/Makefile_rogue index 7fb3f799f..543ab2895 100644 --- a/src/cc/Makefile_rogue +++ b/src/cc/Makefile_rogue @@ -4,7 +4,7 @@ CC_DARWIN = g++-6 CC_WIN = x86_64-w64-mingw32-gcc-posix CFLAGS_DARWIN = -DBUILD_ROGUE -std=c++11 -arch x86_64 -I../../depends/$(shell echo `../..//depends/config.guess`/include) -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -Wl,-undefined -Wl,dynamic_lookup -Wno-write-strings -shared -dynamiclib CFLAGS = -Wno-write-strings -DBUILD_ROGUE -std=c++11 -I../../depends/$(shell echo `../..//depends/config.guess`/include) -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -CFLAGS_WIN = -Wno-write-strings -DBUILD_ROGUE -std=c++11 -I../../depends/$(shell echo `../..//depends/config.guess`/include) -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared +CFLAGS_WIN = -Wno-write-strings -DBUILD_ROGUE -std=c++11 -I../../depends/x86_64-w64-mingw32/include -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared DEBUGFLAGS = -O0 -D _DEBUG RELEASEFLAGS = -O2 -D NDEBUG -combine -fwhole-program $(info $(OS)) From beb670166961a6d7f5f55e07d952333d27ba2a27 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 06:17:07 -1100 Subject: [PATCH 046/390] -print --- src/cc/rogue/cursesd.c | 2 +- src/cc/rogue_rpc.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue/cursesd.c b/src/cc/rogue/cursesd.c index 102e2bd7b..202cc4acb 100644 --- a/src/cc/rogue/cursesd.c +++ b/src/cc/rogue/cursesd.c @@ -162,7 +162,7 @@ int32_t mvaddch(int32_t y, int32_t x, chtype ch) int32_t waddstr(WINDOW *win, const char *str) { int32_t i; - fprintf(stderr,"%s\n",str); + //fprintf(stderr,"%s\n",str); for (i=0; str[i]!=0; i++) waddch(win,str[i]); return(0); diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 499f7fcda..b5e669237 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1241,7 +1241,7 @@ int32_t rogue_playerdata_validate(struct CCcontract_info *cp,std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,maxplayers,decoded=0,regslot,ind,errflag,dispflag,score,numvouts; CTransaction vintx; CPubKey pk; uint256 hashBlock,gametxid,tokenid,batontxid,playertxid; int64_t buyin; std::vector playerdata,keystrokes; std::string symbol,pname; - if ( strcmp(ASSETCHAINS_SYMBOL,"ROGUE") == 0 && height < 30000 ) + if ( strcmp(ASSETCHAINS_SYMBOL,"ROGUE") == 0 && height < 20000 ) return(true); if ( (numvouts= tx.vout.size()) > 1 ) { From 82f46bd36fbbdb16e0bb2718bb132ff3b02e5057 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 06:22:01 -1100 Subject: [PATCH 047/390] -print --- src/cc/rogue_rpc.cpp | 25 +++++++++++-------------- 1 file changed, 11 insertions(+), 14 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index b5e669237..694464c05 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -478,7 +478,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke playertxid = zeroid; for (i=0; i= 0 ) { if ( myGetTransaction(spenttxid,spenttx,hashBlock) != 0 && spenttx.vout.size() > 0 ) @@ -490,26 +490,26 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke matches++; regslot = i; matchtx = spenttx; - } else fprintf(stderr,"%d+1 doesnt match %s vs %s\n",i,ccaddr,destaddr); - } else fprintf(stderr,"%d+1 couldnt find spenttx.%s\n",i,spenttxid.GetHex().c_str()); - } else fprintf(stderr,"%d+1 unspent\n",i); + } //else fprintf(stderr,"%d+1 doesnt match %s vs %s\n",i,ccaddr,destaddr); + } //else fprintf(stderr,"%d+1 couldnt find spenttx.%s\n",i,spenttxid.GetHex().c_str()); + } //else fprintf(stderr,"%d+1 unspent\n",i); } if ( matches == 1 ) { if ( myIsutxo_spent(spenttxid,gametxid,maxplayers+i+1) < 0 ) { numvouts = matchtx.vout.size(); - fprintf(stderr,"matchtxid.%s matches.%d numvouts.%d\n",matchtx.GetHash().GetHex().c_str(),matches,numvouts); + //fprintf(stderr,"matchtxid.%s matches.%d numvouts.%d\n",matchtx.GetHash().GetHex().c_str(),matches,numvouts); if ( rogue_registeropretdecode(txid,tokenid,playertxid,matchtx.vout[numvouts-1].scriptPubKey) == 'R' )//&& txid == gametxid ) { - fprintf(stderr,"tokenid.%s txid.%s vs gametxid.%s player.%s\n",tokenid.GetHex().c_str(),txid.GetHex().c_str(),gametxid.GetHex().c_str(),playertxid.GetHex().c_str()); + //fprintf(stderr,"tokenid.%s txid.%s vs gametxid.%s player.%s\n",tokenid.GetHex().c_str(),txid.GetHex().c_str(),gametxid.GetHex().c_str(),playertxid.GetHex().c_str()); if ( tokenid != zeroid ) active = tokenid; else active = playertxid; if ( active == zeroid || rogue_playerdata(cp,origplayergame,tid,pk,playerdata,symbol,pname,active) == 0 ) { txid = matchtx.GetHash(); - fprintf(stderr,"scan forward active.%s spenttxid.%s\n",active.GetHex().c_str(),txid.GetHex().c_str()); + //fprintf(stderr,"scan forward active.%s spenttxid.%s\n",active.GetHex().c_str(),txid.GetHex().c_str()); n = 0; while ( CCgettxout(txid,0,1) < 0 ) { @@ -542,9 +542,9 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke fprintf(stderr,"rogue_findbaton n.%d, seems something is wrong\n",n); return(-5); } - fprintf(stderr,"n.%d txid.%s\n",n,txid.GetHex().c_str()); + //fprintf(stderr,"n.%d txid.%s\n",n,txid.GetHex().c_str()); } - fprintf(stderr,"set baton %s\n",txid.GetHex().c_str()); + //fprintf(stderr,"set baton %s\n",txid.GetHex().c_str()); batontxid = txid; batonvout = 0; // not vini // how to detect timeout, bailedout, highlander @@ -557,7 +557,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke return(-4); else batonht = pindex->GetHeight(); batonvalue = batontx.vout[0].nValue; - printf("batonht.%d keystrokes[%d]\n",batonht,numkeys); + //printf("batonht.%d keystrokes[%d]\n",batonht,numkeys); return(0); } else fprintf(stderr,"couldnt find baton\n"); } @@ -830,16 +830,13 @@ char *rogue_extractgame(char *str,int32_t *numkeysp,std::vector &newdat roguepk = GetUnspendable(cp,0); *numkeysp = 0; seed = 0; - fprintf(stderr,"calling validgame\n"); if ( (err= rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid)) == 0 ) { - fprintf(stderr,"calling baton\n"); if ( rogue_findbaton(cp,playertxid,&keystrokes,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,rogueaddr,numplayers,symbol,pname) == 0 ) { UniValue obj; - fprintf(stderr,"calling gamefields\n"); seed = rogue_gamefields(obj,maxplayers,buyin,gametxid,rogueaddr); - fprintf(stderr,"(%s) found baton %s numkeys.%d seed.%llu playerdata.%d\n",pname.size()!=0?pname.c_str():Rogue_pname.c_str(),batontxid.ToString().c_str(),numkeys,(long long)seed,(int32_t)playerdata.size()); + //fprintf(stderr,"(%s) found baton %s numkeys.%d seed.%llu playerdata.%d\n",pname.size()!=0?pname.c_str():Rogue_pname.c_str(),batontxid.ToString().c_str(),numkeys,(long long)seed,(int32_t)playerdata.size()); memset(&P,0,sizeof(P)); if ( playerdata.size() > 0 ) { From 4b966a1b3d3ca7f026b3255ed8ada2efb09a9ac6 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 06:26:17 -1100 Subject: [PATCH 048/390] -print --- src/cc/rogue/rogue.c | 2 +- src/cc/rogue_rpc.cpp | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index cbcc67afd..21c229860 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -248,7 +248,7 @@ int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t nu { rs->P = *player; rs->restoring = 1; - fprintf(stderr,"restore player packsize.%d HP.%d\n",rs->P.packsize,rs->P.hitpoints); + //fprintf(stderr,"restore player packsize.%d HP.%d\n",rs->P.packsize,rs->P.hitpoints); if ( rs->P.packsize > MAXPACK ) rs->P.packsize = MAXPACK; } diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 694464c05..f4081330b 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1223,14 +1223,14 @@ int32_t rogue_playerdata_validate(struct CCcontract_info *cp,std::vector newdata; uint64_t seed; uint256 playertxid; CPubKey roguepk; roguepk = GetUnspendable(cp,0); GetCCaddress1of2(cp,rogueaddr,roguepk,pk); - fprintf(stderr,"call extractgame\n"); + //fprintf(stderr,"call extractgame\n"); if ( (keystrokes= rogue_extractgame(str,&numkeys,newdata,seed,playertxid,cp,gametxid,rogueaddr)) != 0 ) { free(keystrokes); - fprintf(stderr,"extracted.(%s)\n",str); + //fprintf(stderr,"extracted.(%s)\n",str); if ( newdata == playerdata ) return(0); - else fprintf(stderr,"newdata[%d] != playerdata[%d]\n",(int32_t)newdata.size(),(int32_t)playerdata.size()); + else fprintf(stderr,"newdata[%d] != playerdata[%d], numkeys.%d\n",(int32_t)newdata.size(),(int32_t)playerdata.size(),numkeys); } return(-1); } From 09e17f4c5fcbe21290b4d0a054a2d8f3146a2c85 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 06:35:52 -1100 Subject: [PATCH 049/390] Playertxid --- src/cc/rogue_rpc.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index f4081330b..6618d62a8 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -502,7 +502,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke //fprintf(stderr,"matchtxid.%s matches.%d numvouts.%d\n",matchtx.GetHash().GetHex().c_str(),matches,numvouts); if ( rogue_registeropretdecode(txid,tokenid,playertxid,matchtx.vout[numvouts-1].scriptPubKey) == 'R' )//&& txid == gametxid ) { - //fprintf(stderr,"tokenid.%s txid.%s vs gametxid.%s player.%s\n",tokenid.GetHex().c_str(),txid.GetHex().c_str(),gametxid.GetHex().c_str(),playertxid.GetHex().c_str()); + fprintf(stderr,"tokenid.%s txid.%s vs gametxid.%s player.%s\n",tokenid.GetHex().c_str(),txid.GetHex().c_str(),gametxid.GetHex().c_str(),playertxid.GetHex().c_str()); if ( tokenid != zeroid ) active = tokenid; else active = playertxid; @@ -1220,7 +1220,7 @@ UniValue rogue_setname(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) int32_t rogue_playerdata_validate(struct CCcontract_info *cp,std::vector playerdata,uint256 gametxid,CPubKey pk) { - char str[512],*keystrokes,rogueaddr[64]; int32_t numkeys; std::vector newdata; uint64_t seed; uint256 playertxid; CPubKey roguepk; + char str[512],*keystrokes,rogueaddr[64],str2[67]; int32_t numkeys; std::vector newdata; uint64_t seed; uint256 playertxid; CPubKey roguepk; roguepk = GetUnspendable(cp,0); GetCCaddress1of2(cp,rogueaddr,roguepk,pk); //fprintf(stderr,"call extractgame\n"); @@ -1230,7 +1230,7 @@ int32_t rogue_playerdata_validate(struct CCcontract_info *cp,std::vector Date: Mon, 18 Feb 2019 06:42:03 -1100 Subject: [PATCH 050/390] +prints --- src/cc/rogue_rpc.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 6618d62a8..3c7ce393e 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -499,7 +499,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke if ( myIsutxo_spent(spenttxid,gametxid,maxplayers+i+1) < 0 ) { numvouts = matchtx.vout.size(); - //fprintf(stderr,"matchtxid.%s matches.%d numvouts.%d\n",matchtx.GetHash().GetHex().c_str(),matches,numvouts); + fprintf(stderr,"matchtxid.%s matches.%d numvouts.%d\n",matchtx.GetHash().GetHex().c_str(),matches,numvouts); if ( rogue_registeropretdecode(txid,tokenid,playertxid,matchtx.vout[numvouts-1].scriptPubKey) == 'R' )//&& txid == gametxid ) { fprintf(stderr,"tokenid.%s txid.%s vs gametxid.%s player.%s\n",tokenid.GetHex().c_str(),txid.GetHex().c_str(),gametxid.GetHex().c_str(),playertxid.GetHex().c_str()); @@ -560,7 +560,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke //printf("batonht.%d keystrokes[%d]\n",batonht,numkeys); return(0); } else fprintf(stderr,"couldnt find baton\n"); - } + } else fprintf(stderr,"error with playerdata\n"); } else fprintf(stderr,"findbaton opret error\n"); } else From 31a18239da2ab69cbb4ad37f8610e9161e5592e9 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 06:42:41 -1100 Subject: [PATCH 051/390] Ptr --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 3c7ce393e..3da4b5977 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1230,7 +1230,7 @@ int32_t rogue_playerdata_validate(struct CCcontract_info *cp,std::vector Date: Mon, 18 Feb 2019 06:43:17 -1100 Subject: [PATCH 052/390] Test --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 3da4b5977..a11319daa 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1230,7 +1230,7 @@ int32_t rogue_playerdata_validate(struct CCcontract_info *cp,std::vector Date: Mon, 18 Feb 2019 18:47:07 +0100 Subject: [PATCH 053/390] update win makefile --- zcutil/build-win.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zcutil/build-win.sh b/zcutil/build-win.sh index ef0c09549..8cf1751af 100755 --- a/zcutil/build-win.sh +++ b/zcutil/build-win.sh @@ -1,5 +1,5 @@ #!/bin/bash -HOST=x86_64-w64-mingw32 +export HOST=x86_64-w64-mingw32 CXX=x86_64-w64-mingw32-g++-posix CC=x86_64-w64-mingw32-gcc-posix PREFIX="$(pwd)/depends/$HOST" From 3b0f836867283e68528b7bebd7632ac760bd0554 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 06:51:31 -1100 Subject: [PATCH 054/390] Prints --- src/cc/rogue_rpc.cpp | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index a11319daa..c3016c356 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -836,7 +836,7 @@ char *rogue_extractgame(char *str,int32_t *numkeysp,std::vector &newdat { UniValue obj; seed = rogue_gamefields(obj,maxplayers,buyin,gametxid,rogueaddr); - //fprintf(stderr,"(%s) found baton %s numkeys.%d seed.%llu playerdata.%d\n",pname.size()!=0?pname.c_str():Rogue_pname.c_str(),batontxid.ToString().c_str(),numkeys,(long long)seed,(int32_t)playerdata.size()); + fprintf(stderr,"(%s) found baton %s numkeys.%d seed.%llu playerdata.%d playertxid.%s\n",pname.size()!=0?pname.c_str():Rogue_pname.c_str(),batontxid.ToString().c_str(),numkeys,(long long)seed,(int32_t)playerdata.size(),playertxid.GetHex().c_str()); memset(&P,0,sizeof(P)); if ( playerdata.size() > 0 ) { @@ -1220,7 +1220,7 @@ UniValue rogue_setname(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) int32_t rogue_playerdata_validate(struct CCcontract_info *cp,std::vector playerdata,uint256 gametxid,CPubKey pk) { - char str[512],*keystrokes,rogueaddr[64],str2[67]; int32_t numkeys; std::vector newdata; uint64_t seed; uint256 playertxid; CPubKey roguepk; + char str[512],*keystrokes,rogueaddr[64],str2[67]; int32_t numkeys; std::vector newdata; uint64_t seed; uint256 playertxid; CPubKey roguepk; struct rogue_player P; roguepk = GetUnspendable(cp,0); GetCCaddress1of2(cp,rogueaddr,roguepk,pk); //fprintf(stderr,"call extractgame\n"); @@ -1230,7 +1230,14 @@ int32_t rogue_playerdata_validate(struct CCcontract_info *cp,std::vector no playerdata\n"); + } + fprintf(stderr,"playerdata: gold.%d hp.%d strength.%d/%d level.%d exp.%d dl.%d\n",P.gold,P.hitpoints,P.strength&0xffff,P.strength>>16,P.level,P.experience,P.dungeonlevel); + fprintf(stderr,"newdata[%d] != playerdata[%d], numkeys.%d %s pub.%s playertxid.%s\n",(int32_t)newdata.size(),(int32_t)playerdata.size(),numkeys,rogueaddr,pubkey33_str(str2,(uint8_t *)&pk),playertxid.GetHex().c_str()); } return(-1); } From 0d644e8be0518a2f54e732e6df27eb731f1dd2a2 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 06:52:11 -1100 Subject: [PATCH 055/390] Test --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index c3016c356..5c149e19e 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1220,7 +1220,7 @@ UniValue rogue_setname(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) int32_t rogue_playerdata_validate(struct CCcontract_info *cp,std::vector playerdata,uint256 gametxid,CPubKey pk) { - char str[512],*keystrokes,rogueaddr[64],str2[67]; int32_t numkeys; std::vector newdata; uint64_t seed; uint256 playertxid; CPubKey roguepk; struct rogue_player P; + char str[512],*keystrokes,rogueaddr[64],str2[67]; int32_t i,numkeys; std::vector newdata; uint64_t seed; uint256 playertxid; CPubKey roguepk; struct rogue_player P; roguepk = GetUnspendable(cp,0); GetCCaddress1of2(cp,rogueaddr,roguepk,pk); //fprintf(stderr,"call extractgame\n"); From f70593d5fbe61a79eb16aff958da2f72c2610b57 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 06:52:44 -1100 Subject: [PATCH 056/390] Size --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 5c149e19e..424799597 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1230,7 +1230,7 @@ int32_t rogue_playerdata_validate(struct CCcontract_info *cp,std::vector Date: Mon, 18 Feb 2019 07:02:58 -1100 Subject: [PATCH 057/390] Clear maxstre --- src/cc/rogue_rpc.cpp | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 424799597..1a60bc268 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1220,6 +1220,7 @@ UniValue rogue_setname(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) int32_t rogue_playerdata_validate(struct CCcontract_info *cp,std::vector playerdata,uint256 gametxid,CPubKey pk) { + static uint32_t good,bad; char str[512],*keystrokes,rogueaddr[64],str2[67]; int32_t i,numkeys; std::vector newdata; uint64_t seed; uint256 playertxid; CPubKey roguepk; struct rogue_player P; roguepk = GetUnspendable(cp,0); GetCCaddress1of2(cp,rogueaddr,roguepk,pk); @@ -1229,7 +1230,18 @@ int32_t rogue_playerdata_validate(struct CCcontract_info *cp,std::vector no playerdata\n"); } fprintf(stderr,"playerdata: gold.%d hp.%d strength.%d/%d level.%d exp.%d dl.%d\n",P.gold,P.hitpoints,P.strength&0xffff,P.strength>>16,P.level,P.experience,P.dungeonlevel); - fprintf(stderr,"newdata[%d] != playerdata[%d], numkeys.%d %s pub.%s playertxid.%s\n",(int32_t)newdata.size(),(int32_t)playerdata.size(),numkeys,rogueaddr,pubkey33_str(str2,(uint8_t *)&pk),playertxid.GetHex().c_str()); + fprintf(stderr,"newdata[%d] != playerdata[%d], numkeys.%d %s pub.%s playertxid.%s good.%d bad.%d\n",(int32_t)newdata.size(),(int32_t)playerdata.size(),numkeys,rogueaddr,pubkey33_str(str2,(uint8_t *)&pk),playertxid.GetHex().c_str()); } return(-1); } From 9ff01f928fa9fcc3f6971b9b162011d6c5a1041e Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 07:04:51 -1100 Subject: [PATCH 058/390] Test --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 1a60bc268..3730d2aa2 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1249,7 +1249,7 @@ int32_t rogue_playerdata_validate(struct CCcontract_info *cp,std::vector no playerdata\n"); } fprintf(stderr,"playerdata: gold.%d hp.%d strength.%d/%d level.%d exp.%d dl.%d\n",P.gold,P.hitpoints,P.strength&0xffff,P.strength>>16,P.level,P.experience,P.dungeonlevel); - fprintf(stderr,"newdata[%d] != playerdata[%d], numkeys.%d %s pub.%s playertxid.%s good.%d bad.%d\n",(int32_t)newdata.size(),(int32_t)playerdata.size(),numkeys,rogueaddr,pubkey33_str(str2,(uint8_t *)&pk),playertxid.GetHex().c_str()); + fprintf(stderr,"newdata[%d] != playerdata[%d], numkeys.%d %s pub.%s playertxid.%s good.%d bad.%d\n",(int32_t)newdata.size(),(int32_t)playerdata.size(),numkeys,rogueaddr,pubkey33_str(str2,(uint8_t *)&pk),playertxid.GetHex().c_str(),good,bad); } return(-1); } From 68cd9e8792e742817c5c9ddcba8592e84dfb20ce Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 07:15:34 -1100 Subject: [PATCH 059/390] Test --- src/cc/rogue_rpc.cpp | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 3730d2aa2..581603889 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1218,10 +1218,10 @@ UniValue rogue_setname(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) return(result); } -int32_t rogue_playerdata_validate(struct CCcontract_info *cp,std::vector playerdata,uint256 gametxid,CPubKey pk) +int32_t rogue_playerdata_validate(uint256 &playertxid,struct CCcontract_info *cp,std::vector playerdata,uint256 gametxid,CPubKey pk) { static uint32_t good,bad; - char str[512],*keystrokes,rogueaddr[64],str2[67]; int32_t i,numkeys; std::vector newdata; uint64_t seed; uint256 playertxid; CPubKey roguepk; struct rogue_player P; + char str[512],*keystrokes,rogueaddr[64],str2[67]; int32_t i,numkeys; std::vector newdata; uint64_t seed; CPubKey roguepk; struct rogue_player P; roguepk = GetUnspendable(cp,0); GetCCaddress1of2(cp,rogueaddr,roguepk,pk); //fprintf(stderr,"call extractgame\n"); @@ -1232,13 +1232,14 @@ int32_t rogue_playerdata_validate(struct CCcontract_info *cp,std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,maxplayers,decoded=0,regslot,ind,errflag,dispflag,score,numvouts; CTransaction vintx; CPubKey pk; uint256 hashBlock,gametxid,tokenid,batontxid,playertxid; int64_t buyin; std::vector playerdata,keystrokes; std::string symbol,pname; + CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,maxplayers,decoded=0,regslot,ind,errflag,dispflag,score,numvouts; CTransaction vintx; CPubKey pk; uint256 hashBlock,gametxid,tokenid,batontxid,playertxid,ptxid; int64_t buyin; std::vector playerdata,keystrokes; std::string symbol,pname; if ( strcmp(ASSETCHAINS_SYMBOL,"ROGUE") == 0 && height < 20000 ) return(true); if ( (numvouts= tx.vout.size()) > 1 ) @@ -1336,10 +1337,10 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C // verify pk belongs to this tx if ( playerdata.size() > 0 ) { - if ( rogue_playerdata_validate(cp,playerdata,gametxid,pk) < 0 ) + if ( rogue_playerdata_validate(ptxid,cp,playerdata,gametxid,pk) < 0 ) { - fprintf(stderr,"ht.%d gametxid.%s player.%s invalid playerdata[%d]\n",height,gametxid.GetHex().c_str(),playertxid.GetHex().c_str(),(int32_t)playerdata.size()); - } else fprintf(stderr,"ht.%d playertxid.%s validated\n",height,playertxid.GetHex().c_str()); + fprintf(stderr,"ht.%d gametxid.%s player.%s invalid playerdata[%d]\n",height,gametxid.GetHex().c_str(),ptxid.GetHex().c_str(),(int32_t)playerdata.size()); + } else fprintf(stderr,"ht.%d playertxid.%s validated\n",height,ptxid.GetHex().c_str()); } if ( funcid == 'Q' ) { From 3c9f9ce5542383ef69ac90dedd8c6937676d0f87 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 07:24:05 -1100 Subject: [PATCH 060/390] -prints --- src/cc/rogue/rogue.c | 2 +- src/cc/rogue_rpc.cpp | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 21c229860..786718039 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -650,7 +650,7 @@ int32_t _quit() } else { - fprintf(stderr,"'Q' answer (%c)\n",c); + //fprintf(stderr,"'Q' answer (%c)\n",c); move(0, 0); clrtoeol(); status(rs); diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 581603889..cf8e3feed 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -499,10 +499,10 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke if ( myIsutxo_spent(spenttxid,gametxid,maxplayers+i+1) < 0 ) { numvouts = matchtx.vout.size(); - fprintf(stderr,"matchtxid.%s matches.%d numvouts.%d\n",matchtx.GetHash().GetHex().c_str(),matches,numvouts); + //fprintf(stderr,"matchtxid.%s matches.%d numvouts.%d\n",matchtx.GetHash().GetHex().c_str(),matches,numvouts); if ( rogue_registeropretdecode(txid,tokenid,playertxid,matchtx.vout[numvouts-1].scriptPubKey) == 'R' )//&& txid == gametxid ) { - fprintf(stderr,"tokenid.%s txid.%s vs gametxid.%s player.%s\n",tokenid.GetHex().c_str(),txid.GetHex().c_str(),gametxid.GetHex().c_str(),playertxid.GetHex().c_str()); + //fprintf(stderr,"tokenid.%s txid.%s vs gametxid.%s player.%s\n",tokenid.GetHex().c_str(),txid.GetHex().c_str(),gametxid.GetHex().c_str(),playertxid.GetHex().c_str()); if ( tokenid != zeroid ) active = tokenid; else active = playertxid; @@ -836,7 +836,7 @@ char *rogue_extractgame(char *str,int32_t *numkeysp,std::vector &newdat { UniValue obj; seed = rogue_gamefields(obj,maxplayers,buyin,gametxid,rogueaddr); - fprintf(stderr,"(%s) found baton %s numkeys.%d seed.%llu playerdata.%d playertxid.%s\n",pname.size()!=0?pname.c_str():Rogue_pname.c_str(),batontxid.ToString().c_str(),numkeys,(long long)seed,(int32_t)playerdata.size(),playertxid.GetHex().c_str()); + //fprintf(stderr,"(%s) found baton %s numkeys.%d seed.%llu playerdata.%d playertxid.%s\n",pname.size()!=0?pname.c_str():Rogue_pname.c_str(),batontxid.ToString().c_str(),numkeys,(long long)seed,(int32_t)playerdata.size(),playertxid.GetHex().c_str()); memset(&P,0,sizeof(P)); if ( playerdata.size() > 0 ) { @@ -1339,8 +1339,8 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C { if ( rogue_playerdata_validate(ptxid,cp,playerdata,gametxid,pk) < 0 ) { - fprintf(stderr,"ht.%d gametxid.%s player.%s invalid playerdata[%d]\n",height,gametxid.GetHex().c_str(),ptxid.GetHex().c_str(),(int32_t)playerdata.size()); - } else fprintf(stderr,"ht.%d playertxid.%s validated\n",height,ptxid.GetHex().c_str()); + //fprintf(stderr,"ht.%d gametxid.%s player.%s invalid playerdata[%d]\n",height,gametxid.GetHex().c_str(),ptxid.GetHex().c_str(),(int32_t)playerdata.size()); + } //else fprintf(stderr,"ht.%d playertxid.%s validated\n",height,ptxid.GetHex().c_str()); } if ( funcid == 'Q' ) { From 84dacb5ff8c0c8fdd6db19ae7da1cd54ab65b3b7 Mon Sep 17 00:00:00 2001 From: ca333 Date: Mon, 18 Feb 2019 19:31:49 +0100 Subject: [PATCH 061/390] update Makefile_rogue --- src/cc/Makefile_rogue | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/cc/Makefile_rogue b/src/cc/Makefile_rogue index 543ab2895..45efdc803 100644 --- a/src/cc/Makefile_rogue +++ b/src/cc/Makefile_rogue @@ -23,14 +23,15 @@ $(TARGET): $(SOURCES) ifeq ($(OS),Darwin) $(CC_DARWIN) $(CFLAGS_DARWIN) $(DEBUGFLAGS) -o $(TARGET_DARWIN) -c $(SOURCES) -lncurses cp $(TARGET_DARWIN) ../libcc.dylib -else ifeq ($(OS),Linux) - $(CC) $(CFLAGS) $(DEBUGFLAGS) -o $(TARGET) -c $(SOURCES) -lncurses - cp $(TARGET) ../libcc.so -#else ifeq ($(WIN_HOST),True) - todo: pass ENV var from build.sh if WIN host -else +else ifeq ($(HOST),x86_64-w64-mingw32) $(info WINDOWS) $(CC_WIN) $(CFLAGS_WIN) $(DEBUGFLAGS) -o $(TARGET_WIN) -c $(SOURCES) -lncurses - cp $(TARGET_WIN) ../libcc.dll + cp $(TARGET_WIN) ../libcc.dll +#else ifeq ($(WIN_HOST),True) - todo: pass ENV var from build.sh if WIN host +else + $(info LINUX) + $(CC) $(CFLAGS) $(DEBUGFLAGS) -o $(TARGET) -c $(SOURCES) -lncurses + cp $(TARGET) ../libcc.so endif clean: From 7e3a9acab7578eef88e3d507279ae94f8944d84f Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 07:32:50 -1100 Subject: [PATCH 062/390] +gametxid --- src/cc/rogue_rpc.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index cf8e3feed..45e67d286 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1232,14 +1232,14 @@ int32_t rogue_playerdata_validate(uint256 &playertxid,struct CCcontract_info *cp if ( newdata == playerdata ) { good++; - fprintf(stderr,"good.%d bad.%d\n",good,bad); + fprintf(stderr,"%s good.%d bad.%d\n",gametxid.GetHex().c_str(),good,bad); return(0); } newdata[10] = newdata[11] = playerdata[10] = playerdata[11] = 0; if ( newdata == playerdata ) { good++; - fprintf(stderr,"matched after clearing maxstrength good.%d bad.%d\n",good,bad); + fprintf(stderr,"%s matched after clearing maxstrength good.%d bad.%d\n",gametxid.GetHex().c_str(),good,bad); return(0); } bad++; From 5bb65c9e8bb34c78bbf9df6dbd0850afd8fbd92a Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 07:35:29 -1100 Subject: [PATCH 063/390] Test --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 45e67d286..9c4463930 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1258,7 +1258,7 @@ int32_t rogue_playerdata_validate(uint256 &playertxid,struct CCcontract_info *cp bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,maxplayers,decoded=0,regslot,ind,errflag,dispflag,score,numvouts; CTransaction vintx; CPubKey pk; uint256 hashBlock,gametxid,tokenid,batontxid,playertxid,ptxid; int64_t buyin; std::vector playerdata,keystrokes; std::string symbol,pname; - if ( strcmp(ASSETCHAINS_SYMBOL,"ROGUE") == 0 && height < 20000 ) + if ( strcmp(ASSETCHAINS_SYMBOL,"ROGUE") == 0 && height < 21274 ) return(true); if ( (numvouts= tx.vout.size()) > 1 ) { From 7b43e451d0b1a1003be23f031b58b8df0b60a54b Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 07:39:50 -1100 Subject: [PATCH 064/390] -print --- src/cc/assets.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/assets.cpp b/src/cc/assets.cpp index 921d33d69..6e3fd5909 100644 --- a/src/cc/assets.cpp +++ b/src/cc/assets.cpp @@ -259,7 +259,7 @@ bool AssetsValidate(struct CCcontract_info *cpAssets,Eval* eval,const CTransacti return eval->Invalid("invalid refund for cancelbuy"); preventCCvins = 3; preventCCvouts = 0; - fprintf(stderr,"cancelbuy validated to origaddr.(%s)\n",origNormalAddr); + //fprintf(stderr,"cancelbuy validated to origaddr.(%s)\n",origNormalAddr); break; case 'B': // fillbuy: From 6019a16cf161eddb3c4e6901dd9bfcfe3cb4bff7 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 07:46:03 -1100 Subject: [PATCH 065/390] Test --- src/cc/rogue_rpc.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 9c4463930..d74bc9619 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1220,8 +1220,11 @@ UniValue rogue_setname(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) int32_t rogue_playerdata_validate(uint256 &playertxid,struct CCcontract_info *cp,std::vector playerdata,uint256 gametxid,CPubKey pk) { - static uint32_t good,bad; + static uint32_t good,bad; static uint256 prevgame; char str[512],*keystrokes,rogueaddr[64],str2[67]; int32_t i,numkeys; std::vector newdata; uint64_t seed; CPubKey roguepk; struct rogue_player P; + if ( gametxid == prevgame ) + return(0); + prevgame = gametxid; roguepk = GetUnspendable(cp,0); GetCCaddress1of2(cp,rogueaddr,roguepk,pk); //fprintf(stderr,"call extractgame\n"); @@ -1249,7 +1252,7 @@ int32_t rogue_playerdata_validate(uint256 &playertxid,struct CCcontract_info *cp { fprintf(stderr,"zero value character was killed -> no playerdata\n"); } - fprintf(stderr,"playerdata: gold.%d hp.%d strength.%d/%d level.%d exp.%d dl.%d\n",P.gold,P.hitpoints,P.strength&0xffff,P.strength>>16,P.level,P.experience,P.dungeonlevel); + fprintf(stderr,"%s playerdata: gold.%d hp.%d strength.%d/%d level.%d exp.%d dl.%d\n",gametxid.GetHex().c_str(),P.gold,P.hitpoints,P.strength&0xffff,P.strength>>16,P.level,P.experience,P.dungeonlevel); fprintf(stderr,"newdata[%d] != playerdata[%d], numkeys.%d %s pub.%s playertxid.%s good.%d bad.%d\n",(int32_t)newdata.size(),(int32_t)playerdata.size(),numkeys,rogueaddr,pubkey33_str(str2,(uint8_t *)&pk),playertxid.GetHex().c_str(),good,bad); } return(-1); From 8ac6e7458b2a3ffd982c2d3dd4151e63b9a17f9d Mon Sep 17 00:00:00 2001 From: ca333 Date: Mon, 18 Feb 2019 20:55:08 +0100 Subject: [PATCH 066/390] test --- src/cc/rogue/mdport.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/mdport.c b/src/cc/rogue/mdport.c index 9d6c7d2c6..f87650f38 100644 --- a/src/cc/rogue/mdport.c +++ b/src/cc/rogue/mdport.c @@ -33,7 +33,7 @@ #include #if defined(_WIN32) -#include +#include #include #include #include From 846e102e7b9b4774552ab05dabe4b319974b4772 Mon Sep 17 00:00:00 2001 From: ca333 Date: Mon, 18 Feb 2019 22:13:28 +0100 Subject: [PATCH 067/390] fix --- src/cc/rogue/mdport.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/mdport.c b/src/cc/rogue/mdport.c index f87650f38..d9c4e9c21 100644 --- a/src/cc/rogue/mdport.c +++ b/src/cc/rogue/mdport.c @@ -34,7 +34,7 @@ #if defined(_WIN32) #include -#include +#include #include #include #pragma warning( disable: 4201 ) From 10dfaedb062d1c7a8520d41a3ae9c5d72f8695d2 Mon Sep 17 00:00:00 2001 From: ca333 Date: Mon, 18 Feb 2019 23:23:26 +0100 Subject: [PATCH 068/390] fix --- src/cc/rogue/mdport.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/mdport.c b/src/cc/rogue/mdport.c index d9c4e9c21..988e1c7b7 100644 --- a/src/cc/rogue/mdport.c +++ b/src/cc/rogue/mdport.c @@ -40,7 +40,7 @@ #pragma warning( disable: 4201 ) #include #pragma warning( default: 4201 ) -#include +#include #undef MOUSE_MOVED #endif From 640f3e0699cfd2d93c6ceb7a2c6977a0d7bb5bbe Mon Sep 17 00:00:00 2001 From: ca333 Date: Tue, 19 Feb 2019 00:15:41 +0100 Subject: [PATCH 069/390] resolve conflict --- src/cc/rogue_rpc.cpp | 121 +++++++++++++++++++++++++++++++------------ 1 file changed, 88 insertions(+), 33 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index ef24489ba..d74bc9619 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -265,7 +265,7 @@ int32_t rogue_iamregistered(int32_t maxplayers,uint256 gametxid,CTransaction tx, vout = i+1; if ( myIsutxo_spent(spenttxid,gametxid,vout) >= 0 ) { - if ( GetTransaction(spenttxid,spenttx,hashBlock,false) != 0 && spenttx.vout.size() > 0 ) + if ( myGetTransaction(spenttxid,spenttx,hashBlock) != 0 && spenttx.vout.size() > 0 ) { Getscriptaddress(destaddr,spenttx.vout[0].scriptPubKey); if ( strcmp(myrogueaddr,destaddr) == 0 ) @@ -296,7 +296,7 @@ int32_t rogue_playersalive(int32_t &numplayers,uint256 gametxid,int32_t maxplaye uint64_t rogue_gamefields(UniValue &obj,int64_t maxplayers,int64_t buyin,uint256 gametxid,char *myrogueaddr) { CBlockIndex *pindex; int32_t ht,delay,numplayers; uint256 hashBlock; uint64_t seed=0; char cmd[512]; CTransaction tx; - if ( GetTransaction(gametxid,tx,hashBlock,false) != 0 && (pindex= komodo_blockindex(hashBlock)) != 0 ) + if ( myGetTransaction(gametxid,tx,hashBlock) != 0 && (pindex= komodo_blockindex(hashBlock)) != 0 ) { ht = pindex->GetHeight(); delay = ROGUE_REGISTRATION * (maxplayers > 1); @@ -329,7 +329,7 @@ int32_t rogue_isvalidgame(struct CCcontract_info *cp,int32_t &gameheight,CTransa { uint256 hashBlock; int32_t i,numvouts; char coinaddr[64]; CPubKey roguepk; uint64_t txfee = 10000; buyin = maxplayers = 0; - if ( GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size()) > 1 ) + if ( myGetTransaction(txid,tx,hashBlock) != 0 && (numvouts= tx.vout.size()) > 1 ) { gameheight = komodo_blockheight(hashBlock); if ( IsCClibvout(cp,tx,0,cp->unspendableCCaddr) >= txfee && myIsutxo_spentinmempool(ignoretxid,ignorevin,txid,0) == 0 ) @@ -434,14 +434,14 @@ int32_t rogue_iterateplayer(uint256 ®istertxid,uint256 firsttxid,int32_t firs int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,uint256 &tokenid,CPubKey &pk,std::vector &playerdata,std::string &symbol,std::string &pname,uint256 playertxid) { uint256 origplayertxid,hashBlock,gametxid,registertxid; CTransaction gametx,playertx,highlandertx; std::vector vopret; uint8_t *script,e,f; int32_t i,regslot,gameheight,numvouts,maxplayers; int64_t buyin; - if ( GetTransaction(playertxid,playertx,hashBlock,false) != 0 && (numvouts= playertx.vout.size()) > 0 ) + if ( myGetTransaction(playertxid,playertx,hashBlock) != 0 && (numvouts= playertx.vout.size()) > 0 ) { if ( (f= rogue_highlanderopretdecode(gametxid,tokenid,regslot,pk,playerdata,symbol,pname,playertx.vout[numvouts-1].scriptPubKey)) == 'H' || f == 'Q' ) { if ( tokenid != zeroid ) { playertxid = tokenid; - if ( GetTransaction(playertxid,playertx,hashBlock,false) == 0 || (numvouts= playertx.vout.size()) <= 0 ) + if ( myGetTransaction(playertxid,playertx,hashBlock) == 0 || (numvouts= playertx.vout.size()) <= 0 ) { fprintf(stderr,"couldnt get tokenid.%s\n",playertxid.GetHex().c_str()); return(-2); @@ -478,9 +478,10 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke playertxid = zeroid; for (i=0; i= 0 ) { - if ( GetTransaction(spenttxid,spenttx,hashBlock,false) != 0 && spenttx.vout.size() > 0 ) + if ( myGetTransaction(spenttxid,spenttx,hashBlock) != 0 && spenttx.vout.size() > 0 ) { numplayers++; Getscriptaddress(ccaddr,spenttx.vout[0].scriptPubKey); @@ -524,7 +525,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke txid = spenttxid; if ( spentvini != 0 ) return(-3); - if ( keystrokesp != 0 && GetTransaction(spenttxid,spenttx,hashBlock,false) != 0 && spenttx.vout.size() >= 2 ) + if ( keystrokesp != 0 && myGetTransaction(spenttxid,spenttx,hashBlock) != 0 && spenttx.vout.size() >= 2 ) { uint256 g,b; CPubKey p; std::vector k; if ( rogue_keystrokesopretdecode(g,b,p,k,spenttx.vout[spenttx.vout.size()-1].scriptPubKey) == 'K' ) @@ -541,13 +542,14 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke fprintf(stderr,"rogue_findbaton n.%d, seems something is wrong\n",n); return(-5); } + //fprintf(stderr,"n.%d txid.%s\n",n,txid.GetHex().c_str()); } //fprintf(stderr,"set baton %s\n",txid.GetHex().c_str()); batontxid = txid; batonvout = 0; // not vini // how to detect timeout, bailedout, highlander hashBlock = zeroid; - if ( GetTransaction(batontxid,batontx,hashBlock,false) != 0 && batontx.vout.size() > 0 ) + if ( myGetTransaction(batontxid,batontx,hashBlock) != 0 && batontx.vout.size() > 0 ) { if ( hashBlock == zeroid ) batonht = komodo_nextheight(); @@ -555,10 +557,10 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke return(-4); else batonht = pindex->GetHeight(); batonvalue = batontx.vout[0].nValue; - //printf("keystrokes[%d]\n",numkeys); + //printf("batonht.%d keystrokes[%d]\n",batonht,numkeys); return(0); - } - } + } else fprintf(stderr,"couldnt find baton\n"); + } else fprintf(stderr,"error with playerdata\n"); } else fprintf(stderr,"findbaton opret error\n"); } else @@ -577,7 +579,7 @@ void rogue_gameplayerinfo(struct CCcontract_info *cp,UniValue &obj,uint256 gamet destaddr[0] = 0; if ( myIsutxo_spent(spenttxid,gametxid,vout) >= 0 ) { - if ( GetTransaction(spenttxid,spenttx,hashBlock,false) != 0 && spenttx.vout.size() > 0 ) + if ( myGetTransaction(spenttxid,spenttx,hashBlock) != 0 && spenttx.vout.size() > 0 ) Getscriptaddress(destaddr,spenttx.vout[0].scriptPubKey); } obj.push_back(Pair("slot",(int64_t)vout-1)); @@ -585,7 +587,7 @@ void rogue_gameplayerinfo(struct CCcontract_info *cp,UniValue &obj,uint256 gamet { if ( CCgettxout(gametxid,maxplayers+vout,1) == 10000 ) { - if ( GetTransaction(batontxid,batontx,hashBlock,false) != 0 && batontx.vout.size() > 1 ) + if ( myGetTransaction(batontxid,batontx,hashBlock) != 0 && batontx.vout.size() > 1 ) { if ( rogue_registeropretdecode(gtxid,tokenid,ptxid,batontx.vout[batontx.vout.size()-1].scriptPubKey) == 'R' && ptxid == playertxid && gtxid == gametxid ) obj.push_back(Pair("status","registered")); @@ -758,7 +760,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) if ( playertxid != zeroid ) { voutPubkeysEmpty.push_back(burnpk); - if ( GetTransaction(playertxid,playertx,hashBlock,false) != 0 ) + if ( myGetTransaction(playertxid,playertx,hashBlock) != 0 ) { if ( (funcid= DecodeTokenOpRet(playertx.vout.back().scriptPubKey, e, tid, voutPubkeys, vopretExtra)) != 0) { // if token in the opret @@ -834,7 +836,7 @@ char *rogue_extractgame(char *str,int32_t *numkeysp,std::vector &newdat { UniValue obj; seed = rogue_gamefields(obj,maxplayers,buyin,gametxid,rogueaddr); - //fprintf(stderr,"(%s) found baton %s numkeys.%d seed.%llu playerdata.%d\n",pname.size()!=0?pname.c_str():Rogue_pname.c_str(),batontxid.ToString().c_str(),numkeys,(long long)seed,(int32_t)playerdata.size()); + //fprintf(stderr,"(%s) found baton %s numkeys.%d seed.%llu playerdata.%d playertxid.%s\n",pname.size()!=0?pname.c_str():Rogue_pname.c_str(),batontxid.ToString().c_str(),numkeys,(long long)seed,(int32_t)playerdata.size(),playertxid.GetHex().c_str()); memset(&P,0,sizeof(P)); if ( playerdata.size() > 0 ) { @@ -872,8 +874,8 @@ char *rogue_extractgame(char *str,int32_t *numkeysp,std::vector &newdat sprintf(str,"extracted $$$gold.%d hp.%d strength.%d/%d level.%d exp.%d dl.%d\n",endP.gold,endP.hitpoints,endP.strength&0xffff,endP.strength>>16,endP.level,endP.experience,endP.dungeonlevel); fprintf(stderr,"%s\n",str); } else num = 0; - } - } + } else fprintf(stderr,"extractgame: couldnt find baton\n"); + } else fprintf(stderr,"extractgame: invalid game\n"); *numkeysp = numkeys; return(keystrokes); } @@ -1174,7 +1176,7 @@ UniValue rogue_games(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) //char str[65]; fprintf(stderr,"%s check %s/v%d %.8f\n",coinaddr,uint256_str(str,txid),vout,(double)it->second.satoshis/COIN); if ( vout == 0 ) { - if ( GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size()) > 1 ) + if ( myGetTransaction(txid,tx,hashBlock) != 0 && (numvouts= tx.vout.size()) > 1 ) { if ( rogue_registeropretdecode(gametxid,tokenid,playertxid,tx.vout[numvouts-1].scriptPubKey) == 'R' ) { @@ -1216,9 +1218,51 @@ UniValue rogue_setname(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) return(result); } +int32_t rogue_playerdata_validate(uint256 &playertxid,struct CCcontract_info *cp,std::vector playerdata,uint256 gametxid,CPubKey pk) +{ + static uint32_t good,bad; static uint256 prevgame; + char str[512],*keystrokes,rogueaddr[64],str2[67]; int32_t i,numkeys; std::vector newdata; uint64_t seed; CPubKey roguepk; struct rogue_player P; + if ( gametxid == prevgame ) + return(0); + prevgame = gametxid; + roguepk = GetUnspendable(cp,0); + GetCCaddress1of2(cp,rogueaddr,roguepk,pk); + //fprintf(stderr,"call extractgame\n"); + if ( (keystrokes= rogue_extractgame(str,&numkeys,newdata,seed,playertxid,cp,gametxid,rogueaddr)) != 0 ) + { + free(keystrokes); + //fprintf(stderr,"extracted.(%s)\n",str); + if ( newdata == playerdata ) + { + good++; + fprintf(stderr,"%s good.%d bad.%d\n",gametxid.GetHex().c_str(),good,bad); + return(0); + } + newdata[10] = newdata[11] = playerdata[10] = playerdata[11] = 0; + if ( newdata == playerdata ) + { + good++; + fprintf(stderr,"%s matched after clearing maxstrength good.%d bad.%d\n",gametxid.GetHex().c_str(),good,bad); + return(0); + } + bad++; + for (i=0; i no playerdata\n"); + } + fprintf(stderr,"%s playerdata: gold.%d hp.%d strength.%d/%d level.%d exp.%d dl.%d\n",gametxid.GetHex().c_str(),P.gold,P.hitpoints,P.strength&0xffff,P.strength>>16,P.level,P.experience,P.dungeonlevel); + fprintf(stderr,"newdata[%d] != playerdata[%d], numkeys.%d %s pub.%s playertxid.%s good.%d bad.%d\n",(int32_t)newdata.size(),(int32_t)playerdata.size(),numkeys,rogueaddr,pubkey33_str(str2,(uint8_t *)&pk),playertxid.GetHex().c_str(),good,bad); + } + return(-1); +} + bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { - CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,maxplayers,decoded=0,regslot,ind,errflag,dispflag,score,numvouts; CTransaction vintx; CPubKey pk; uint256 hashBlock,gametxid,tokenid,batontxid,playertxid; int64_t buyin; std::vector playerdata,keystrokes; std::string symbol,pname; + CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,maxplayers,decoded=0,regslot,ind,errflag,dispflag,score,numvouts; CTransaction vintx; CPubKey pk; uint256 hashBlock,gametxid,tokenid,batontxid,playertxid,ptxid; int64_t buyin; std::vector playerdata,keystrokes; std::string symbol,pname; + if ( strcmp(ASSETCHAINS_SYMBOL,"ROGUE") == 0 && height < 21274 ) + return(true); if ( (numvouts= tx.vout.size()) > 1 ) { scriptPubKey = tx.vout[numvouts-1].scriptPubKey; @@ -1233,10 +1277,7 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C { if ( (funcid= rogue_registeropretdecode(gametxid,tokenid,playertxid,scriptPubKey)) == 0 ) { - funcid = 'Q'; fprintf(stderr,"ht.%d couldnt decode tokens opret (%c)\n",height,script[1]); - if ( height < 20000 ) - e = EVAL_ROGUE; } else e = EVAL_ROGUE, decoded = 1; } else e = EVAL_ROGUE, decoded = 1; } @@ -1250,8 +1291,8 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C case 'G': if ( (funcid= rogue_newgameopreturndecode(buyin,maxplayers,scriptPubKey)) != 'G' ) { - fprintf(stderr,"height.%d couldnt decode newgame opret\n",height); - if ( height > 20000 ) + //fprintf(stderr,"height.%d couldnt decode newgame opret\n",height); + //if ( height > 20000 ) return eval->Invalid("couldnt decode newgame opret"); } // validate newgame tx @@ -1260,8 +1301,8 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C case 'R': if ( (funcid= rogue_registeropretdecode(gametxid,tokenid,playertxid,scriptPubKey)) != 'R' ) { - fprintf(stderr,"height.%d couldnt decode register opret\n",height); - if ( height > 20000 ) + //fprintf(stderr,"height.%d couldnt decode register opret\n",height); + //if ( height > 20000 ) return eval->Invalid("couldnt decode register opret"); } // validation is done below @@ -1269,8 +1310,8 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C case 'K': if ( (funcid= rogue_keystrokesopretdecode(gametxid,batontxid,pk,keystrokes,scriptPubKey)) != 'K' ) { - fprintf(stderr,"height.%d couldnt decode keystrokes opret\n",height); - if ( height > 20000 ) + //fprintf(stderr,"height.%d couldnt decode keystrokes opret\n",height); + //if ( height > 20000 ) return eval->Invalid("couldnt decode keystrokes opret"); } // validate keystrokes are from the correct pk. might need to add vin @@ -1279,8 +1320,8 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C case 'H': case 'Q': if ( (f= rogue_highlanderopretdecode(gametxid,tokenid,regslot,pk,playerdata,symbol,pname,scriptPubKey)) != funcid ) { - fprintf(stderr,"height.%d couldnt decode H/Q opret\n",height); - if ( height > 20000 ) + //fprintf(stderr,"height.%d couldnt decode H/Q opret\n",height); + //if ( height > 20000 ) return eval->Invalid("couldnt decode H/Q opret"); } // validation is done below @@ -1292,12 +1333,26 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C } switch ( funcid ) { - case 'G': // newgame case 'R': // register - case 'K': // keystrokes + return(true); case 'H': // win case 'Q': // bailout - //fprintf(stderr,"ht.%d rogue.(%c)\n",height,script[1]); + // verify pk belongs to this tx + if ( playerdata.size() > 0 ) + { + if ( rogue_playerdata_validate(ptxid,cp,playerdata,gametxid,pk) < 0 ) + { + //fprintf(stderr,"ht.%d gametxid.%s player.%s invalid playerdata[%d]\n",height,gametxid.GetHex().c_str(),ptxid.GetHex().c_str(),(int32_t)playerdata.size()); + } //else fprintf(stderr,"ht.%d playertxid.%s validated\n",height,ptxid.GetHex().c_str()); + } + if ( funcid == 'Q' ) + { + // verify vin/vout + } + else // 'H' + { + // verify vin/vout + } return(true); break; default: From aa60acbf2764632b9e0a206364a959f503f0c729 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 21:15:47 -1100 Subject: [PATCH 070/390] ROGUE_MAXTOTAL = strength*2, ISMANY -> 1 --- src/cc/rogue/init.c | 11 +++++++++-- src/cc/rogue/pack.c | 6 +++--- src/cc/rogue/rogue.h | 3 +++ 3 files changed, 15 insertions(+), 5 deletions(-) diff --git a/src/cc/rogue/init.c b/src/cc/rogue/init.c index 30370f958..ffc0b3707 100644 --- a/src/cc/rogue/init.c +++ b/src/cc/rogue/init.c @@ -22,6 +22,13 @@ */ void rogue_restoreobject(THING *o,struct rogue_packitem *item); +int32_t rogue_total(THING *o) +{ + if ( (o->o_flags & ISMANY) != 0 ) + return(1); + else return(o->o_count); +} + void restore_player(struct rogue_state *rs) { int32_t i,total = 0; THING *obj; @@ -38,8 +45,8 @@ void restore_player(struct rogue_state *rs) { obj = new_item(); rogue_restoreobject(obj,&rs->P.roguepack[i]); - total += obj->o_count; - if ( total > pstats.s_str*3 ) + total += rogue_total(obj); + if ( total > ROGUE_MAXTOTAL ) break; add_pack(rs,obj,TRUE); } diff --git a/src/cc/rogue/pack.c b/src/cc/rogue/pack.c index e4ceee689..776669b3b 100644 --- a/src/cc/rogue/pack.c +++ b/src/cc/rogue/pack.c @@ -166,16 +166,16 @@ int32_t num_packitems(struct rogue_state *rs) if ( list->o_packch != 0 ) { n++; - total += list->o_count; + total += rogue_total(list); } } if ( rs->guiflag != 0 ) { char str[MAXSTR]; - sprintf(str,"strength*3 %d vs total.%d vs %d inventory letters\n",pstats.s_str*3,total,n); + sprintf(str,"strength*2 %d vs total.%d vs %d inventory letters\n",ROGUE_MAXTOTAL,total,n); add_line(rs,"%s",str); } - if ( total > pstats.s_str*3 ) + if ( total > ROGUE_MAXTOTAL ) return(MAXPACK); return(n); } diff --git a/src/cc/rogue/rogue.h b/src/cc/rogue/rogue.h index 515c1d44a..9339b630f 100644 --- a/src/cc/rogue/rogue.h +++ b/src/cc/rogue/rogue.h @@ -381,6 +381,9 @@ void restore_player(struct rogue_state *rs); int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t num,struct rogue_player *player,int32_t sleepmillis); void rogue_bailout(struct rogue_state *rs); +#define ROGUE_MAXTOTAL (pstats.s_str*2) +int32_t rogue_total(THING *o); + /* * Help list */ From f77c99d7817ea50bb83c6d1d3929434016a8fe3e Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 21:16:32 -1100 Subject: [PATCH 071/390] int32_t rogue_total(THING *o); --- src/cc/rogue/rogue.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/rogue.h b/src/cc/rogue/rogue.h index 9339b630f..f687b170c 100644 --- a/src/cc/rogue/rogue.h +++ b/src/cc/rogue/rogue.h @@ -382,7 +382,6 @@ int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t nu void rogue_bailout(struct rogue_state *rs); #define ROGUE_MAXTOTAL (pstats.s_str*2) -int32_t rogue_total(THING *o); /* * Help list @@ -806,6 +805,7 @@ THING *new_item(void); THING *new_thing(struct rogue_state *rs); void end_line(struct rogue_state *rs); int32_t num_packitems(struct rogue_state *rs); +int32_t rogue_total(THING *o); void runners(struct rogue_state *rs,int); void land(struct rogue_state *rs,int); From 2c6640cdd4c7774a25cce074be62ea3fd772563f Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 22:21:26 -1100 Subject: [PATCH 072/390] Change multiplayer payout to 2x, if amulet then 10x --- src/cc/rogue/rogue_player.h | 2 +- src/cc/rogue/state.c | 1 + src/cc/rogue_rpc.cpp | 8 +++++--- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/src/cc/rogue/rogue_player.h b/src/cc/rogue/rogue_player.h index 1319b3213..e6b7a69e6 100644 --- a/src/cc/rogue/rogue_player.h +++ b/src/cc/rogue/rogue_player.h @@ -25,7 +25,7 @@ struct rogue_packitem }; struct rogue_player { - int32_t gold,hitpoints,strength,level,experience,packsize,dungeonlevel,pad; + int32_t gold,hitpoints,strength,level,experience,packsize,dungeonlevel,amulet; struct rogue_packitem roguepack[MAXPACK]; }; int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t num,struct rogue_player *player,int32_t sleepmillis); diff --git a/src/cc/rogue/state.c b/src/cc/rogue/state.c index 778540b68..589f77422 100644 --- a/src/cc/rogue/state.c +++ b/src/cc/rogue/state.c @@ -1452,6 +1452,7 @@ rs_write_object(struct rogue_state *rs,FILE *savef, THING *o) rs->P.level = pstats.s_lvl; rs->P.experience = pstats.s_exp; rs->P.dungeonlevel = level; + rs->P.amulet = amulet; //fprintf(stderr,"%ld gold.%d hp.%d strength.%d/%d level.%d exp.%d %d\n",ftell(savef),purse,max_hp,pstats.s_str,max_stats.s_str,pstats.s_lvl,pstats.s_exp,level); } //fprintf(stderr,"object (%s) x.%d y.%d type.%d pack.(%c:%d)\n",inv_name(o,FALSE),o->_o._o_pos.x,o->_o._o_pos.y,o->_o._o_type,o->_o._o_packch,o->_o._o_packch); diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index d74bc9619..a7bbaa489 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -957,7 +957,7 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param else { funcid = 'H'; - mult = 1000000; + mult = 200000; } if ( (params= cclib_reparse(&n,params)) != 0 ) { @@ -1008,11 +1008,13 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param cpTokens = CCinit(&tokensC, EVAL_TOKENS); mtx.vout.push_back(MakeCC1vout(EVAL_TOKENS, txfee, GetUnspendable(cpTokens,NULL))); // marker to token cc addr, burnable and validated mtx.vout.push_back(MakeTokensCC1vout(cp->evalcode,1,mypk)); - fprintf(stderr,"\nextracted $$$gold.%d hp.%d strength.%d/%d level.%d exp.%d dl.%d n.%d size.%d\n",P.gold,P.hitpoints,P.strength&0xffff,P.strength>>16,P.level,P.experience,P.dungeonlevel,n,(int32_t)sizeof(P)); + fprintf(stderr,"\nextracted $$$gold.%d hp.%d strength.%d/%d level.%d exp.%d dl.%d n.%d amulet.%d\n",P.gold,P.hitpoints,P.strength&0xffff,P.strength>>16,P.level,P.experience,P.dungeonlevel,n,P.amulet); + if ( P.amulet != 0 ) + mult *= 5; cashout = (uint64_t)P.gold * mult; if ( funcid == 'H' && maxplayers > 1 ) { - if ( numplayers != maxplayers || (numplayers - rogue_playersalive(tmp,gametxid,maxplayers)) > 1 && (P.dungeonlevel > 1 || P.gold < 10000 || P.level < 20) ) + if ( (numplayers != maxplayers || (numplayers - rogue_playersalive(tmp,gametxid,maxplayers)) > 1) && P.amulet == 0 ) return(cclib_error(result,"highlander must be a winner or last one standing")); cashout += numplayers * buyin; } From 1c85c52f49c17e7520ff253aaeee70d37a9233d8 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 23:04:17 -1100 Subject: [PATCH 073/390] You can ignore ./makerogue: shell: not found --- src/cc/makerogue | 1 + src/cc/rogue_rpc.cpp | 50 ++++++++++++++++++++++++-------------------- 2 files changed, 28 insertions(+), 23 deletions(-) diff --git a/src/cc/makerogue b/src/cc/makerogue index 249e646f5..fb7a53cec 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -1,4 +1,5 @@ #!/bin/sh +echo "you can ignore ./makerogue: shell: not found" cd rogue; ./configure # only need this first time make; cd .. diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index a7bbaa489..1ca1bce88 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -325,18 +325,20 @@ uint64_t rogue_gamefields(UniValue &obj,int64_t maxplayers,int64_t buyin,uint256 return(seed); } -int32_t rogue_isvalidgame(struct CCcontract_info *cp,int32_t &gameheight,CTransaction &tx,int64_t &buyin,int32_t &maxplayers,uint256 txid) +int32_t rogue_isvalidgame(struct CCcontract_info *cp,int32_t &gameheight,CTransaction &tx,int64_t &buyin,int32_t &maxplayers,uint256 txid,int32_t unspentv0) { uint256 hashBlock; int32_t i,numvouts; char coinaddr[64]; CPubKey roguepk; uint64_t txfee = 10000; buyin = maxplayers = 0; if ( myGetTransaction(txid,tx,hashBlock) != 0 && (numvouts= tx.vout.size()) > 1 ) { gameheight = komodo_blockheight(hashBlock); - if ( IsCClibvout(cp,tx,0,cp->unspendableCCaddr) >= txfee && myIsutxo_spentinmempool(ignoretxid,ignorevin,txid,0) == 0 ) + if ( IsCClibvout(cp,tx,0,cp->unspendableCCaddr) == txfee && (unspentv0 == 0 || CCgettxout(playertxid,0,1) == txfee) ) { if ( rogue_newgameopreturndecode(buyin,maxplayers,tx.vout[numvouts-1].scriptPubKey) == 'G' ) { - if ( numvouts > maxplayers+1 ) + if ( maxplayers < 1 || maxplayers > ROGUE_MAXPLAYERS || buyin < 0 ) + return(-6); + if ( numvouts > 2*maxplayers+1 ) { for (i=0; i 0 ) { gametxid = juint256(jitem(params,0)); - if ( (err= rogue_isvalidgame(cp,gameheight,tx,buyin,maxplayers,gametxid)) == 0 ) + if ( (err= rogue_isvalidgame(cp,gameheight,tx,buyin,maxplayers,gametxid,1)) == 0 ) { if ( n > 1 ) { @@ -803,7 +806,7 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param mypk = pubkey2pk(Mypubkey()); roguepk = GetUnspendable(cp,0); GetCCaddress1of2(cp,destaddr,roguepk,mypk); - if ( rogue_isvalidgame(cp,gameheight,tx,buyin,maxplayers,gametxid) == 0 ) + if ( rogue_isvalidgame(cp,gameheight,tx,buyin,maxplayers,gametxid,1) == 0 ) { if ( rogue_findbaton(cp,playertxid,0,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,tx,maxplayers,destaddr,numplayers,symbol,pname) == 0 ) { @@ -811,7 +814,7 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param result.push_back(Pair("playertxid",playertxid.GetHex())); if ( maxplayers == 1 || nextheight <= batonht+ROGUE_MAXKEYSTROKESGAP ) { - mtx.vin.push_back(CTxIn(batontxid,batonvout,CScript())); + mtx.vin.push_back(CTxIn(batontxid,batonvout,CScript())); // this validates user mtx.vout.push_back(MakeCC1of2vout(cp->evalcode,batonvalue-txfee,roguepk,mypk)); Myprivkey(mypriv); CCaddr1of2set(cp,roguepk,mypk,mypriv,destaddr); @@ -830,7 +833,7 @@ char *rogue_extractgame(char *str,int32_t *numkeysp,std::vector &newdat roguepk = GetUnspendable(cp,0); *numkeysp = 0; seed = 0; - if ( (err= rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid)) == 0 ) + if ( (err= rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid,0)) == 0 ) { if ( rogue_findbaton(cp,playertxid,&keystrokes,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,rogueaddr,numplayers,symbol,pname) == 0 ) { @@ -965,7 +968,7 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param { gametxid = juint256(jitem(params,0)); result.push_back(Pair("gametxid",gametxid.GetHex())); - if ( (err= rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid)) == 0 ) + if ( (err= rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid,1)) == 0 ) { if ( rogue_findbaton(cp,playertxid,&keystrokes,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,myrogueaddr,numplayers,symbol,pname) == 0 ) { @@ -1078,7 +1081,7 @@ UniValue rogue_gameinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { txid = juint256(jitem(params,0)); result.push_back(Pair("gametxid",txid.GetHex())); - if ( rogue_isvalidgame(cp,gameheight,tx,buyin,maxplayers,txid) == 0 ) + if ( rogue_isvalidgame(cp,gameheight,tx,buyin,maxplayers,txid,0) == 0 ) { result.push_back(Pair("result","success")); result.push_back(Pair("gameheight",(int64_t)gameheight)); @@ -1118,7 +1121,7 @@ UniValue rogue_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) //char str[65]; fprintf(stderr,"%s check %s/v%d %.8f\n",coinaddr,uint256_str(str,txid),vout,(double)it->second.satoshis/COIN); if ( it->second.satoshis != txfee || vout != 0 ) // reject any that are not highlander markers continue; - if ( rogue_isvalidgame(cp,gameheight,tx,buyin,maxplayers,txid) == 0 && nextheight <= gameheight+ROGUE_MAXKEYSTROKESGAP ) + if ( rogue_isvalidgame(cp,gameheight,tx,buyin,maxplayers,txid,1) == 0 && nextheight <= gameheight+ROGUE_MAXKEYSTROKESGAP ) { rogue_playersalive(numplayers,txid,maxplayers); if ( numplayers < maxplayers ) @@ -1182,7 +1185,7 @@ UniValue rogue_games(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { if ( rogue_registeropretdecode(gametxid,tokenid,playertxid,tx.vout[numvouts-1].scriptPubKey) == 'R' ) { - if ( rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid) == 0 ) + if ( rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid,0) == 0 ) { if ( CCgettxout(txid,vout,1) < 0 ) b.push_back(gametxid.GetHex()); @@ -1262,7 +1265,7 @@ int32_t rogue_playerdata_validate(uint256 &playertxid,struct CCcontract_info *cp bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { - CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,maxplayers,decoded=0,regslot,ind,errflag,dispflag,score,numvouts; CTransaction vintx; CPubKey pk; uint256 hashBlock,gametxid,tokenid,batontxid,playertxid,ptxid; int64_t buyin; std::vector playerdata,keystrokes; std::string symbol,pname; + CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,maxplayers,decoded=0,regslot,ind,errs,dispflag,gameheight,score,numvouts; CTransaction vintx,gametx; CPubKey pk; uint256 hashBlock,gametxid,tokenid,batontxid,playertxid,ptxid; int64_t buyin; std::vector playerdata,keystrokes; std::string symbol,pname; if ( strcmp(ASSETCHAINS_SYMBOL,"ROGUE") == 0 && height < 21274 ) return(true); if ( (numvouts= tx.vout.size()) > 1 ) @@ -1291,13 +1294,12 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C switch ( funcid ) { case 'G': - if ( (funcid= rogue_newgameopreturndecode(buyin,maxplayers,scriptPubKey)) != 'G' ) + if ( (err= rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid,0)) != 0 ) { - //fprintf(stderr,"height.%d couldnt decode newgame opret\n",height); + fprintf(stderr,"height.%d rogue_isvalidgame error.%d\n",height,err); //if ( height > 20000 ) - return eval->Invalid("couldnt decode newgame opret"); + return eval->Invalid("invalid gametxid"); } - // validate newgame tx return(true); break; case 'R': @@ -1307,6 +1309,7 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C //if ( height > 20000 ) return eval->Invalid("couldnt decode register opret"); } + // baton is created // validation is done below break; case 'K': @@ -1316,7 +1319,7 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C //if ( height > 20000 ) return eval->Invalid("couldnt decode keystrokes opret"); } - // validate keystrokes are from the correct pk. might need to add vin + // spending the baton proves it is the user if the pk is the signer return(true); break; case 'H': case 'Q': @@ -1326,7 +1329,8 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C //if ( height > 20000 ) return eval->Invalid("couldnt decode H/Q opret"); } - // validation is done below + // spending the baton proves it is the user if the pk is the signer + // rest of validation is done below break; default: return eval->Invalid("illegal rogue non-decoded funcid"); @@ -1353,7 +1357,7 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C } else // 'H' { - // verify vin/vout + // verify vin/vout and proper payouts } return(true); break; From fed6024ee745bf526d543ba70f9253239b09a6c7 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 23:05:43 -1100 Subject: [PATCH 074/390] err --- src/cc/rogue_rpc.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 1ca1bce88..b5e44aad5 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -332,7 +332,7 @@ int32_t rogue_isvalidgame(struct CCcontract_info *cp,int32_t &gameheight,CTransa if ( myGetTransaction(txid,tx,hashBlock) != 0 && (numvouts= tx.vout.size()) > 1 ) { gameheight = komodo_blockheight(hashBlock); - if ( IsCClibvout(cp,tx,0,cp->unspendableCCaddr) == txfee && (unspentv0 == 0 || CCgettxout(playertxid,0,1) == txfee) ) + if ( IsCClibvout(cp,tx,0,cp->unspendableCCaddr) == txfee && (unspentv0 == 0 || CCgettxout(txid,0,1) == txfee) ) { if ( rogue_newgameopreturndecode(buyin,maxplayers,tx.vout[numvouts-1].scriptPubKey) == 'G' ) { @@ -1265,7 +1265,7 @@ int32_t rogue_playerdata_validate(uint256 &playertxid,struct CCcontract_info *cp bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { - CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,maxplayers,decoded=0,regslot,ind,errs,dispflag,gameheight,score,numvouts; CTransaction vintx,gametx; CPubKey pk; uint256 hashBlock,gametxid,tokenid,batontxid,playertxid,ptxid; int64_t buyin; std::vector playerdata,keystrokes; std::string symbol,pname; + CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,maxplayers,decoded=0,regslot,ind,err,dispflag,gameheight,score,numvouts; CTransaction vintx,gametx; CPubKey pk; uint256 hashBlock,gametxid,tokenid,batontxid,playertxid,ptxid; int64_t buyin; std::vector playerdata,keystrokes; std::string symbol,pname; if ( strcmp(ASSETCHAINS_SYMBOL,"ROGUE") == 0 && height < 21274 ) return(true); if ( (numvouts= tx.vout.size()) > 1 ) From 9377ec6542066c435b6660797d38ccd92393175d Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 23:06:36 -1100 Subject: [PATCH 075/390] Ignore --- src/cc/makerogue | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/cc/makerogue b/src/cc/makerogue index fb7a53cec..d737f39fa 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -1,9 +1,8 @@ #!/bin/sh -echo "you can ignore ./makerogue: shell: not found" cd rogue; ./configure # only need this first time +echo "you can ignore ./makerogue: shell: not found" make; cd .. gcc -Wno-write-strings -DBUILD_ROGUE -std=c++11 -I../../depends/$(shell echo `../..//depends/config.guess`/include) -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -o librogue.so -c cclib.cpp -#gcc -std=c++11 -fPIC -shared -o librogue.so cclib.o rogue/rogue.so cp librogue.so ../libcc.so From 0ca1b888c395737651ddf73b4592d4021e3c7c30 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 23:10:55 -1100 Subject: [PATCH 076/390] Test --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index b5e44aad5..510b67727 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1297,7 +1297,7 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C if ( (err= rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid,0)) != 0 ) { fprintf(stderr,"height.%d rogue_isvalidgame error.%d\n",height,err); - //if ( height > 20000 ) + if ( height > 30000 ) return eval->Invalid("invalid gametxid"); } return(true); From 60e6554848eacda156de40263806f6966ca315a1 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 23:16:24 -1100 Subject: [PATCH 077/390] Test --- src/cc/rogue_rpc.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 510b67727..d4ee66b57 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1294,12 +1294,14 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C switch ( funcid ) { case 'G': + gametxid = tx.GetHash(); if ( (err= rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid,0)) != 0 ) { - fprintf(stderr,"height.%d rogue_isvalidgame error.%d\n",height,err); + fprintf(stderr,"height.%d %s rogue_isvalidgame error.%d\n",height,gametxid.GetHex().c_str(),err); if ( height > 30000 ) return eval->Invalid("invalid gametxid"); } + fprintf(stderr,"height.%d %s rogue_isvalidgame\n",height,gametxid.GetHex().c_str()); return(true); break; case 'R': From 79e09db7e6a8a0b1c35fc5a3d75bd54f2ae9497d Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 23:28:25 -1100 Subject: [PATCH 078/390] +print --- src/cc/rogue_rpc.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index d4ee66b57..f7ac0162a 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -814,7 +814,7 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param result.push_back(Pair("playertxid",playertxid.GetHex())); if ( maxplayers == 1 || nextheight <= batonht+ROGUE_MAXKEYSTROKESGAP ) { - mtx.vin.push_back(CTxIn(batontxid,batonvout,CScript())); // this validates user + mtx.vin.push_back(CTxIn(batontxid,batonvout,CScript())); //this validates user if pk mtx.vout.push_back(MakeCC1of2vout(cp->evalcode,batonvalue-txfee,roguepk,mypk)); Myprivkey(mypriv); CCaddr1of2set(cp,roguepk,mypk,mypriv,destaddr); @@ -1293,7 +1293,7 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C { switch ( funcid ) { - case 'G': + case 'G': // seems just need to make sure no vout abuse is left to do gametxid = tx.GetHash(); if ( (err= rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid,0)) != 0 ) { @@ -1301,7 +1301,7 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C if ( height > 30000 ) return eval->Invalid("invalid gametxid"); } - fprintf(stderr,"height.%d %s rogue_isvalidgame\n",height,gametxid.GetHex().c_str()); + //fprintf(stderr,"height.%d %s rogue_isvalidgame\n",height,gametxid.GetHex().c_str()); return(true); break; case 'R': @@ -1342,6 +1342,7 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C switch ( funcid ) { case 'R': // register + // verify vout amounts are as they should be and no vins that shouldnt be return(true); case 'H': // win case 'Q': // bailout From 961a1eb0a2b1967cfdb74fe548f661fd3b5a7713 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 23:28:46 -1100 Subject: [PATCH 079/390] Enforce new game --- src/cc/rogue_rpc.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index f7ac0162a..ec1b669dc 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1298,8 +1298,7 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C if ( (err= rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid,0)) != 0 ) { fprintf(stderr,"height.%d %s rogue_isvalidgame error.%d\n",height,gametxid.GetHex().c_str(),err); - if ( height > 30000 ) - return eval->Invalid("invalid gametxid"); + return eval->Invalid("invalid gametxid"); } //fprintf(stderr,"height.%d %s rogue_isvalidgame\n",height,gametxid.GetHex().c_str()); return(true); From f3c28c684a58e4601e439be6200f8365aac0d6fa Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 00:07:07 -1100 Subject: [PATCH 080/390] -print --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index ec1b669dc..9cef26d83 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1288,7 +1288,7 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C } if ( e == EVAL_ROGUE ) { - fprintf(stderr,"ht.%d rogue.(%c)\n",height,script[1]); + //fprintf(stderr,"ht.%d rogue.(%c)\n",height,script[1]); if ( decoded == 0 ) { switch ( funcid ) From d0888260aa142faab3044a6ea0876a2ed5849a61 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 01:24:08 -1100 Subject: [PATCH 081/390] +print validgame --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 9cef26d83..d1c63f592 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1300,7 +1300,7 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C fprintf(stderr,"height.%d %s rogue_isvalidgame error.%d\n",height,gametxid.GetHex().c_str(),err); return eval->Invalid("invalid gametxid"); } - //fprintf(stderr,"height.%d %s rogue_isvalidgame\n",height,gametxid.GetHex().c_str()); + fprintf(stderr,"height.%d %s rogue_isvalidgame\n",height,gametxid.GetHex().c_str()); return(true); break; case 'R': From ef05677ec88427b56d6083c6711a0de05af00297 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 01:24:32 -1100 Subject: [PATCH 082/390] -print --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index d1c63f592..9cef26d83 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1300,7 +1300,7 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C fprintf(stderr,"height.%d %s rogue_isvalidgame error.%d\n",height,gametxid.GetHex().c_str(),err); return eval->Invalid("invalid gametxid"); } - fprintf(stderr,"height.%d %s rogue_isvalidgame\n",height,gametxid.GetHex().c_str()); + //fprintf(stderr,"height.%d %s rogue_isvalidgame\n",height,gametxid.GetHex().c_str()); return(true); break; case 'R': From ee5d656a2c1c7df3160281939ebebeab3fbeba8a Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 01:31:02 -1100 Subject: [PATCH 083/390] Rework game validation --- src/cc/rogue_rpc.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 9cef26d83..78541b63c 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -329,9 +329,10 @@ int32_t rogue_isvalidgame(struct CCcontract_info *cp,int32_t &gameheight,CTransa { uint256 hashBlock; int32_t i,numvouts; char coinaddr[64]; CPubKey roguepk; uint64_t txfee = 10000; buyin = maxplayers = 0; - if ( myGetTransaction(txid,tx,hashBlock) != 0 && (numvouts= tx.vout.size()) > 1 ) + if ( (txid == zeroid || myGetTransaction(txid,tx,hashBlock) != 0) && (numvouts= tx.vout.size()) > 1 ) { - gameheight = komodo_blockheight(hashBlock); + if ( txid != zeroid ) + gameheight = komodo_blockheight(hashBlock); if ( IsCClibvout(cp,tx,0,cp->unspendableCCaddr) == txfee && (unspentv0 == 0 || CCgettxout(txid,0,1) == txfee) ) { if ( rogue_newgameopreturndecode(buyin,maxplayers,tx.vout[numvouts-1].scriptPubKey) == 'G' ) @@ -1295,7 +1296,8 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C { case 'G': // seems just need to make sure no vout abuse is left to do gametxid = tx.GetHash(); - if ( (err= rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid,0)) != 0 ) + gameheight = height; + if ( (err= rogue_isvalidgame(cp,gameheight,tx,buyin,maxplayers,zerotxid,0)) != 0 ) { fprintf(stderr,"height.%d %s rogue_isvalidgame error.%d\n",height,gametxid.GetHex().c_str(),err); return eval->Invalid("invalid gametxid"); From 67eb2929d63534398efdea4007c7d6192b598634 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 01:31:56 -1100 Subject: [PATCH 084/390] Zeroed --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 78541b63c..9d493e5ae 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1297,7 +1297,7 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C case 'G': // seems just need to make sure no vout abuse is left to do gametxid = tx.GetHash(); gameheight = height; - if ( (err= rogue_isvalidgame(cp,gameheight,tx,buyin,maxplayers,zerotxid,0)) != 0 ) + if ( (err= rogue_isvalidgame(cp,gameheight,tx,buyin,maxplayers,zeroid,0)) != 0 ) { fprintf(stderr,"height.%d %s rogue_isvalidgame error.%d\n",height,gametxid.GetHex().c_str(),err); return eval->Invalid("invalid gametxid"); From 92c9825cdea8ad8be5a00b7f74412556840d69a3 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 01:41:28 -1100 Subject: [PATCH 085/390] Test --- src/cc/rogue_rpc.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 9d493e5ae..50492e2cf 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -333,6 +333,11 @@ int32_t rogue_isvalidgame(struct CCcontract_info *cp,int32_t &gameheight,CTransa { if ( txid != zeroid ) gameheight = komodo_blockheight(hashBlock); + else + { + txid = tx.GetHash(); + fprintf(stderr,"set txid %s %llu\n",txid.GetHex().c_str(),(long long)CCgettxout(txid,0,1)); + } if ( IsCClibvout(cp,tx,0,cp->unspendableCCaddr) == txfee && (unspentv0 == 0 || CCgettxout(txid,0,1) == txfee) ) { if ( rogue_newgameopreturndecode(buyin,maxplayers,tx.vout[numvouts-1].scriptPubKey) == 'G' ) From fbe6061dc6e76a292ae49e284a1354dc2de4f8b0 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 01:42:45 -1100 Subject: [PATCH 086/390] Test --- src/cc/rogue_rpc.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 50492e2cf..2496d6a5e 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1300,9 +1300,10 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C switch ( funcid ) { case 'G': // seems just need to make sure no vout abuse is left to do + gametx = tx; gametxid = tx.GetHash(); gameheight = height; - if ( (err= rogue_isvalidgame(cp,gameheight,tx,buyin,maxplayers,zeroid,0)) != 0 ) + if ( (err= rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,zeroid,0)) != 0 ) { fprintf(stderr,"height.%d %s rogue_isvalidgame error.%d\n",height,gametxid.GetHex().c_str(),err); return eval->Invalid("invalid gametxid"); From 180114697aaf5f7ff6ee96ec51722e1150aeea42 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 01:44:36 -1100 Subject: [PATCH 087/390] -print --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 2496d6a5e..3d89e0568 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -336,7 +336,7 @@ int32_t rogue_isvalidgame(struct CCcontract_info *cp,int32_t &gameheight,CTransa else { txid = tx.GetHash(); - fprintf(stderr,"set txid %s %llu\n",txid.GetHex().c_str(),(long long)CCgettxout(txid,0,1)); + //fprintf(stderr,"set txid %s %llu\n",txid.GetHex().c_str(),(long long)CCgettxout(txid,0,1)); } if ( IsCClibvout(cp,tx,0,cp->unspendableCCaddr) == txfee && (unspentv0 == 0 || CCgettxout(txid,0,1) == txfee) ) { From 2ca8d1eedaef49bccd8622bc8f61a6d6fa4c6dc9 Mon Sep 17 00:00:00 2001 From: ca333 Date: Tue, 19 Feb 2019 14:15:09 +0100 Subject: [PATCH 088/390] resolve conflict PR for multi OS build will follow this PR --- src/cc/makerogue | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/cc/makerogue b/src/cc/makerogue index d737f39fa..a38eab6a4 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -1,8 +1,11 @@ #!/bin/sh cd rogue; -./configure # only need this first time -echo "you can ignore ./makerogue: shell: not found" +./configure make; cd .. -gcc -Wno-write-strings -DBUILD_ROGUE -std=c++11 -I../../depends/$(shell echo `../..//depends/config.guess`/include) -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -o librogue.so -c cclib.cpp -cp librogue.so ../libcc.so +if make -f Makefile_rogue "$@"; then + echo ROGUE BUILD SUCCESSFUL +else + echo ROGUE BUILD FAILED + exit 1 +fi From 4bf1256a68a0248dfdc9b54b8e31dbe759cf073b Mon Sep 17 00:00:00 2001 From: ca333 Date: Tue, 19 Feb 2019 16:57:47 +0100 Subject: [PATCH 089/390] add ifndef WIN --- src/cc/rogue/cursesd.h | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/cc/rogue/cursesd.h b/src/cc/rogue/cursesd.h index 87304cfa6..cb74941e5 100644 --- a/src/cc/rogue/cursesd.h +++ b/src/cc/rogue/cursesd.h @@ -48,7 +48,10 @@ extern WINDOW *stdscr,*curscr; extern int32_t ESCDELAY; typedef char chtype; +#ifndef __MINGW32__ int32_t getch(void); // stub +#endif + int32_t md_readchar(void); // stub WINDOW *initscr(void); From c127a8f0b5bfd89e76364e6432c8a70b5eb3a203 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 06:34:34 -1100 Subject: [PATCH 090/390] ENABLE_MODULE_MUSIG --- src/secp256k1/Makefile.am | 5 + src/secp256k1/src/ecmult.h | 55 + src/secp256k1/src/ecmult_impl.h | 1176 +++++++++++++++++ .../src/modules/musig/Makefile.am.include | 17 + src/secp256k1/src/modules/musig/example.c | 166 +++ src/secp256k1/src/modules/musig/main_impl.h | 631 +++++++++ src/secp256k1/src/modules/musig/tests_impl.h | 758 +++++++++++ .../modules/schnorrsig/Makefile.am.include | 9 + .../src/modules/schnorrsig/main_impl.h | 339 +++++ .../src/modules/schnorrsig/tests_impl.h | 727 ++++++++++ src/secp256k1/src/scalar.h | 235 ++++ src/secp256k1/src/scalar_4x64.h | 49 + src/secp256k1/src/scalar_4x64_impl.h | 1056 +++++++++++++++ src/secp256k1/src/scalar_8x32.h | 24 + src/secp256k1/src/scalar_8x32_impl.h | 838 ++++++++++++ src/secp256k1/src/scalar_impl.h | 340 +++++ src/secp256k1/src/scalar_low.h | 20 + src/secp256k1/src/scalar_low_impl.h | 126 ++ 18 files changed, 6571 insertions(+) create mode 100644 src/secp256k1/src/modules/musig/Makefile.am.include create mode 100644 src/secp256k1/src/modules/musig/example.c create mode 100644 src/secp256k1/src/modules/musig/main_impl.h create mode 100644 src/secp256k1/src/modules/musig/tests_impl.h create mode 100644 src/secp256k1/src/modules/schnorrsig/Makefile.am.include create mode 100644 src/secp256k1/src/modules/schnorrsig/main_impl.h create mode 100644 src/secp256k1/src/modules/schnorrsig/tests_impl.h diff --git a/src/secp256k1/Makefile.am b/src/secp256k1/Makefile.am index c071fbe27..ff5a2c50c 100644 --- a/src/secp256k1/Makefile.am +++ b/src/secp256k1/Makefile.am @@ -172,6 +172,11 @@ if ENABLE_MODULE_ECDH include src/modules/ecdh/Makefile.am.include endif +if ENABLE_MODULE_MUSIG +include src/modules/schnorrsig/Makefile.am.include +include src/modules/musig/Makefile.am.include +endif + if ENABLE_MODULE_RECOVERY include src/modules/recovery/Makefile.am.include endif diff --git a/src/secp256k1/src/ecmult.h b/src/secp256k1/src/ecmult.h index 6d44aba60..7fe619b21 100644 --- a/src/secp256k1/src/ecmult.h +++ b/src/secp256k1/src/ecmult.h @@ -1,3 +1,5 @@ +#ifdef ENABLE_MODULE_MUSIG + /********************************************************************** * Copyright (c) 2013, 2014 Pieter Wuille * * Distributed under the MIT software license, see the accompanying * @@ -29,3 +31,56 @@ static int secp256k1_ecmult_context_is_built(const secp256k1_ecmult_context *ctx static void secp256k1_ecmult(const secp256k1_ecmult_context *ctx, secp256k1_gej *r, const secp256k1_gej *a, const secp256k1_scalar *na, const secp256k1_scalar *ng); #endif /* SECP256K1_ECMULT_H */ + +#else +/********************************************************************** + * Copyright (c) 2013, 2014, 2017 Pieter Wuille, Andrew Poelstra * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_ECMULT_H +#define SECP256K1_ECMULT_H + +#include "num.h" +#include "group.h" +#include "scalar.h" +#include "scratch.h" + +typedef struct { + /* For accelerating the computation of a*P + b*G: */ + secp256k1_ge_storage (*pre_g)[]; /* odd multiples of the generator */ +#ifdef USE_ENDOMORPHISM + secp256k1_ge_storage (*pre_g_128)[]; /* odd multiples of 2^128*generator */ +#endif +} secp256k1_ecmult_context; + +static void secp256k1_ecmult_context_init(secp256k1_ecmult_context *ctx); +static void secp256k1_ecmult_context_build(secp256k1_ecmult_context *ctx, const secp256k1_callback *cb); +static void secp256k1_ecmult_context_clone(secp256k1_ecmult_context *dst, + const secp256k1_ecmult_context *src, const secp256k1_callback *cb); +static void secp256k1_ecmult_context_clear(secp256k1_ecmult_context *ctx); +static int secp256k1_ecmult_context_is_built(const secp256k1_ecmult_context *ctx); + +/** Double multiply: R = na*A + ng*G */ +static void secp256k1_ecmult(const secp256k1_ecmult_context *ctx, secp256k1_gej *r, const secp256k1_gej *a, const secp256k1_scalar *na, const secp256k1_scalar *ng); + +typedef int (secp256k1_ecmult_multi_callback)(secp256k1_scalar *sc, secp256k1_ge *pt, size_t idx, void *data); + +/** + * Multi-multiply: R = inp_g_sc * G + sum_i ni * Ai. + * Chooses the right algorithm for a given number of points and scratch space + * size. Resets and overwrites the given scratch space. If the points do not + * fit in the scratch space the algorithm is repeatedly run with batches of + * points. If no scratch space is given then a simple algorithm is used that + * simply multiplies the points with the corresponding scalars and adds them up. + * Returns: 1 on success (including when inp_g_sc is NULL and n is 0) + * 0 if there is not enough scratch space for a single point or + * callback returns 0 + */ +static int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n); + +#endif /* SECP256K1_ECMULT_H */ + +#endif + diff --git a/src/secp256k1/src/ecmult_impl.h b/src/secp256k1/src/ecmult_impl.h index 93d3794cb..6c9a1daf2 100644 --- a/src/secp256k1/src/ecmult_impl.h +++ b/src/secp256k1/src/ecmult_impl.h @@ -1,3 +1,6 @@ +#ifndef ENABLE_MODULE_MUSIG + + /********************************************************************** * Copyright (c) 2013, 2014 Pieter Wuille * * Distributed under the MIT software license, see the accompanying * @@ -404,3 +407,1176 @@ static void secp256k1_ecmult(const secp256k1_ecmult_context *ctx, secp256k1_gej } #endif /* SECP256K1_ECMULT_IMPL_H */ + +#else + +/***************************************************************************** + * Copyright (c) 2013, 2014, 2017 Pieter Wuille, Andrew Poelstra, Jonas Nick * + * 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 +#include + +#include "group.h" +#include "scalar.h" +#include "ecmult.h" + +#if defined(EXHAUSTIVE_TEST_ORDER) +/* We need to lower these values for exhaustive tests because + * the tables cannot have infinities in them (this breaks the + * affine-isomorphism stuff which tracks z-ratios) */ +# if EXHAUSTIVE_TEST_ORDER > 128 +# define WINDOW_A 5 +# define WINDOW_G 8 +# elif EXHAUSTIVE_TEST_ORDER > 8 +# define WINDOW_A 4 +# define WINDOW_G 4 +# else +# define WINDOW_A 2 +# define WINDOW_G 2 +# endif +#else +/* 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 +#endif + +#ifdef USE_ENDOMORPHISM +#define WNAF_BITS 128 +#else +#define WNAF_BITS 256 +#endif +#define WNAF_SIZE_BITS(bits, w) (((bits) + (w) - 1) / (w)) +#define WNAF_SIZE(w) WNAF_SIZE_BITS(WNAF_BITS, w) + +/** The number of entries a table with precomputed multiples needs to have. */ +#define ECMULT_TABLE_SIZE(w) (1 << ((w)-2)) + +/* The number of objects allocated on the scratch space for ecmult_multi algorithms */ +#define PIPPENGER_SCRATCH_OBJECTS 6 +#define STRAUSS_SCRATCH_OBJECTS 6 + +#define PIPPENGER_MAX_BUCKET_WINDOW 12 + +/* Minimum number of points for which pippenger_wnaf is faster than strauss wnaf */ +#ifdef USE_ENDOMORPHISM +#define ECMULT_PIPPENGER_THRESHOLD 88 +#else +#define ECMULT_PIPPENGER_THRESHOLD 160 +#endif + +#ifdef USE_ENDOMORPHISM +#define ECMULT_MAX_POINTS_PER_BATCH 5000000 +#else +#define ECMULT_MAX_POINTS_PER_BATCH 10000000 +#endif + +/** Fill a table 'prej' with precomputed odd multiples of a. Prej will contain + * the values [1*a,3*a,...,(2*n-1)*a], so it space for n values. zr[0] will + * contain prej[0].z / a.z. The other zr[i] values = prej[i].z / prej[i-1].z. + * Prej's Z values are undefined, except for the last value. + */ +static void secp256k1_ecmult_odd_multiples_table(int n, secp256k1_gej *prej, secp256k1_fe *zr, const secp256k1_gej *a) { + secp256k1_gej d; + secp256k1_ge a_ge, d_ge; + int i; + + VERIFY_CHECK(!a->infinity); + + secp256k1_gej_double_var(&d, a, NULL); + + /* + * Perform the additions on an isomorphism where 'd' is affine: drop the z coordinate + * of 'd', and scale the 1P starting value's x/y coordinates without changing its z. + */ + d_ge.x = d.x; + d_ge.y = d.y; + d_ge.infinity = 0; + + secp256k1_ge_set_gej_zinv(&a_ge, a, &d.z); + prej[0].x = a_ge.x; + prej[0].y = a_ge.y; + prej[0].z = a->z; + prej[0].infinity = 0; + + zr[0] = d.z; + for (i = 1; i < n; i++) { + secp256k1_gej_add_ge_var(&prej[i], &prej[i-1], &d_ge, &zr[i]); + } + + /* + * Each point in 'prej' has a z coordinate too small by a factor of 'd.z'. Only + * the final point's z coordinate is actually used though, so just update that. + */ + secp256k1_fe_mul(&prej[n-1].z, &prej[n-1].z, &d.z); +} + +/** Fill a table 'pre' with precomputed odd multiples of a. + * + * There are two versions of this function: + * - secp256k1_ecmult_odd_multiples_table_globalz_windowa which brings its + * resulting point set to a single constant Z denominator, stores the X and Y + * coordinates as ge_storage points in pre, and stores the global Z in rz. + * It only operates on tables sized for WINDOW_A wnaf multiples. + * - secp256k1_ecmult_odd_multiples_table_storage_var, which converts its + * resulting point set to actually affine points, and stores those in pre. + * It operates on tables of any size, but uses heap-allocated temporaries. + * + * To compute a*P + b*G, we compute a table for P using the first function, + * and for G using the second (which requires an inverse, but it only needs to + * happen once). + */ +static void secp256k1_ecmult_odd_multiples_table_globalz_windowa(secp256k1_ge *pre, secp256k1_fe *globalz, const secp256k1_gej *a) { + secp256k1_gej prej[ECMULT_TABLE_SIZE(WINDOW_A)]; + secp256k1_fe zr[ECMULT_TABLE_SIZE(WINDOW_A)]; + + /* Compute the odd multiples in Jacobian form. */ + secp256k1_ecmult_odd_multiples_table(ECMULT_TABLE_SIZE(WINDOW_A), prej, zr, a); + /* Bring them to the same Z denominator. */ + secp256k1_ge_globalz_set_table_gej(ECMULT_TABLE_SIZE(WINDOW_A), pre, globalz, prej, zr); +} + +static void secp256k1_ecmult_odd_multiples_table_storage_var(const int n, secp256k1_ge_storage *pre, const secp256k1_gej *a) { + secp256k1_gej d; + secp256k1_ge d_ge, p_ge; + secp256k1_gej pj; + secp256k1_fe zi; + secp256k1_fe zr; + secp256k1_fe dx_over_dz_squared; + int i; + + VERIFY_CHECK(!a->infinity); + + secp256k1_gej_double_var(&d, a, NULL); + + /* First, we perform all the additions in an isomorphic curve obtained by multiplying + * all `z` coordinates by 1/`d.z`. In these coordinates `d` is affine so we can use + * `secp256k1_gej_add_ge_var` to perform the additions. For each addition, we store + * the resulting y-coordinate and the z-ratio, since we only have enough memory to + * store two field elements. These are sufficient to efficiently undo the isomorphism + * and recompute all the `x`s. + */ + d_ge.x = d.x; + d_ge.y = d.y; + d_ge.infinity = 0; + + secp256k1_ge_set_gej_zinv(&p_ge, a, &d.z); + pj.x = p_ge.x; + pj.y = p_ge.y; + pj.z = a->z; + pj.infinity = 0; + + for (i = 0; i < (n - 1); i++) { + secp256k1_fe_normalize_var(&pj.y); + secp256k1_fe_to_storage(&pre[i].y, &pj.y); + secp256k1_gej_add_ge_var(&pj, &pj, &d_ge, &zr); + secp256k1_fe_normalize_var(&zr); + secp256k1_fe_to_storage(&pre[i].x, &zr); + } + + /* Invert d.z in the same batch, preserving pj.z so we can extract 1/d.z */ + secp256k1_fe_mul(&zi, &pj.z, &d.z); + secp256k1_fe_inv_var(&zi, &zi); + + /* Directly set `pre[n - 1]` to `pj`, saving the inverted z-coordinate so + * that we can combine it with the saved z-ratios to compute the other zs + * without any more inversions. */ + secp256k1_ge_set_gej_zinv(&p_ge, &pj, &zi); + secp256k1_ge_to_storage(&pre[n - 1], &p_ge); + + /* Compute the actual x-coordinate of D, which will be needed below. */ + secp256k1_fe_mul(&d.z, &zi, &pj.z); /* d.z = 1/d.z */ + secp256k1_fe_sqr(&dx_over_dz_squared, &d.z); + secp256k1_fe_mul(&dx_over_dz_squared, &dx_over_dz_squared, &d.x); + + /* Going into the second loop, we have set `pre[n-1]` to its final affine + * form, but still need to set `pre[i]` for `i` in 0 through `n-2`. We + * have `zi = (p.z * d.z)^-1`, where + * + * `p.z` is the z-coordinate of the point on the isomorphic curve + * which was ultimately assigned to `pre[n-1]`. + * `d.z` is the multiplier that must be applied to all z-coordinates + * to move from our isomorphic curve back to secp256k1; so the + * product `p.z * d.z` is the z-coordinate of the secp256k1 + * point assigned to `pre[n-1]`. + * + * All subsequent inverse-z-coordinates can be obtained by multiplying this + * factor by successive z-ratios, which is much more efficient than directly + * computing each one. + * + * Importantly, these inverse-zs will be coordinates of points on secp256k1, + * while our other stored values come from computations on the isomorphic + * curve. So in the below loop, we will take care not to actually use `zi` + * or any derived values until we're back on secp256k1. + */ + i = n - 1; + while (i > 0) { + secp256k1_fe zi2, zi3; + const secp256k1_fe *rzr; + i--; + + secp256k1_ge_from_storage(&p_ge, &pre[i]); + + /* For each remaining point, we extract the z-ratio from the stored + * x-coordinate, compute its z^-1 from that, and compute the full + * point from that. */ + rzr = &p_ge.x; + secp256k1_fe_mul(&zi, &zi, rzr); + secp256k1_fe_sqr(&zi2, &zi); + secp256k1_fe_mul(&zi3, &zi2, &zi); + /* To compute the actual x-coordinate, we use the stored z ratio and + * y-coordinate, which we obtained from `secp256k1_gej_add_ge_var` + * in the loop above, as well as the inverse of the square of its + * z-coordinate. We store the latter in the `zi2` variable, which is + * computed iteratively starting from the overall Z inverse then + * multiplying by each z-ratio in turn. + * + * Denoting the z-ratio as `rzr`, we observe that it is equal to `h` + * from the inside of the above `gej_add_ge_var` call. This satisfies + * + * rzr = d_x * z^2 - x * d_z^2 + * + * where (`d_x`, `d_z`) are Jacobian coordinates of `D` and `(x, z)` + * are Jacobian coordinates of our desired point -- except both are on + * the isomorphic curve that we were using when we called `gej_add_ge_var`. + * To get back to secp256k1, we must multiply both `z`s by `d_z`, or + * equivalently divide both `x`s by `d_z^2`. Our equation then becomes + * + * rzr = d_x * z^2 / d_z^2 - x + * + * (The left-hand-side, being a ratio of z-coordinates, is unaffected + * by the isomorphism.) + * + * Rearranging to solve for `x`, we have + * + * x = d_x * z^2 / d_z^2 - rzr + * + * But what we actually want is the affine coordinate `X = x/z^2`, + * which will satisfy + * + * X = d_x / d_z^2 - rzr / z^2 + * = dx_over_dz_squared - rzr * zi2 + */ + secp256k1_fe_mul(&p_ge.x, rzr, &zi2); + secp256k1_fe_negate(&p_ge.x, &p_ge.x, 1); + secp256k1_fe_add(&p_ge.x, &dx_over_dz_squared); + /* y is stored_y/z^3, as we expect */ + secp256k1_fe_mul(&p_ge.y, &p_ge.y, &zi3); + /* Store */ + secp256k1_ge_to_storage(&pre[i], &p_ge); + } +} + +/** The following two macro retrieves a particular odd multiple from a table + * of precomputed multiples. */ +#define ECMULT_TABLE_GET_GE(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_ge_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) + +static void secp256k1_ecmult_context_init(secp256k1_ecmult_context *ctx) { + ctx->pre_g = NULL; +#ifdef USE_ENDOMORPHISM + ctx->pre_g_128 = NULL; +#endif +} + +static void secp256k1_ecmult_context_build(secp256k1_ecmult_context *ctx, const secp256k1_callback *cb) { + secp256k1_gej gj; + + if (ctx->pre_g != NULL) { + return; + } + + /* get the generator */ + secp256k1_gej_set_ge(&gj, &secp256k1_ge_const_g); + + ctx->pre_g = (secp256k1_ge_storage (*)[])checked_malloc(cb, sizeof((*ctx->pre_g)[0]) * ECMULT_TABLE_SIZE(WINDOW_G)); + + /* precompute the tables with odd multiples */ + secp256k1_ecmult_odd_multiples_table_storage_var(ECMULT_TABLE_SIZE(WINDOW_G), *ctx->pre_g, &gj); + +#ifdef USE_ENDOMORPHISM + { + secp256k1_gej g_128j; + int i; + + ctx->pre_g_128 = (secp256k1_ge_storage (*)[])checked_malloc(cb, sizeof((*ctx->pre_g_128)[0]) * ECMULT_TABLE_SIZE(WINDOW_G)); + + /* calculate 2^128*generator */ + g_128j = gj; + for (i = 0; i < 128; i++) { + secp256k1_gej_double_var(&g_128j, &g_128j, NULL); + } + secp256k1_ecmult_odd_multiples_table_storage_var(ECMULT_TABLE_SIZE(WINDOW_G), *ctx->pre_g_128, &g_128j); + } +#endif +} + +static void secp256k1_ecmult_context_clone(secp256k1_ecmult_context *dst, + const secp256k1_ecmult_context *src, const secp256k1_callback *cb) { + if (src->pre_g == NULL) { + dst->pre_g = NULL; + } else { + size_t size = sizeof((*dst->pre_g)[0]) * ECMULT_TABLE_SIZE(WINDOW_G); + dst->pre_g = (secp256k1_ge_storage (*)[])checked_malloc(cb, size); + memcpy(dst->pre_g, src->pre_g, size); + } +#ifdef USE_ENDOMORPHISM + if (src->pre_g_128 == NULL) { + dst->pre_g_128 = NULL; + } else { + size_t size = sizeof((*dst->pre_g_128)[0]) * ECMULT_TABLE_SIZE(WINDOW_G); + dst->pre_g_128 = (secp256k1_ge_storage (*)[])checked_malloc(cb, size); + memcpy(dst->pre_g_128, src->pre_g_128, size); + } +#endif +} + +static int secp256k1_ecmult_context_is_built(const secp256k1_ecmult_context *ctx) { + return ctx->pre_g != NULL; +} + +static void secp256k1_ecmult_context_clear(secp256k1_ecmult_context *ctx) { + free(ctx->pre_g); +#ifdef USE_ENDOMORPHISM + free(ctx->pre_g_128); +#endif + secp256k1_ecmult_context_init(ctx); +} + +/** 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, int len, const secp256k1_scalar *a, int w) { + secp256k1_scalar s = *a; + int last_set_bit = -1; + int bit = 0; + int sign = 1; + int carry = 0; + + VERIFY_CHECK(wnaf != NULL); + VERIFY_CHECK(0 <= len && len <= 256); + VERIFY_CHECK(a != NULL); + VERIFY_CHECK(2 <= w && w <= 31); + + memset(wnaf, 0, len * sizeof(wnaf[0])); + + if (secp256k1_scalar_get_bits(&s, 255, 1)) { + secp256k1_scalar_negate(&s, &s); + sign = -1; + } + + while (bit < len) { + int now; + int word; + if (secp256k1_scalar_get_bits(&s, bit, 1) == (unsigned int)carry) { + bit++; + continue; + } + + now = w; + if (now > len - bit) { + now = len - bit; + } + + word = secp256k1_scalar_get_bits_var(&s, bit, now) + carry; + + carry = (word >> (w-1)) & 1; + word -= carry << w; + + wnaf[bit] = sign * word; + last_set_bit = bit; + + bit += now; + } +#ifdef VERIFY + CHECK(carry == 0); + while (bit < 256) { + CHECK(secp256k1_scalar_get_bits(&s, bit++, 1) == 0); + } +#endif + return last_set_bit + 1; +} + +struct secp256k1_strauss_point_state { +#ifdef USE_ENDOMORPHISM + secp256k1_scalar na_1, na_lam; + int wnaf_na_1[130]; + int wnaf_na_lam[130]; + int bits_na_1; + int bits_na_lam; +#else + int wnaf_na[256]; + int bits_na; +#endif + size_t input_pos; +}; + +struct secp256k1_strauss_state { + secp256k1_gej* prej; + secp256k1_fe* zr; + secp256k1_ge* pre_a; +#ifdef USE_ENDOMORPHISM + secp256k1_ge* pre_a_lam; +#endif + struct secp256k1_strauss_point_state* ps; +}; + +static void secp256k1_ecmult_strauss_wnaf(const secp256k1_ecmult_context *ctx, const struct secp256k1_strauss_state *state, secp256k1_gej *r, int num, const secp256k1_gej *a, const secp256k1_scalar *na, const secp256k1_scalar *ng) { + secp256k1_ge tmpa; + secp256k1_fe Z; +#ifdef USE_ENDOMORPHISM + /* Splitted G factors. */ + secp256k1_scalar ng_1, ng_128; + int wnaf_ng_1[129]; + int bits_ng_1 = 0; + int wnaf_ng_128[129]; + int bits_ng_128 = 0; +#else + int wnaf_ng[256]; + int bits_ng = 0; +#endif + int i; + int bits = 0; + int np; + int no = 0; + + for (np = 0; np < num; ++np) { + if (secp256k1_scalar_is_zero(&na[np]) || secp256k1_gej_is_infinity(&a[np])) { + continue; + } + state->ps[no].input_pos = np; +#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(&state->ps[no].na_1, &state->ps[no].na_lam, &na[np]); + + /* build wnaf representation for na_1 and na_lam. */ + state->ps[no].bits_na_1 = secp256k1_ecmult_wnaf(state->ps[no].wnaf_na_1, 130, &state->ps[no].na_1, WINDOW_A); + state->ps[no].bits_na_lam = secp256k1_ecmult_wnaf(state->ps[no].wnaf_na_lam, 130, &state->ps[no].na_lam, WINDOW_A); + VERIFY_CHECK(state->ps[no].bits_na_1 <= 130); + VERIFY_CHECK(state->ps[no].bits_na_lam <= 130); + if (state->ps[no].bits_na_1 > bits) { + bits = state->ps[no].bits_na_1; + } + if (state->ps[no].bits_na_lam > bits) { + bits = state->ps[no].bits_na_lam; + } +#else + /* build wnaf representation for na. */ + state->ps[no].bits_na = secp256k1_ecmult_wnaf(state->ps[no].wnaf_na, 256, &na[np], WINDOW_A); + if (state->ps[no].bits_na > bits) { + bits = state->ps[no].bits_na; + } +#endif + ++no; + } + + /* Calculate odd multiples of a. + * All multiples are brought to the same Z 'denominator', which is stored + * in Z. Due to secp256k1' isomorphism we can do all operations pretending + * that the Z coordinate was 1, use affine addition formulae, and correct + * the Z coordinate of the result once at the end. + * The exception is the precomputed G table points, which are actually + * affine. Compared to the base used for other points, they have a Z ratio + * of 1/Z, so we can use secp256k1_gej_add_zinv_var, which uses the same + * isomorphism to efficiently add with a known Z inverse. + */ + if (no > 0) { + /* Compute the odd multiples in Jacobian form. */ + secp256k1_ecmult_odd_multiples_table(ECMULT_TABLE_SIZE(WINDOW_A), state->prej, state->zr, &a[state->ps[0].input_pos]); + for (np = 1; np < no; ++np) { + secp256k1_gej tmp = a[state->ps[np].input_pos]; +#ifdef VERIFY + secp256k1_fe_normalize_var(&(state->prej[(np - 1) * ECMULT_TABLE_SIZE(WINDOW_A) + ECMULT_TABLE_SIZE(WINDOW_A) - 1].z)); +#endif + secp256k1_gej_rescale(&tmp, &(state->prej[(np - 1) * ECMULT_TABLE_SIZE(WINDOW_A) + ECMULT_TABLE_SIZE(WINDOW_A) - 1].z)); + secp256k1_ecmult_odd_multiples_table(ECMULT_TABLE_SIZE(WINDOW_A), state->prej + np * ECMULT_TABLE_SIZE(WINDOW_A), state->zr + np * ECMULT_TABLE_SIZE(WINDOW_A), &tmp); + secp256k1_fe_mul(state->zr + np * ECMULT_TABLE_SIZE(WINDOW_A), state->zr + np * ECMULT_TABLE_SIZE(WINDOW_A), &(a[state->ps[np].input_pos].z)); + } + /* Bring them to the same Z denominator. */ + secp256k1_ge_globalz_set_table_gej(ECMULT_TABLE_SIZE(WINDOW_A) * no, state->pre_a, &Z, state->prej, state->zr); + } else { + secp256k1_fe_set_int(&Z, 1); + } + +#ifdef USE_ENDOMORPHISM + for (np = 0; np < no; ++np) { + for (i = 0; i < ECMULT_TABLE_SIZE(WINDOW_A); i++) { + secp256k1_ge_mul_lambda(&state->pre_a_lam[np * ECMULT_TABLE_SIZE(WINDOW_A) + i], &state->pre_a[np * ECMULT_TABLE_SIZE(WINDOW_A) + i]); + } + } + + if (ng) { + /* 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, 129, &ng_1, WINDOW_G); + bits_ng_128 = secp256k1_ecmult_wnaf(wnaf_ng_128, 129, &ng_128, WINDOW_G); + if (bits_ng_1 > bits) { + bits = bits_ng_1; + } + if (bits_ng_128 > bits) { + bits = bits_ng_128; + } + } +#else + if (ng) { + bits_ng = secp256k1_ecmult_wnaf(wnaf_ng, 256, 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, NULL); +#ifdef USE_ENDOMORPHISM + for (np = 0; np < no; ++np) { + if (i < state->ps[np].bits_na_1 && (n = state->ps[np].wnaf_na_1[i])) { + ECMULT_TABLE_GET_GE(&tmpa, state->pre_a + np * ECMULT_TABLE_SIZE(WINDOW_A), n, WINDOW_A); + secp256k1_gej_add_ge_var(r, r, &tmpa, NULL); + } + if (i < state->ps[np].bits_na_lam && (n = state->ps[np].wnaf_na_lam[i])) { + ECMULT_TABLE_GET_GE(&tmpa, state->pre_a_lam + np * ECMULT_TABLE_SIZE(WINDOW_A), n, WINDOW_A); + secp256k1_gej_add_ge_var(r, r, &tmpa, NULL); + } + } + if (i < bits_ng_1 && (n = wnaf_ng_1[i])) { + ECMULT_TABLE_GET_GE_STORAGE(&tmpa, *ctx->pre_g, n, WINDOW_G); + secp256k1_gej_add_zinv_var(r, r, &tmpa, &Z); + } + if (i < bits_ng_128 && (n = wnaf_ng_128[i])) { + ECMULT_TABLE_GET_GE_STORAGE(&tmpa, *ctx->pre_g_128, n, WINDOW_G); + secp256k1_gej_add_zinv_var(r, r, &tmpa, &Z); + } +#else + for (np = 0; np < no; ++np) { + if (i < state->ps[np].bits_na && (n = state->ps[np].wnaf_na[i])) { + ECMULT_TABLE_GET_GE(&tmpa, state->pre_a + np * ECMULT_TABLE_SIZE(WINDOW_A), n, WINDOW_A); + secp256k1_gej_add_ge_var(r, r, &tmpa, NULL); + } + } + if (i < bits_ng && (n = wnaf_ng[i])) { + ECMULT_TABLE_GET_GE_STORAGE(&tmpa, *ctx->pre_g, n, WINDOW_G); + secp256k1_gej_add_zinv_var(r, r, &tmpa, &Z); + } +#endif + } + + if (!r->infinity) { + secp256k1_fe_mul(&r->z, &r->z, &Z); + } +} + +static void secp256k1_ecmult(const secp256k1_ecmult_context *ctx, secp256k1_gej *r, const secp256k1_gej *a, const secp256k1_scalar *na, const secp256k1_scalar *ng) { + secp256k1_gej prej[ECMULT_TABLE_SIZE(WINDOW_A)]; + secp256k1_fe zr[ECMULT_TABLE_SIZE(WINDOW_A)]; + secp256k1_ge pre_a[ECMULT_TABLE_SIZE(WINDOW_A)]; + struct secp256k1_strauss_point_state ps[1]; +#ifdef USE_ENDOMORPHISM + secp256k1_ge pre_a_lam[ECMULT_TABLE_SIZE(WINDOW_A)]; +#endif + struct secp256k1_strauss_state state; + + state.prej = prej; + state.zr = zr; + state.pre_a = pre_a; +#ifdef USE_ENDOMORPHISM + state.pre_a_lam = pre_a_lam; +#endif + state.ps = ps; + secp256k1_ecmult_strauss_wnaf(ctx, &state, r, 1, a, na, ng); +} + +static size_t secp256k1_strauss_scratch_size(size_t n_points) { +#ifdef USE_ENDOMORPHISM + static const size_t point_size = (2 * sizeof(secp256k1_ge) + sizeof(secp256k1_gej) + sizeof(secp256k1_fe)) * ECMULT_TABLE_SIZE(WINDOW_A) + sizeof(struct secp256k1_strauss_point_state) + sizeof(secp256k1_gej) + sizeof(secp256k1_scalar); +#else + static const size_t point_size = (sizeof(secp256k1_ge) + sizeof(secp256k1_gej) + sizeof(secp256k1_fe)) * ECMULT_TABLE_SIZE(WINDOW_A) + sizeof(struct secp256k1_strauss_point_state) + sizeof(secp256k1_gej) + sizeof(secp256k1_scalar); +#endif + return n_points*point_size; +} + +static int secp256k1_ecmult_strauss_batch(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n_points, size_t cb_offset) { + secp256k1_gej* points; + secp256k1_scalar* scalars; + struct secp256k1_strauss_state state; + size_t i; + + secp256k1_gej_set_infinity(r); + if (inp_g_sc == NULL && n_points == 0) { + return 1; + } + + if (!secp256k1_scratch_allocate_frame(scratch, secp256k1_strauss_scratch_size(n_points), STRAUSS_SCRATCH_OBJECTS)) { + return 0; + } + points = (secp256k1_gej*)secp256k1_scratch_alloc(scratch, n_points * sizeof(secp256k1_gej)); + scalars = (secp256k1_scalar*)secp256k1_scratch_alloc(scratch, n_points * sizeof(secp256k1_scalar)); + state.prej = (secp256k1_gej*)secp256k1_scratch_alloc(scratch, n_points * ECMULT_TABLE_SIZE(WINDOW_A) * sizeof(secp256k1_gej)); + state.zr = (secp256k1_fe*)secp256k1_scratch_alloc(scratch, n_points * ECMULT_TABLE_SIZE(WINDOW_A) * sizeof(secp256k1_fe)); +#ifdef USE_ENDOMORPHISM + state.pre_a = (secp256k1_ge*)secp256k1_scratch_alloc(scratch, n_points * 2 * ECMULT_TABLE_SIZE(WINDOW_A) * sizeof(secp256k1_ge)); + state.pre_a_lam = state.pre_a + n_points * ECMULT_TABLE_SIZE(WINDOW_A); +#else + state.pre_a = (secp256k1_ge*)secp256k1_scratch_alloc(scratch, n_points * ECMULT_TABLE_SIZE(WINDOW_A) * sizeof(secp256k1_ge)); +#endif + state.ps = (struct secp256k1_strauss_point_state*)secp256k1_scratch_alloc(scratch, n_points * sizeof(struct secp256k1_strauss_point_state)); + + for (i = 0; i < n_points; i++) { + secp256k1_ge point; + if (!cb(&scalars[i], &point, i+cb_offset, cbdata)) { + secp256k1_scratch_deallocate_frame(scratch); + return 0; + } + secp256k1_gej_set_ge(&points[i], &point); + } + secp256k1_ecmult_strauss_wnaf(ctx, &state, r, n_points, points, scalars, inp_g_sc); + secp256k1_scratch_deallocate_frame(scratch); + return 1; +} + +/* Wrapper for secp256k1_ecmult_multi_func interface */ +static int secp256k1_ecmult_strauss_batch_single(const secp256k1_ecmult_context *actx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n) { + return secp256k1_ecmult_strauss_batch(actx, scratch, r, inp_g_sc, cb, cbdata, n, 0); +} + +static size_t secp256k1_strauss_max_points(secp256k1_scratch *scratch) { + return secp256k1_scratch_max_allocation(scratch, STRAUSS_SCRATCH_OBJECTS) / secp256k1_strauss_scratch_size(1); +} + +/** Convert a number to WNAF notation. + * The number becomes represented by sum(2^{wi} * wnaf[i], i=0..WNAF_SIZE(w)+1) - return_val. + * It has the following guarantees: + * - each wnaf[i] is either 0 or an odd integer between -(1 << w) and (1 << w) + * - the number of words set is always WNAF_SIZE(w) + * - the returned skew is 0 or 1 + */ +static int secp256k1_wnaf_fixed(int *wnaf, const secp256k1_scalar *s, int w) { + int skew = 0; + int pos; + int max_pos; + int last_w; + const secp256k1_scalar *work = s; + + if (secp256k1_scalar_is_zero(s)) { + for (pos = 0; pos < WNAF_SIZE(w); pos++) { + wnaf[pos] = 0; + } + return 0; + } + + if (secp256k1_scalar_is_even(s)) { + skew = 1; + } + + wnaf[0] = secp256k1_scalar_get_bits_var(work, 0, w) + skew; + /* Compute last window size. Relevant when window size doesn't divide the + * number of bits in the scalar */ + last_w = WNAF_BITS - (WNAF_SIZE(w) - 1) * w; + + /* Store the position of the first nonzero word in max_pos to allow + * skipping leading zeros when calculating the wnaf. */ + for (pos = WNAF_SIZE(w) - 1; pos > 0; pos--) { + int val = secp256k1_scalar_get_bits_var(work, pos * w, pos == WNAF_SIZE(w)-1 ? last_w : w); + if(val != 0) { + break; + } + wnaf[pos] = 0; + } + max_pos = pos; + pos = 1; + + while (pos <= max_pos) { + int val = secp256k1_scalar_get_bits_var(work, pos * w, pos == WNAF_SIZE(w)-1 ? last_w : w); + if ((val & 1) == 0) { + wnaf[pos - 1] -= (1 << w); + wnaf[pos] = (val + 1); + } else { + wnaf[pos] = val; + } + /* Set a coefficient to zero if it is 1 or -1 and the proceeding digit + * is strictly negative or strictly positive respectively. Only change + * coefficients at previous positions because above code assumes that + * wnaf[pos - 1] is odd. + */ + if (pos >= 2 && ((wnaf[pos - 1] == 1 && wnaf[pos - 2] < 0) || (wnaf[pos - 1] == -1 && wnaf[pos - 2] > 0))) { + if (wnaf[pos - 1] == 1) { + wnaf[pos - 2] += 1 << w; + } else { + wnaf[pos - 2] -= 1 << w; + } + wnaf[pos - 1] = 0; + } + ++pos; + } + + return skew; +} + +struct secp256k1_pippenger_point_state { + int skew_na; + size_t input_pos; +}; + +struct secp256k1_pippenger_state { + int *wnaf_na; + struct secp256k1_pippenger_point_state* ps; +}; + +/* + * pippenger_wnaf computes the result of a multi-point multiplication as + * follows: The scalars are brought into wnaf with n_wnaf elements each. Then + * for every i < n_wnaf, first each point is added to a "bucket" corresponding + * to the point's wnaf[i]. Second, the buckets are added together such that + * r += 1*bucket[0] + 3*bucket[1] + 5*bucket[2] + ... + */ +static int secp256k1_ecmult_pippenger_wnaf(secp256k1_gej *buckets, int bucket_window, struct secp256k1_pippenger_state *state, secp256k1_gej *r, const secp256k1_scalar *sc, const secp256k1_ge *pt, size_t num) { + size_t n_wnaf = WNAF_SIZE(bucket_window+1); + size_t np; + size_t no = 0; + int i; + int j; + + for (np = 0; np < num; ++np) { + if (secp256k1_scalar_is_zero(&sc[np]) || secp256k1_ge_is_infinity(&pt[np])) { + continue; + } + state->ps[no].input_pos = np; + state->ps[no].skew_na = secp256k1_wnaf_fixed(&state->wnaf_na[no*n_wnaf], &sc[np], bucket_window+1); + no++; + } + secp256k1_gej_set_infinity(r); + + if (no == 0) { + return 1; + } + + for (i = n_wnaf - 1; i >= 0; i--) { + secp256k1_gej running_sum; + + for(j = 0; j < ECMULT_TABLE_SIZE(bucket_window+2); j++) { + secp256k1_gej_set_infinity(&buckets[j]); + } + + for (np = 0; np < no; ++np) { + int n = state->wnaf_na[np*n_wnaf + i]; + struct secp256k1_pippenger_point_state point_state = state->ps[np]; + secp256k1_ge tmp; + int idx; + + if (i == 0) { + /* correct for wnaf skew */ + int skew = point_state.skew_na; + if (skew) { + secp256k1_ge_neg(&tmp, &pt[point_state.input_pos]); + secp256k1_gej_add_ge_var(&buckets[0], &buckets[0], &tmp, NULL); + } + } + if (n > 0) { + idx = (n - 1)/2; + secp256k1_gej_add_ge_var(&buckets[idx], &buckets[idx], &pt[point_state.input_pos], NULL); + } else if (n < 0) { + idx = -(n + 1)/2; + secp256k1_ge_neg(&tmp, &pt[point_state.input_pos]); + secp256k1_gej_add_ge_var(&buckets[idx], &buckets[idx], &tmp, NULL); + } + } + + for(j = 0; j < bucket_window; j++) { + secp256k1_gej_double_var(r, r, NULL); + } + + secp256k1_gej_set_infinity(&running_sum); + /* Accumulate the sum: bucket[0] + 3*bucket[1] + 5*bucket[2] + 7*bucket[3] + ... + * = bucket[0] + bucket[1] + bucket[2] + bucket[3] + ... + * + 2 * (bucket[1] + 2*bucket[2] + 3*bucket[3] + ...) + * using an intermediate running sum: + * running_sum = bucket[0] + bucket[1] + bucket[2] + ... + * + * The doubling is done implicitly by deferring the final window doubling (of 'r'). + */ + for(j = ECMULT_TABLE_SIZE(bucket_window+2) - 1; j > 0; j--) { + secp256k1_gej_add_var(&running_sum, &running_sum, &buckets[j], NULL); + secp256k1_gej_add_var(r, r, &running_sum, NULL); + } + + secp256k1_gej_add_var(&running_sum, &running_sum, &buckets[0], NULL); + secp256k1_gej_double_var(r, r, NULL); + secp256k1_gej_add_var(r, r, &running_sum, NULL); + } + return 1; +} + +/** + * Returns optimal bucket_window (number of bits of a scalar represented by a + * set of buckets) for a given number of points. + */ +static int secp256k1_pippenger_bucket_window(size_t n) { +#ifdef USE_ENDOMORPHISM + if (n <= 1) { + return 1; + } else if (n <= 4) { + return 2; + } else if (n <= 20) { + return 3; + } else if (n <= 57) { + return 4; + } else if (n <= 136) { + return 5; + } else if (n <= 235) { + return 6; + } else if (n <= 1260) { + return 7; + } else if (n <= 4420) { + return 9; + } else if (n <= 7880) { + return 10; + } else if (n <= 16050) { + return 11; + } else { + return PIPPENGER_MAX_BUCKET_WINDOW; + } +#else + if (n <= 1) { + return 1; + } else if (n <= 11) { + return 2; + } else if (n <= 45) { + return 3; + } else if (n <= 100) { + return 4; + } else if (n <= 275) { + return 5; + } else if (n <= 625) { + return 6; + } else if (n <= 1850) { + return 7; + } else if (n <= 3400) { + return 8; + } else if (n <= 9630) { + return 9; + } else if (n <= 17900) { + return 10; + } else if (n <= 32800) { + return 11; + } else { + return PIPPENGER_MAX_BUCKET_WINDOW; + } +#endif +} + +/** + * Returns the maximum optimal number of points for a bucket_window. + */ +static size_t secp256k1_pippenger_bucket_window_inv(int bucket_window) { + switch(bucket_window) { +#ifdef USE_ENDOMORPHISM + case 1: return 1; + case 2: return 4; + case 3: return 20; + case 4: return 57; + case 5: return 136; + case 6: return 235; + case 7: return 1260; + case 8: return 1260; + case 9: return 4420; + case 10: return 7880; + case 11: return 16050; + case PIPPENGER_MAX_BUCKET_WINDOW: return SIZE_MAX; +#else + case 1: return 1; + case 2: return 11; + case 3: return 45; + case 4: return 100; + case 5: return 275; + case 6: return 625; + case 7: return 1850; + case 8: return 3400; + case 9: return 9630; + case 10: return 17900; + case 11: return 32800; + case PIPPENGER_MAX_BUCKET_WINDOW: return SIZE_MAX; +#endif + } + return 0; +} + + +#ifdef USE_ENDOMORPHISM +SECP256K1_INLINE static void secp256k1_ecmult_endo_split(secp256k1_scalar *s1, secp256k1_scalar *s2, secp256k1_ge *p1, secp256k1_ge *p2) { + secp256k1_scalar tmp = *s1; + secp256k1_scalar_split_lambda(s1, s2, &tmp); + secp256k1_ge_mul_lambda(p2, p1); + + if (secp256k1_scalar_is_high(s1)) { + secp256k1_scalar_negate(s1, s1); + secp256k1_ge_neg(p1, p1); + } + if (secp256k1_scalar_is_high(s2)) { + secp256k1_scalar_negate(s2, s2); + secp256k1_ge_neg(p2, p2); + } +} +#endif + +/** + * Returns the scratch size required for a given number of points (excluding + * base point G) without considering alignment. + */ +static size_t secp256k1_pippenger_scratch_size(size_t n_points, int bucket_window) { +#ifdef USE_ENDOMORPHISM + size_t entries = 2*n_points + 2; +#else + size_t entries = n_points + 1; +#endif + size_t entry_size = sizeof(secp256k1_ge) + sizeof(secp256k1_scalar) + sizeof(struct secp256k1_pippenger_point_state) + (WNAF_SIZE(bucket_window+1)+1)*sizeof(int); + return ((1<ps = (struct secp256k1_pippenger_point_state *) secp256k1_scratch_alloc(scratch, entries * sizeof(*state_space->ps)); + state_space->wnaf_na = (int *) secp256k1_scratch_alloc(scratch, entries*(WNAF_SIZE(bucket_window+1)) * sizeof(int)); + buckets = (secp256k1_gej *) secp256k1_scratch_alloc(scratch, (1<ps[i].skew_na = 0; + for(j = 0; j < WNAF_SIZE(bucket_window+1); j++) { + state_space->wnaf_na[i * WNAF_SIZE(bucket_window+1) + j] = 0; + } + } + for(i = 0; i < 1< max_alloc) { + break; + } + space_for_points = max_alloc - space_overhead; + + n_points = space_for_points/entry_size; + n_points = n_points > max_points ? max_points : n_points; + if (n_points > res) { + res = n_points; + } + if (n_points < max_points) { + /* A larger bucket_window may support even more points. But if we + * would choose that then the caller couldn't safely use any number + * smaller than what this function returns */ + break; + } + } + return res; +} + +/* Computes ecmult_multi by simply multiplying and adding each point. Does not + * require a scratch space */ +static int secp256k1_ecmult_multi_var_simple(const secp256k1_ecmult_context *ctx, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n_points) { + size_t point_idx; + secp256k1_scalar szero; + secp256k1_gej tmpj; + + secp256k1_scalar_set_int(&szero, 0); + /* r = inp_g_sc*G */ + secp256k1_gej_set_infinity(r); + secp256k1_ecmult(ctx, r, &tmpj, &szero, inp_g_sc); + for (point_idx = 0; point_idx < n_points; point_idx++) { + secp256k1_ge point; + secp256k1_gej pointj; + secp256k1_scalar scalar; + if (!cb(&scalar, &point, point_idx, cbdata)) { + return 0; + } + /* r += scalar*point */ + secp256k1_gej_set_ge(&pointj, &point); + secp256k1_ecmult(ctx, &tmpj, &pointj, &scalar, NULL); + secp256k1_gej_add_var(r, r, &tmpj, NULL); + } + return 1; +} + +typedef int (*secp256k1_ecmult_multi_func)(const secp256k1_ecmult_context*, secp256k1_scratch*, secp256k1_gej*, const secp256k1_scalar*, secp256k1_ecmult_multi_callback cb, void*, size_t); +static int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n) { + size_t i; + + int (*f)(const secp256k1_ecmult_context*, secp256k1_scratch*, secp256k1_gej*, const secp256k1_scalar*, secp256k1_ecmult_multi_callback cb, void*, size_t, size_t); + size_t max_points; + size_t n_batches; + size_t n_batch_points; + + secp256k1_gej_set_infinity(r); + if (inp_g_sc == NULL && n == 0) { + return 1; + } else if (n == 0) { + secp256k1_scalar szero; + secp256k1_scalar_set_int(&szero, 0); + secp256k1_ecmult(ctx, r, r, &szero, inp_g_sc); + return 1; + } + if (scratch == NULL) { + return secp256k1_ecmult_multi_var_simple(ctx, r, inp_g_sc, cb, cbdata, n); + } + + max_points = secp256k1_pippenger_max_points(scratch); + if (max_points == 0) { + return 0; + } else if (max_points > ECMULT_MAX_POINTS_PER_BATCH) { + max_points = ECMULT_MAX_POINTS_PER_BATCH; + } + n_batches = (n+max_points-1)/max_points; + n_batch_points = (n+n_batches-1)/n_batches; + + if (n_batch_points >= ECMULT_PIPPENGER_THRESHOLD) { + f = secp256k1_ecmult_pippenger_batch; + } else { + max_points = secp256k1_strauss_max_points(scratch); + if (max_points == 0) { + return 0; + } + n_batches = (n+max_points-1)/max_points; + n_batch_points = (n+n_batches-1)/n_batches; + f = secp256k1_ecmult_strauss_batch; + } + for(i = 0; i < n_batches; i++) { + size_t nbp = n < n_batch_points ? n : n_batch_points; + size_t offset = n_batch_points*i; + secp256k1_gej tmp; + if (!f(ctx, scratch, &tmp, i == 0 ? inp_g_sc : NULL, cb, cbdata, nbp, offset)) { + return 0; + } + secp256k1_gej_add_var(r, r, &tmp, NULL); + n -= nbp; + } + return 1; +} + +#endif /* SECP256K1_ECMULT_IMPL_H */ + +#endif + diff --git a/src/secp256k1/src/modules/musig/Makefile.am.include b/src/secp256k1/src/modules/musig/Makefile.am.include new file mode 100644 index 000000000..34583a23a --- /dev/null +++ b/src/secp256k1/src/modules/musig/Makefile.am.include @@ -0,0 +1,17 @@ +include_HEADERS += include/secp256k1_musig.h +noinst_HEADERS += src/modules/musig/main_impl.h +noinst_HEADERS += src/modules/musig/tests_impl.h + +noinst_PROGRAMS += example_musig +example_musig_SOURCES = src/modules/musig/example.c +example_musig_CPPFLAGS = -DSECP256K1_BUILD -I$(top_srcdir)/include $(SECP_INCLUDES) +if !ENABLE_COVERAGE +example_musig_CPPFLAGS += -DVERIFY +endif +example_musig_LDADD = libsecp256k1.la $(SECP_LIBS) +example_musig_LDFLAGS = -static + +if USE_TESTS +TESTS += example_musig +endif + diff --git a/src/secp256k1/src/modules/musig/example.c b/src/secp256k1/src/modules/musig/example.c new file mode 100644 index 000000000..ceae18686 --- /dev/null +++ b/src/secp256k1/src/modules/musig/example.c @@ -0,0 +1,166 @@ +/********************************************************************** + * Copyright (c) 2018 Jonas Nick * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +/** + * This file demonstrates how to use the MuSig module to create a multisignature. + * Additionally, see the documentation in include/secp256k1_musig.h. + */ + +#include +#include +#include +#include +#include + + /* Number of public keys involved in creating the aggregate signature */ +#define N_SIGNERS 3 + /* Create a key pair and store it in seckey and pubkey */ +int create_key(const secp256k1_context* ctx, unsigned char* seckey, secp256k1_pubkey* pubkey) { + int ret; + FILE *frand = fopen("/dev/urandom", "r"); + if (frand == NULL) { + return 0; + } + do { + if(!fread(seckey, 32, 1, frand)) { + fclose(frand); + return 0; + } + /* The probability that this not a valid secret key is approximately 2^-128 */ + } while (!secp256k1_ec_seckey_verify(ctx, seckey)); + fclose(frand); + ret = secp256k1_ec_pubkey_create(ctx, pubkey, seckey); + return ret; +} + +/* Sign a message hash with the given key pairs and store the result in sig */ +int sign(const secp256k1_context* ctx, unsigned char seckeys[][32], const secp256k1_pubkey* pubkeys, const unsigned char* msg32, secp256k1_schnorrsig *sig) { + secp256k1_musig_session musig_session[N_SIGNERS]; + unsigned char nonce_commitment[N_SIGNERS][32]; + const unsigned char *nonce_commitment_ptr[N_SIGNERS]; + secp256k1_musig_session_signer_data signer_data[N_SIGNERS][N_SIGNERS]; + secp256k1_pubkey nonce[N_SIGNERS]; + int i, j; + secp256k1_musig_partial_signature partial_sig[N_SIGNERS]; + + for (i = 0; i < N_SIGNERS; i++) { + FILE *frand; + unsigned char session_id32[32]; + unsigned char pk_hash[32]; + secp256k1_pubkey combined_pk; + + /* Create combined pubkey and initialize signer data */ + if (!secp256k1_musig_pubkey_combine(ctx, NULL, &combined_pk, pk_hash, pubkeys, N_SIGNERS)) { + return 0; + } + /* Create random session ID. It is absolutely necessary that the session ID + * is unique for every call of secp256k1_musig_session_initialize. Otherwise + * it's trivial for an attacker to extract the secret key! */ + frand = fopen("/dev/urandom", "r"); + if(frand == NULL) { + return 0; + } + if (!fread(session_id32, 32, 1, frand)) { + fclose(frand); + return 0; + } + fclose(frand); + /* Initialize session */ + if (!secp256k1_musig_session_initialize(ctx, &musig_session[i], signer_data[i], nonce_commitment[i], session_id32, msg32, &combined_pk, pk_hash, N_SIGNERS, i, seckeys[i])) { + return 0; + } + nonce_commitment_ptr[i] = &nonce_commitment[i][0]; + } + /* Communication round 1: Exchange nonce commitments */ + for (i = 0; i < N_SIGNERS; i++) { + /* Set nonce commitments in the signer data and get the own public nonce */ + if (!secp256k1_musig_session_get_public_nonce(ctx, &musig_session[i], signer_data[i], &nonce[i], nonce_commitment_ptr, N_SIGNERS)) { + return 0; + } + } + /* Communication round 2: Exchange nonces */ + for (i = 0; i < N_SIGNERS; i++) { + for (j = 0; j < N_SIGNERS; j++) { + if (!secp256k1_musig_set_nonce(ctx, &signer_data[i][j], &nonce[j])) { + /* Signer j's nonce does not match the nonce commitment. In this case + * abort the protocol. If you make another attempt at finishing the + * protocol, create a new session (with a fresh session ID!). */ + return 0; + } + } + if (!secp256k1_musig_session_combine_nonces(ctx, &musig_session[i], signer_data[i], N_SIGNERS, NULL, NULL)) { + return 0; + } + } + for (i = 0; i < N_SIGNERS; i++) { + if (!secp256k1_musig_partial_sign(ctx, &musig_session[i], &partial_sig[i])) { + return 0; + } + } + /* Communication round 3: Exchange partial signatures */ + for (i = 0; i < N_SIGNERS; i++) { + for (j = 0; j < N_SIGNERS; j++) { + /* To check whether signing was successful, it suffices to either verify + * the the combined signature with the combined public key using + * secp256k1_schnorrsig_verify, or verify all partial signatures of all + * signers individually. Verifying the combined signature is cheaper but + * verifying the individual partial signatures has the advantage that it + * can be used to determine which of the partial signatures are invalid + * (if any), i.e., which of the partial signatures cause the combined + * signature to be invalid and thus the protocol run to fail. It's also + * fine to first verify the combined sig, and only verify the individual + * sigs if it does not work. + */ + if (!secp256k1_musig_partial_sig_verify(ctx, &musig_session[i], &signer_data[i][j], &partial_sig[j], &pubkeys[j])) { + return 0; + } + } + } + return secp256k1_musig_partial_sig_combine(ctx, &musig_session[0], sig, partial_sig, N_SIGNERS); +} + + int main(void) { + secp256k1_context* ctx; + int i; + unsigned char seckeys[N_SIGNERS][32]; + secp256k1_pubkey pubkeys[N_SIGNERS]; + secp256k1_pubkey combined_pk; + unsigned char msg[32] = "this_could_be_the_hash_of_a_msg!"; + secp256k1_schnorrsig sig; + + /* Create a context for signing and verification */ + ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); + printf("Creating key pairs......"); + for (i = 0; i < N_SIGNERS; i++) { + if (!create_key(ctx, seckeys[i], &pubkeys[i])) { + printf("FAILED\n"); + return 1; + } + } + printf("ok\n"); + printf("Combining public keys..."); + if (!secp256k1_musig_pubkey_combine(ctx, NULL, &combined_pk, NULL, pubkeys, N_SIGNERS)) { + printf("FAILED\n"); + return 1; + } + printf("ok\n"); + printf("Signing message........."); + if (!sign(ctx, seckeys, pubkeys, msg, &sig)) { + printf("FAILED\n"); + return 1; + } + printf("ok\n"); + printf("Verifying signature....."); + if (!secp256k1_schnorrsig_verify(ctx, &sig, msg, &combined_pk)) { + printf("FAILED\n"); + return 1; + } + printf("ok\n"); + secp256k1_context_destroy(ctx); + return 0; +} + + diff --git a/src/secp256k1/src/modules/musig/main_impl.h b/src/secp256k1/src/modules/musig/main_impl.h new file mode 100644 index 000000000..dece823d6 --- /dev/null +++ b/src/secp256k1/src/modules/musig/main_impl.h @@ -0,0 +1,631 @@ + +/********************************************************************** + * Copyright (c) 2018 Andrew Poelstra, Jonas Nick * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef _SECP256K1_MODULE_MUSIG_MAIN_ +#define _SECP256K1_MODULE_MUSIG_MAIN_ + +#include "include/secp256k1.h" +#include "include/secp256k1_musig.h" +#include "hash.h" + +/* Computes ell = SHA256(pk[0], ..., pk[np-1]) */ +static int secp256k1_musig_compute_ell(const secp256k1_context *ctx, unsigned char *ell, const secp256k1_pubkey *pk, size_t np) { + secp256k1_sha256 sha; + size_t i; + + secp256k1_sha256_initialize(&sha); + for (i = 0; i < np; i++) { + unsigned char ser[33]; + size_t serlen = sizeof(ser); + if (!secp256k1_ec_pubkey_serialize(ctx, ser, &serlen, &pk[i], SECP256K1_EC_COMPRESSED)) { + return 0; + } + secp256k1_sha256_write(&sha, ser, serlen); + } + secp256k1_sha256_finalize(&sha, ell); + return 1; +} + +/* Initializes SHA256 with fixed midstate. This midstate was computed by applying + * SHA256 to SHA256("MuSig coefficient")||SHA256("MuSig coefficient"). */ +static void secp256k1_musig_sha256_init_tagged(secp256k1_sha256 *sha) { + secp256k1_sha256_initialize(sha); + + sha->s[0] = 0x0fd0690cul; + sha->s[1] = 0xfefeae97ul; + sha->s[2] = 0x996eac7ful; + sha->s[3] = 0x5c30d864ul; + sha->s[4] = 0x8c4a0573ul; + sha->s[5] = 0xaca1a22ful; + sha->s[6] = 0x6f43b801ul; + sha->s[7] = 0x85ce27cdul; + sha->bytes = 64; +} + +/* Compute r = SHA256(ell, idx). The four bytes of idx are serialized least significant byte first. */ +static void secp256k1_musig_coefficient(secp256k1_scalar *r, const unsigned char *ell, uint32_t idx) { + secp256k1_sha256 sha; + unsigned char buf[32]; + size_t i; + + secp256k1_musig_sha256_init_tagged(&sha); + secp256k1_sha256_write(&sha, ell, 32); + /* We're hashing the index of the signer instead of its public key as specified + * in the MuSig paper. This reduces the total amount of data that needs to be + * hashed. + * Additionally, it prevents creating identical musig_coefficients for identical + * public keys. A participant Bob could choose his public key to be the same as + * Alice's, then replay Alice's messages (nonce and partial signature) to create + * a valid partial signature. This is not a problem for MuSig per se, but could + * result in subtle issues with protocols building on threshold signatures. + * With the assumption that public keys are unique, hashing the index is + * equivalent to hashing the public key. Because the public key can be + * identified by the index given the ordered list of public keys (included in + * ell), the index is just a different encoding of the public key.*/ + for (i = 0; i < sizeof(uint32_t); i++) { + unsigned char c = idx; + secp256k1_sha256_write(&sha, &c, 1); + idx >>= 8; + } + secp256k1_sha256_finalize(&sha, buf); + secp256k1_scalar_set_b32(r, buf, NULL); +} + +typedef struct { + const secp256k1_context *ctx; + unsigned char ell[32]; + const secp256k1_pubkey *pks; +} secp256k1_musig_pubkey_combine_ecmult_data; + +/* Callback for batch EC multiplication to compute ell_0*P0 + ell_1*P1 + ... */ +static int secp256k1_musig_pubkey_combine_callback(secp256k1_scalar *sc, secp256k1_ge *pt, size_t idx, void *data) { + secp256k1_musig_pubkey_combine_ecmult_data *ctx = (secp256k1_musig_pubkey_combine_ecmult_data *) data; + secp256k1_musig_coefficient(sc, ctx->ell, idx); + return secp256k1_pubkey_load(ctx->ctx, pt, &ctx->pks[idx]); +} + + +static void secp256k1_musig_signers_init(secp256k1_musig_session_signer_data *signers, uint32_t n_signers) { + uint32_t i; + for (i = 0; i < n_signers; i++) { + memset(&signers[i], 0, sizeof(signers[i])); + signers[i].index = i; + signers[i].present = 0; + } +} + +int secp256k1_musig_pubkey_combine(const secp256k1_context* ctx, secp256k1_scratch_space *scratch, secp256k1_pubkey *combined_pk, unsigned char *pk_hash32, const secp256k1_pubkey *pubkeys, size_t n_pubkeys) { + secp256k1_musig_pubkey_combine_ecmult_data ecmult_data; + secp256k1_gej pkj; + secp256k1_ge pkp; + + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(combined_pk != NULL); + ARG_CHECK(secp256k1_ecmult_context_is_built(&ctx->ecmult_ctx)); + ARG_CHECK(pubkeys != NULL); + ARG_CHECK(n_pubkeys > 0); + + ecmult_data.ctx = ctx; + ecmult_data.pks = pubkeys; + if (!secp256k1_musig_compute_ell(ctx, ecmult_data.ell, pubkeys, n_pubkeys)) { + return 0; + } + if (!secp256k1_ecmult_multi_var(&ctx->ecmult_ctx, scratch, &pkj, NULL, secp256k1_musig_pubkey_combine_callback, (void *) &ecmult_data, n_pubkeys)) { + return 0; + } + secp256k1_ge_set_gej(&pkp, &pkj); + secp256k1_pubkey_save(combined_pk, &pkp); + + if (pk_hash32 != NULL) { + memcpy(pk_hash32, ecmult_data.ell, 32); + } + return 1; +} + +int secp256k1_musig_session_initialize(const secp256k1_context* ctx, secp256k1_musig_session *session, secp256k1_musig_session_signer_data *signers, unsigned char *nonce_commitment32, const unsigned char *session_id32, const unsigned char *msg32, const secp256k1_pubkey *combined_pk, const unsigned char *pk_hash32, size_t n_signers, size_t my_index, const unsigned char *seckey) { + unsigned char combined_ser[33]; + size_t combined_ser_size = sizeof(combined_ser); + int overflow; + secp256k1_scalar secret; + secp256k1_scalar mu; + secp256k1_sha256 sha; + secp256k1_gej rj; + secp256k1_ge rp; + + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(secp256k1_ecmult_gen_context_is_built(&ctx->ecmult_gen_ctx)); + ARG_CHECK(session != NULL); + ARG_CHECK(signers != NULL); + ARG_CHECK(nonce_commitment32 != NULL); + ARG_CHECK(session_id32 != NULL); + ARG_CHECK(combined_pk != NULL); + ARG_CHECK(pk_hash32 != NULL); + ARG_CHECK(seckey != NULL); + + memset(session, 0, sizeof(*session)); + + if (msg32 != NULL) { + memcpy(session->msg, msg32, 32); + session->msg_is_set = 1; + } else { + session->msg_is_set = 0; + } + memcpy(&session->combined_pk, combined_pk, sizeof(*combined_pk)); + memcpy(session->pk_hash, pk_hash32, 32); + session->nonce_is_set = 0; + session->has_secret_data = 1; + if (n_signers == 0 || my_index >= n_signers) { + return 0; + } + if (n_signers > UINT32_MAX) { + return 0; + } + session->n_signers = (uint32_t) n_signers; + secp256k1_musig_signers_init(signers, session->n_signers); + session->nonce_commitments_hash_is_set = 0; + + /* Compute secret key */ + secp256k1_scalar_set_b32(&secret, seckey, &overflow); + if (overflow) { + secp256k1_scalar_clear(&secret); + return 0; + } + secp256k1_musig_coefficient(&mu, pk_hash32, (uint32_t) my_index); + secp256k1_scalar_mul(&secret, &secret, &mu); + secp256k1_scalar_get_b32(session->seckey, &secret); + + /* Compute secret nonce */ + secp256k1_sha256_initialize(&sha); + secp256k1_sha256_write(&sha, session_id32, 32); + if (session->msg_is_set) { + secp256k1_sha256_write(&sha, msg32, 32); + } + secp256k1_ec_pubkey_serialize(ctx, combined_ser, &combined_ser_size, combined_pk, SECP256K1_EC_COMPRESSED); + secp256k1_sha256_write(&sha, combined_ser, combined_ser_size); + secp256k1_sha256_write(&sha, seckey, 32); + secp256k1_sha256_finalize(&sha, session->secnonce); + secp256k1_scalar_set_b32(&secret, session->secnonce, &overflow); + if (overflow) { + secp256k1_scalar_clear(&secret); + return 0; + } + + /* Compute public nonce and commitment */ + secp256k1_ecmult_gen(&ctx->ecmult_gen_ctx, &rj, &secret); + secp256k1_ge_set_gej(&rp, &rj); + secp256k1_pubkey_save(&session->nonce, &rp); + + if (nonce_commitment32 != NULL) { + unsigned char commit[33]; + size_t commit_size = sizeof(commit); + secp256k1_sha256_initialize(&sha); + secp256k1_ec_pubkey_serialize(ctx, commit, &commit_size, &session->nonce, SECP256K1_EC_COMPRESSED); + secp256k1_sha256_write(&sha, commit, commit_size); + secp256k1_sha256_finalize(&sha, nonce_commitment32); + } + + secp256k1_scalar_clear(&secret); + return 1; +} + +int secp256k1_musig_session_get_public_nonce(const secp256k1_context* ctx, secp256k1_musig_session *session, secp256k1_musig_session_signer_data *signers, secp256k1_pubkey *nonce, const unsigned char *const *commitments, size_t n_commitments) { + secp256k1_sha256 sha; + unsigned char nonce_commitments_hash[32]; + size_t i; + (void) ctx; + + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(session != NULL); + ARG_CHECK(signers != NULL); + ARG_CHECK(nonce != NULL); + ARG_CHECK(commitments != NULL); + + if (!session->has_secret_data || n_commitments != session->n_signers) { + return 0; + } + for (i = 0; i < n_commitments; i++) { + ARG_CHECK(commitments[i] != NULL); + } + + secp256k1_sha256_initialize(&sha); + for (i = 0; i < n_commitments; i++) { + memcpy(signers[i].nonce_commitment, commitments[i], 32); + secp256k1_sha256_write(&sha, commitments[i], 32); + } + secp256k1_sha256_finalize(&sha, nonce_commitments_hash); + if (session->nonce_commitments_hash_is_set + && memcmp(session->nonce_commitments_hash, nonce_commitments_hash, 32) != 0) { + /* Abort if get_public_nonce has been called before with a different array of + * commitments. */ + return 0; + } + memcpy(session->nonce_commitments_hash, nonce_commitments_hash, 32); + session->nonce_commitments_hash_is_set = 1; + memcpy(nonce, &session->nonce, sizeof(*nonce)); + return 1; +} + +int secp256k1_musig_session_initialize_verifier(const secp256k1_context* ctx, secp256k1_musig_session *session, secp256k1_musig_session_signer_data *signers, const unsigned char *msg32, const secp256k1_pubkey *combined_pk, const unsigned char *pk_hash32, const unsigned char *const *commitments, size_t n_signers) { + size_t i; + + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(session != NULL); + ARG_CHECK(signers != NULL); + ARG_CHECK(combined_pk != NULL); + ARG_CHECK(pk_hash32 != NULL); + ARG_CHECK(commitments != NULL); + /* Check n_signers before checking commitments to allow testing the case where + * n_signers is big without allocating the space. */ + if (n_signers > UINT32_MAX) { + return 0; + } + for (i = 0; i < n_signers; i++) { + ARG_CHECK(commitments[i] != NULL); + } + (void) ctx; + + memset(session, 0, sizeof(*session)); + + memcpy(&session->combined_pk, combined_pk, sizeof(*combined_pk)); + if (n_signers == 0) { + return 0; + } + session->n_signers = (uint32_t) n_signers; + secp256k1_musig_signers_init(signers, session->n_signers); + + memcpy(session->pk_hash, pk_hash32, 32); + session->nonce_is_set = 0; + session->msg_is_set = 0; + if (msg32 != NULL) { + memcpy(session->msg, msg32, 32); + session->msg_is_set = 1; + } + session->has_secret_data = 0; + session->nonce_commitments_hash_is_set = 0; + + for (i = 0; i < n_signers; i++) { + memcpy(signers[i].nonce_commitment, commitments[i], 32); + } + return 1; +} + +int secp256k1_musig_set_nonce(const secp256k1_context* ctx, secp256k1_musig_session_signer_data *signer, const secp256k1_pubkey *nonce) { + unsigned char commit[33]; + size_t commit_size = sizeof(commit); + secp256k1_sha256 sha; + + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(signer != NULL); + ARG_CHECK(nonce != NULL); + + secp256k1_sha256_initialize(&sha); + secp256k1_ec_pubkey_serialize(ctx, commit, &commit_size, nonce, SECP256K1_EC_COMPRESSED); + secp256k1_sha256_write(&sha, commit, commit_size); + secp256k1_sha256_finalize(&sha, commit); + + if (memcmp(commit, signer->nonce_commitment, 32) != 0) { + return 0; + } + memcpy(&signer->nonce, nonce, sizeof(*nonce)); + signer->present = 1; + return 1; +} + +int secp256k1_musig_session_combine_nonces(const secp256k1_context* ctx, secp256k1_musig_session *session, const secp256k1_musig_session_signer_data *signers, size_t n_signers, int *nonce_is_negated, const secp256k1_pubkey *adaptor) { + secp256k1_gej combined_noncej; + secp256k1_ge combined_noncep; + secp256k1_ge noncep; + secp256k1_sha256 sha; + unsigned char nonce_commitments_hash[32]; + size_t i; + + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(session != NULL); + ARG_CHECK(signers != NULL); + + if (n_signers != session->n_signers) { + return 0; + } + secp256k1_sha256_initialize(&sha); + secp256k1_gej_set_infinity(&combined_noncej); + for (i = 0; i < n_signers; i++) { + if (!signers[i].present) { + return 0; + } + secp256k1_sha256_write(&sha, signers[i].nonce_commitment, 32); + secp256k1_pubkey_load(ctx, &noncep, &signers[i].nonce); + secp256k1_gej_add_ge_var(&combined_noncej, &combined_noncej, &noncep, NULL); + } + secp256k1_sha256_finalize(&sha, nonce_commitments_hash); + /* Either the session is a verifier session or or the nonce_commitments_hash has + * been set in `musig_session_get_public_nonce`. */ + VERIFY_CHECK(!session->has_secret_data || session->nonce_commitments_hash_is_set); + if (session->has_secret_data + && memcmp(session->nonce_commitments_hash, nonce_commitments_hash, 32) != 0) { + /* If the signers' commitments changed between get_public_nonce and now we + * have to abort because in that case they may have seen our nonce before + * creating their commitment. That can happen if the signer_data given to + * this function is different to the signer_data given to get_public_nonce. + * */ + return 0; + } + + /* Add public adaptor to nonce */ + if (adaptor != NULL) { + secp256k1_pubkey_load(ctx, &noncep, adaptor); + secp256k1_gej_add_ge_var(&combined_noncej, &combined_noncej, &noncep, NULL); + } + secp256k1_ge_set_gej(&combined_noncep, &combined_noncej); + if (secp256k1_fe_is_quad_var(&combined_noncep.y)) { + session->nonce_is_negated = 0; + } else { + session->nonce_is_negated = 1; + secp256k1_ge_neg(&combined_noncep, &combined_noncep); + } + if (nonce_is_negated != NULL) { + *nonce_is_negated = session->nonce_is_negated; + } + secp256k1_pubkey_save(&session->combined_nonce, &combined_noncep); + session->nonce_is_set = 1; + return 1; +} + +int secp256k1_musig_session_set_msg(const secp256k1_context* ctx, secp256k1_musig_session *session, const unsigned char *msg32) { + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(session != NULL); + ARG_CHECK(msg32 != NULL); + + if (session->msg_is_set) { + return 0; + } + memcpy(session->msg, msg32, 32); + session->msg_is_set = 1; + return 1; +} + +int secp256k1_musig_partial_signature_serialize(const secp256k1_context* ctx, unsigned char *out32, const secp256k1_musig_partial_signature* sig) { + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(out32 != NULL); + ARG_CHECK(sig != NULL); + memcpy(out32, sig->data, 32); + return 1; +} + +int secp256k1_musig_partial_signature_parse(const secp256k1_context* ctx, secp256k1_musig_partial_signature* sig, const unsigned char *in32) { + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(sig != NULL); + ARG_CHECK(in32 != NULL); + memcpy(sig->data, in32, 32); + return 1; +} + +/* Compute msghash = SHA256(combined_nonce, combined_pk, msg) */ +static int secp256k1_musig_compute_messagehash(const secp256k1_context *ctx, unsigned char *msghash, const secp256k1_musig_session *session) { + unsigned char buf[33]; + size_t bufsize = 33; + secp256k1_ge rp; + secp256k1_sha256 sha; + + secp256k1_sha256_initialize(&sha); + if (!session->nonce_is_set) { + return 0; + } + secp256k1_pubkey_load(ctx, &rp, &session->combined_nonce); + secp256k1_fe_get_b32(buf, &rp.x); + secp256k1_sha256_write(&sha, buf, 32); + secp256k1_ec_pubkey_serialize(ctx, buf, &bufsize, &session->combined_pk, SECP256K1_EC_COMPRESSED); + VERIFY_CHECK(bufsize == 33); + secp256k1_sha256_write(&sha, buf, bufsize); + if (!session->msg_is_set) { + return 0; + } + secp256k1_sha256_write(&sha, session->msg, 32); + secp256k1_sha256_finalize(&sha, msghash); + return 1; +} + +int secp256k1_musig_partial_sign(const secp256k1_context* ctx, const secp256k1_musig_session *session, secp256k1_musig_partial_signature *partial_sig) { + unsigned char msghash[32]; + int overflow; + secp256k1_scalar sk; + secp256k1_scalar e, k; + + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(partial_sig != NULL); + ARG_CHECK(session != NULL); + + if (!session->nonce_is_set || !session->has_secret_data) { + return 0; + } + + /* build message hash */ + if (!secp256k1_musig_compute_messagehash(ctx, msghash, session)) { + return 0; + } + secp256k1_scalar_set_b32(&e, msghash, NULL); + + secp256k1_scalar_set_b32(&sk, session->seckey, &overflow); + if (overflow) { + secp256k1_scalar_clear(&sk); + return 0; + } + + secp256k1_scalar_set_b32(&k, session->secnonce, &overflow); + if (overflow || secp256k1_scalar_is_zero(&k)) { + secp256k1_scalar_clear(&sk); + secp256k1_scalar_clear(&k); + return 0; + } + if (session->nonce_is_negated) { + secp256k1_scalar_negate(&k, &k); + } + + /* Sign */ + secp256k1_scalar_mul(&e, &e, &sk); + secp256k1_scalar_add(&e, &e, &k); + secp256k1_scalar_get_b32(&partial_sig->data[0], &e); + secp256k1_scalar_clear(&sk); + secp256k1_scalar_clear(&k); + + return 1; +} + +int secp256k1_musig_partial_sig_combine(const secp256k1_context* ctx, const secp256k1_musig_session *session, secp256k1_schnorrsig *sig, const secp256k1_musig_partial_signature *partial_sigs, size_t n_sigs) { + size_t i; + secp256k1_scalar s; + secp256k1_ge noncep; + (void) ctx; + + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(sig != NULL); + ARG_CHECK(partial_sigs != NULL); + ARG_CHECK(session != NULL); + + if (!session->nonce_is_set) { + return 0; + } + if (n_sigs != session->n_signers) { + return 0; + } + secp256k1_scalar_clear(&s); + for (i = 0; i < n_sigs; i++) { + int overflow; + secp256k1_scalar term; + + secp256k1_scalar_set_b32(&term, partial_sigs[i].data, &overflow); + if (overflow) { + return 0; + } + secp256k1_scalar_add(&s, &s, &term); + } + + secp256k1_pubkey_load(ctx, &noncep, &session->combined_nonce); + VERIFY_CHECK(secp256k1_fe_is_quad_var(&noncep.y)); + secp256k1_fe_normalize(&noncep.x); + secp256k1_fe_get_b32(&sig->data[0], &noncep.x); + secp256k1_scalar_get_b32(&sig->data[32], &s); + + return 1; +} + +int secp256k1_musig_partial_sig_verify(const secp256k1_context* ctx, const secp256k1_musig_session *session, const secp256k1_musig_session_signer_data *signer, const secp256k1_musig_partial_signature *partial_sig, const secp256k1_pubkey *pubkey) { + unsigned char msghash[32]; + secp256k1_scalar s; + secp256k1_scalar e; + secp256k1_scalar mu; + secp256k1_gej rj; + secp256k1_ge rp; + int overflow; + + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(secp256k1_ecmult_context_is_built(&ctx->ecmult_ctx)); + ARG_CHECK(session != NULL); + ARG_CHECK(signer != NULL); + ARG_CHECK(partial_sig != NULL); + ARG_CHECK(pubkey != NULL); + + if (!session->nonce_is_set || !signer->present) { + return 0; + } + secp256k1_scalar_set_b32(&s, partial_sig->data, &overflow); + if (overflow) { + return 0; + } + if (!secp256k1_musig_compute_messagehash(ctx, msghash, session)) { + return 0; + } + secp256k1_scalar_set_b32(&e, msghash, NULL); + + /* Multiplying the messagehash by the musig coefficient is equivalent + * to multiplying the signer's public key by the coefficient, except + * much easier to do. */ + secp256k1_musig_coefficient(&mu, session->pk_hash, signer->index); + secp256k1_scalar_mul(&e, &e, &mu); + + if (!secp256k1_pubkey_load(ctx, &rp, &signer->nonce)) { + return 0; + } + + if (!secp256k1_schnorrsig_real_verify(ctx, &rj, &s, &e, pubkey)) { + return 0; + } + if (!session->nonce_is_negated) { + secp256k1_ge_neg(&rp, &rp); + } + secp256k1_gej_add_ge_var(&rj, &rj, &rp, NULL); + + return secp256k1_gej_is_infinity(&rj); +} + +int secp256k1_musig_partial_sig_adapt(const secp256k1_context* ctx, secp256k1_musig_partial_signature *adaptor_sig, const secp256k1_musig_partial_signature *partial_sig, const unsigned char *sec_adaptor32, int nonce_is_negated) { + secp256k1_scalar s; + secp256k1_scalar t; + int overflow; + + (void) ctx; + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(adaptor_sig != NULL); + ARG_CHECK(partial_sig != NULL); + ARG_CHECK(sec_adaptor32 != NULL); + + secp256k1_scalar_set_b32(&s, partial_sig->data, &overflow); + if (overflow) { + return 0; + } + secp256k1_scalar_set_b32(&t, sec_adaptor32, &overflow); + if (overflow) { + secp256k1_scalar_clear(&t); + return 0; + } + + if (nonce_is_negated) { + secp256k1_scalar_negate(&t, &t); + } + + secp256k1_scalar_add(&s, &s, &t); + secp256k1_scalar_get_b32(adaptor_sig->data, &s); + secp256k1_scalar_clear(&t); + return 1; +} + +int secp256k1_musig_extract_secret_adaptor(const secp256k1_context* ctx, unsigned char *sec_adaptor32, const secp256k1_schnorrsig *sig, const secp256k1_musig_partial_signature *partial_sigs, size_t n_partial_sigs, int nonce_is_negated) { + secp256k1_scalar t; + secp256k1_scalar s; + int overflow; + size_t i; + + (void) ctx; + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(sec_adaptor32 != NULL); + ARG_CHECK(sig != NULL); + ARG_CHECK(partial_sigs != NULL); + + secp256k1_scalar_set_b32(&t, &sig->data[32], &overflow); + if (overflow) { + return 0; + } + secp256k1_scalar_negate(&t, &t); + + for (i = 0; i < n_partial_sigs; i++) { + secp256k1_scalar_set_b32(&s, partial_sigs[i].data, &overflow); + if (overflow) { + secp256k1_scalar_clear(&t); + return 0; + } + secp256k1_scalar_add(&t, &t, &s); + } + + if (!nonce_is_negated) { + secp256k1_scalar_negate(&t, &t); + } + secp256k1_scalar_get_b32(sec_adaptor32, &t); + secp256k1_scalar_clear(&t); + return 1; +} + +#endif + diff --git a/src/secp256k1/src/modules/musig/tests_impl.h b/src/secp256k1/src/modules/musig/tests_impl.h new file mode 100644 index 000000000..c58ae95af --- /dev/null +++ b/src/secp256k1/src/modules/musig/tests_impl.h @@ -0,0 +1,758 @@ +/********************************************************************** + * Copyright (c) 2018 Andrew Poelstra * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef _SECP256K1_MODULE_MUSIG_TESTS_ +#define _SECP256K1_MODULE_MUSIG_TESTS_ + +#include "secp256k1_musig.h" + +void musig_api_tests(secp256k1_scratch_space *scratch) { + secp256k1_scratch_space *scratch_small; + secp256k1_musig_session session[2]; + secp256k1_musig_session verifier_session; + secp256k1_musig_session_signer_data signer0[2]; + secp256k1_musig_session_signer_data signer1[2]; + secp256k1_musig_session_signer_data verifier_signer_data[2]; + secp256k1_musig_partial_signature partial_sig[2]; + secp256k1_musig_partial_signature partial_sig_adapted[2]; + secp256k1_musig_partial_signature partial_sig_overflow; + secp256k1_schnorrsig final_sig; + secp256k1_schnorrsig final_sig_cmp; + + unsigned char buf[32]; + unsigned char sk[2][32]; + unsigned char ones[32]; + unsigned char session_id[2][32]; + unsigned char nonce_commitment[2][32]; + int nonce_is_negated; + const unsigned char *ncs[2]; + unsigned char msg[32]; + unsigned char msghash[32]; + secp256k1_pubkey combined_pk; + unsigned char pk_hash[32]; + secp256k1_pubkey pk[2]; + + unsigned char sec_adaptor[32]; + unsigned char sec_adaptor1[32]; + secp256k1_pubkey adaptor; + + /** setup **/ + secp256k1_context *none = secp256k1_context_create(SECP256K1_CONTEXT_NONE); + secp256k1_context *sign = secp256k1_context_create(SECP256K1_CONTEXT_SIGN); + secp256k1_context *vrfy = secp256k1_context_create(SECP256K1_CONTEXT_VERIFY); + int ecount; + + secp256k1_context_set_error_callback(none, counting_illegal_callback_fn, &ecount); + secp256k1_context_set_error_callback(sign, counting_illegal_callback_fn, &ecount); + secp256k1_context_set_error_callback(vrfy, counting_illegal_callback_fn, &ecount); + secp256k1_context_set_illegal_callback(none, counting_illegal_callback_fn, &ecount); + secp256k1_context_set_illegal_callback(sign, counting_illegal_callback_fn, &ecount); + secp256k1_context_set_illegal_callback(vrfy, counting_illegal_callback_fn, &ecount); + + memset(ones, 0xff, 32); + + secp256k1_rand256(session_id[0]); + secp256k1_rand256(session_id[1]); + secp256k1_rand256(sk[0]); + secp256k1_rand256(sk[1]); + secp256k1_rand256(msg); + secp256k1_rand256(sec_adaptor); + + CHECK(secp256k1_ec_pubkey_create(ctx, &pk[0], sk[0]) == 1); + CHECK(secp256k1_ec_pubkey_create(ctx, &pk[1], sk[1]) == 1); + CHECK(secp256k1_ec_pubkey_create(ctx, &adaptor, sec_adaptor) == 1); + + /** main test body **/ + + /* Key combination */ + ecount = 0; + CHECK(secp256k1_musig_pubkey_combine(none, scratch, &combined_pk, pk_hash, pk, 2) == 0); + CHECK(ecount == 1); + CHECK(secp256k1_musig_pubkey_combine(sign, scratch, &combined_pk, pk_hash, pk, 2) == 0); + CHECK(ecount == 2); + CHECK(secp256k1_musig_pubkey_combine(vrfy, scratch, &combined_pk, pk_hash, pk, 2) == 1); + CHECK(ecount == 2); + /* pubkey_combine does not require a scratch space */ + CHECK(secp256k1_musig_pubkey_combine(vrfy, NULL, &combined_pk, pk_hash, pk, 2) == 1); + CHECK(ecount == 2); + /* If a scratch space is given it shouldn't be too small */ + scratch_small = secp256k1_scratch_space_create(ctx, 1); + CHECK(secp256k1_musig_pubkey_combine(vrfy, scratch_small, &combined_pk, pk_hash, pk, 2) == 0); + secp256k1_scratch_space_destroy(scratch_small); + CHECK(ecount == 2); + CHECK(secp256k1_musig_pubkey_combine(vrfy, scratch, NULL, pk_hash, pk, 2) == 0); + CHECK(ecount == 3); + CHECK(secp256k1_musig_pubkey_combine(vrfy, scratch, &combined_pk, NULL, pk, 2) == 1); + CHECK(ecount == 3); + CHECK(secp256k1_musig_pubkey_combine(vrfy, scratch, &combined_pk, pk_hash, NULL, 2) == 0); + CHECK(ecount == 4); + CHECK(secp256k1_musig_pubkey_combine(vrfy, scratch, &combined_pk, pk_hash, pk, 0) == 0); + CHECK(ecount == 5); + CHECK(secp256k1_musig_pubkey_combine(vrfy, scratch, &combined_pk, pk_hash, NULL, 0) == 0); + CHECK(ecount == 6); + + CHECK(secp256k1_musig_pubkey_combine(vrfy, scratch, &combined_pk, pk_hash, pk, 2) == 1); + CHECK(secp256k1_musig_pubkey_combine(vrfy, scratch, &combined_pk, pk_hash, pk, 2) == 1); + CHECK(secp256k1_musig_pubkey_combine(vrfy, scratch, &combined_pk, pk_hash, pk, 2) == 1); + + /** Session creation **/ + ecount = 0; + CHECK(secp256k1_musig_session_initialize(none, &session[0], signer0, nonce_commitment[0], session_id[0], msg, &combined_pk, pk_hash, 2, 0, sk[0]) == 0); + CHECK(ecount == 1); + CHECK(secp256k1_musig_session_initialize(vrfy, &session[0], signer0, nonce_commitment[0], session_id[0], msg, &combined_pk, pk_hash, 2, 0, sk[0]) == 0); + CHECK(ecount == 2); + CHECK(secp256k1_musig_session_initialize(sign, &session[0], signer0, nonce_commitment[0], session_id[0], msg, &combined_pk, pk_hash, 2, 0, sk[0]) == 1); + CHECK(ecount == 2); + CHECK(secp256k1_musig_session_initialize(sign, NULL, signer0, nonce_commitment[0], session_id[0], msg, &combined_pk, pk_hash, 2, 0, sk[0]) == 0); + CHECK(ecount == 3); + CHECK(secp256k1_musig_session_initialize(sign, &session[0], NULL, nonce_commitment[0], session_id[0], msg, &combined_pk, pk_hash, 2, 0, sk[0]) == 0); + CHECK(ecount == 4); + CHECK(secp256k1_musig_session_initialize(sign, &session[0], signer0, NULL, session_id[0], msg, &combined_pk, pk_hash, 2, 0, sk[0]) == 0); + CHECK(ecount == 5); + CHECK(secp256k1_musig_session_initialize(sign, &session[0], signer0, nonce_commitment[0], NULL, msg, &combined_pk, pk_hash, 2, 0, sk[0]) == 0); + CHECK(ecount == 6); + CHECK(secp256k1_musig_session_initialize(sign, &session[0], signer0, nonce_commitment[0], session_id[0], NULL, &combined_pk, pk_hash, 2, 0, sk[0]) == 1); + CHECK(ecount == 6); + CHECK(secp256k1_musig_session_initialize(sign, &session[0], signer0, nonce_commitment[0], session_id[0], msg, NULL, pk_hash, 2, 0, sk[0]) == 0); + CHECK(ecount == 7); + CHECK(secp256k1_musig_session_initialize(sign, &session[0], signer0, nonce_commitment[0], session_id[0], msg, &combined_pk, NULL, 2, 0, sk[0]) == 0); + CHECK(ecount == 8); + CHECK(secp256k1_musig_session_initialize(sign, &session[0], signer0, nonce_commitment[0], session_id[0], msg, &combined_pk, pk_hash, 0, 0, sk[0]) == 0); + CHECK(ecount == 8); + /* If more than UINT32_MAX fits in a size_t, test that session_initialize + * rejects n_signers that high. */ + if (SIZE_MAX > UINT32_MAX) { + CHECK(secp256k1_musig_session_initialize(sign, &session[0], signer0, nonce_commitment[0], session_id[0], msg, &combined_pk, pk_hash, ((size_t) UINT32_MAX) + 2, 0, sk[0]) == 0); + } + CHECK(ecount == 8); + CHECK(secp256k1_musig_session_initialize(sign, &session[0], signer0, nonce_commitment[0], session_id[0], msg, &combined_pk, pk_hash, 2, 0, NULL) == 0); + CHECK(ecount == 9); + /* secret key overflows */ + CHECK(secp256k1_musig_session_initialize(sign, &session[0], signer0, nonce_commitment[0], session_id[0], msg, &combined_pk, pk_hash, 2, 0, ones) == 0); + CHECK(ecount == 9); + + + { + secp256k1_musig_session session_without_msg; + CHECK(secp256k1_musig_session_initialize(sign, &session_without_msg, signer0, nonce_commitment[0], session_id[0], NULL, &combined_pk, pk_hash, 2, 0, sk[0]) == 1); + CHECK(secp256k1_musig_session_set_msg(none, &session_without_msg, msg) == 1); + CHECK(secp256k1_musig_session_set_msg(none, &session_without_msg, msg) == 0); + } + CHECK(secp256k1_musig_session_initialize(sign, &session[0], signer0, nonce_commitment[0], session_id[0], msg, &combined_pk, pk_hash, 2, 0, sk[0]) == 1); + CHECK(secp256k1_musig_session_initialize(sign, &session[1], signer1, nonce_commitment[1], session_id[1], msg, &combined_pk, pk_hash, 2, 1, sk[1]) == 1); + ncs[0] = nonce_commitment[0]; + ncs[1] = nonce_commitment[1]; + + ecount = 0; + CHECK(secp256k1_musig_session_initialize_verifier(none, &verifier_session, verifier_signer_data, msg, &combined_pk, pk_hash, ncs, 2) == 1); + CHECK(ecount == 0); + CHECK(secp256k1_musig_session_initialize_verifier(none, NULL, verifier_signer_data, msg, &combined_pk, pk_hash, ncs, 2) == 0); + CHECK(ecount == 1); + CHECK(secp256k1_musig_session_initialize_verifier(none, &verifier_session, verifier_signer_data, NULL, &combined_pk, pk_hash, ncs, 2) == 1); + CHECK(ecount == 1); + CHECK(secp256k1_musig_session_initialize_verifier(none, &verifier_session, verifier_signer_data, msg, NULL, pk_hash, ncs, 2) == 0); + CHECK(ecount == 2); + CHECK(secp256k1_musig_session_initialize_verifier(none, &verifier_session, verifier_signer_data, msg, &combined_pk, NULL, ncs, 2) == 0); + CHECK(ecount == 3); + CHECK(secp256k1_musig_session_initialize_verifier(none, &verifier_session, verifier_signer_data, msg, &combined_pk, pk_hash, NULL, 2) == 0); + CHECK(ecount == 4); + CHECK(secp256k1_musig_session_initialize_verifier(none, &verifier_session, verifier_signer_data, msg, &combined_pk, pk_hash, ncs, 0) == 0); + CHECK(ecount == 4); + if (SIZE_MAX > UINT32_MAX) { + CHECK(secp256k1_musig_session_initialize_verifier(none, &verifier_session, verifier_signer_data, msg, &combined_pk, pk_hash, ncs, ((size_t) UINT32_MAX) + 2) == 0); + } + CHECK(ecount == 4); + CHECK(secp256k1_musig_session_initialize_verifier(none, &verifier_session, verifier_signer_data, msg, &combined_pk, pk_hash, ncs, 2) == 1); + + CHECK(secp256k1_musig_compute_messagehash(none, msghash, &verifier_session) == 0); + CHECK(secp256k1_musig_compute_messagehash(none, msghash, &session[0]) == 0); + + /** Signing step 0 -- exchange nonce commitments */ + ecount = 0; + { + secp256k1_pubkey nonce; + + /* Can obtain public nonce after commitments have been exchanged; still can't sign */ + CHECK(secp256k1_musig_session_get_public_nonce(none, &session[0], signer0, &nonce, ncs, 2) == 1); + CHECK(secp256k1_musig_partial_sign(none, &session[0], &partial_sig[0]) == 0); + CHECK(ecount == 0); + } + + /** Signing step 1 -- exchange nonces */ + ecount = 0; + { + secp256k1_pubkey public_nonce[3]; + + CHECK(secp256k1_musig_session_get_public_nonce(none, &session[0], signer0, &public_nonce[0], ncs, 2) == 1); + CHECK(ecount == 0); + CHECK(secp256k1_musig_session_get_public_nonce(none, NULL, signer0, &public_nonce[0], ncs, 2) == 0); + CHECK(ecount == 1); + CHECK(secp256k1_musig_session_get_public_nonce(none, &session[0], NULL, &public_nonce[0], ncs, 2) == 0); + CHECK(ecount == 2); + CHECK(secp256k1_musig_session_get_public_nonce(none, &session[0], signer0, NULL, ncs, 2) == 0); + CHECK(ecount == 3); + CHECK(secp256k1_musig_session_get_public_nonce(none, &session[0], signer0, &public_nonce[0], NULL, 2) == 0); + CHECK(ecount == 4); + /* Number of commitments and number of signers are different */ + CHECK(secp256k1_musig_session_get_public_nonce(none, &session[0], signer0, &public_nonce[0], ncs, 1) == 0); + CHECK(ecount == 4); + + CHECK(secp256k1_musig_session_get_public_nonce(none, &session[0], signer0, &public_nonce[0], ncs, 2) == 1); + CHECK(secp256k1_musig_session_get_public_nonce(none, &session[1], signer1, &public_nonce[1], ncs, 2) == 1); + + CHECK(secp256k1_musig_set_nonce(none, &signer0[0], &public_nonce[0]) == 1); + CHECK(secp256k1_musig_set_nonce(none, &signer0[1], &public_nonce[0]) == 0); + CHECK(secp256k1_musig_set_nonce(none, &signer0[1], &public_nonce[1]) == 1); + CHECK(secp256k1_musig_set_nonce(none, &signer0[1], &public_nonce[1]) == 1); + CHECK(ecount == 4); + + CHECK(secp256k1_musig_set_nonce(none, NULL, &public_nonce[0]) == 0); + CHECK(ecount == 5); + CHECK(secp256k1_musig_set_nonce(none, &signer1[0], NULL) == 0); + CHECK(ecount == 6); + + CHECK(secp256k1_musig_set_nonce(none, &signer1[0], &public_nonce[0]) == 1); + CHECK(secp256k1_musig_set_nonce(none, &signer1[1], &public_nonce[1]) == 1); + CHECK(secp256k1_musig_set_nonce(none, &verifier_signer_data[0], &public_nonce[0]) == 1); + CHECK(secp256k1_musig_set_nonce(none, &verifier_signer_data[1], &public_nonce[1]) == 1); + + ecount = 0; + CHECK(secp256k1_musig_session_combine_nonces(none, &session[0], signer0, 2, &nonce_is_negated, &adaptor) == 1); + CHECK(secp256k1_musig_session_combine_nonces(none, NULL, signer0, 2, &nonce_is_negated, &adaptor) == 0); + CHECK(ecount == 1); + CHECK(secp256k1_musig_session_combine_nonces(none, &session[0], NULL, 2, &nonce_is_negated, &adaptor) == 0); + CHECK(ecount == 2); + /* Number of signers differs from number during intialization */ + CHECK(secp256k1_musig_session_combine_nonces(none, &session[0], signer0, 1, &nonce_is_negated, &adaptor) == 0); + CHECK(ecount == 2); + CHECK(secp256k1_musig_session_combine_nonces(none, &session[0], signer0, 2, NULL, &adaptor) == 1); + CHECK(ecount == 2); + CHECK(secp256k1_musig_session_combine_nonces(none, &session[0], signer0, 2, &nonce_is_negated, NULL) == 1); + + CHECK(secp256k1_musig_session_combine_nonces(none, &session[0], signer0, 2, &nonce_is_negated, &adaptor) == 1); + CHECK(secp256k1_musig_session_combine_nonces(none, &session[1], signer0, 2, &nonce_is_negated, &adaptor) == 1); + CHECK(secp256k1_musig_session_combine_nonces(none, &verifier_session, verifier_signer_data, 2, &nonce_is_negated, &adaptor) == 1); + } + + /** Signing step 2 -- partial signatures */ + ecount = 0; + CHECK(secp256k1_musig_partial_sign(none, &session[0], &partial_sig[0]) == 1); + CHECK(ecount == 0); + CHECK(secp256k1_musig_partial_sign(none, NULL, &partial_sig[0]) == 0); + CHECK(ecount == 1); + CHECK(secp256k1_musig_partial_sign(none, &session[0], NULL) == 0); + CHECK(ecount == 2); + + CHECK(secp256k1_musig_partial_sign(none, &session[0], &partial_sig[0]) == 1); + CHECK(secp256k1_musig_partial_sign(none, &session[1], &partial_sig[1]) == 1); + /* observer can't sign */ + CHECK(secp256k1_musig_partial_sign(none, &verifier_session, &partial_sig[2]) == 0); + CHECK(ecount == 2); + + ecount = 0; + CHECK(secp256k1_musig_partial_signature_serialize(none, buf, &partial_sig[0]) == 1); + CHECK(secp256k1_musig_partial_signature_serialize(none, NULL, &partial_sig[0]) == 0); + CHECK(ecount == 1); + CHECK(secp256k1_musig_partial_signature_serialize(none, buf, NULL) == 0); + CHECK(ecount == 2); + CHECK(secp256k1_musig_partial_signature_parse(none, &partial_sig[0], buf) == 1); + CHECK(secp256k1_musig_partial_signature_parse(none, NULL, buf) == 0); + CHECK(ecount == 3); + CHECK(secp256k1_musig_partial_signature_parse(none, &partial_sig[0], NULL) == 0); + CHECK(ecount == 4); + CHECK(secp256k1_musig_partial_signature_parse(none, &partial_sig_overflow, ones) == 1); + + /** Partial signature verification */ + ecount = 0; + CHECK(secp256k1_musig_partial_sig_verify(none, &session[0], &signer0[0], &partial_sig[0], &pk[0]) == 0); + CHECK(ecount == 1); + CHECK(secp256k1_musig_partial_sig_verify(sign, &session[0], &signer0[0], &partial_sig[0], &pk[0]) == 0); + CHECK(ecount == 2); + CHECK(secp256k1_musig_partial_sig_verify(vrfy, &session[0], &signer0[0], &partial_sig[0], &pk[0]) == 1); + CHECK(ecount == 2); + CHECK(secp256k1_musig_partial_sig_verify(vrfy, &session[0], &signer0[0], &partial_sig[1], &pk[0]) == 0); + CHECK(ecount == 2); + CHECK(secp256k1_musig_partial_sig_verify(vrfy, NULL, &signer0[0], &partial_sig[0], &pk[0]) == 0); + CHECK(ecount == 3); + CHECK(secp256k1_musig_partial_sig_verify(vrfy, &session[0], NULL, &partial_sig[0], &pk[0]) == 0); + CHECK(ecount == 4); + CHECK(secp256k1_musig_partial_sig_verify(vrfy, &session[0], &signer0[0], NULL, &pk[0]) == 0); + CHECK(ecount == 5); + CHECK(secp256k1_musig_partial_sig_verify(vrfy, &session[0], &signer0[0], &partial_sig_overflow, &pk[0]) == 0); + CHECK(ecount == 5); + CHECK(secp256k1_musig_partial_sig_verify(vrfy, &session[0], &signer0[0], &partial_sig[0], NULL) == 0); + CHECK(ecount == 6); + + CHECK(secp256k1_musig_partial_sig_verify(vrfy, &session[0], &signer0[0], &partial_sig[0], &pk[0]) == 1); + CHECK(secp256k1_musig_partial_sig_verify(vrfy, &session[1], &signer1[0], &partial_sig[0], &pk[0]) == 1); + CHECK(secp256k1_musig_partial_sig_verify(vrfy, &session[0], &signer0[1], &partial_sig[1], &pk[1]) == 1); + CHECK(secp256k1_musig_partial_sig_verify(vrfy, &session[1], &signer1[1], &partial_sig[1], &pk[1]) == 1); + CHECK(secp256k1_musig_partial_sig_verify(vrfy, &verifier_session, &verifier_signer_data[0], &partial_sig[0], &pk[0]) == 1); + CHECK(secp256k1_musig_partial_sig_verify(vrfy, &verifier_session, &verifier_signer_data[1], &partial_sig[1], &pk[1]) == 1); + CHECK(ecount == 6); + + /** Adaptor signature verification */ + memcpy(&partial_sig_adapted[1], &partial_sig[1], sizeof(partial_sig_adapted[1])); + ecount = 0; + CHECK(secp256k1_musig_partial_sig_adapt(none, &partial_sig_adapted[0], &partial_sig[0], sec_adaptor, nonce_is_negated) == 1); + CHECK(secp256k1_musig_partial_sig_adapt(none, NULL, &partial_sig[0], sec_adaptor, 0) == 0); + CHECK(ecount == 1); + CHECK(secp256k1_musig_partial_sig_adapt(none, &partial_sig_adapted[0], NULL, sec_adaptor, 0) == 0); + CHECK(ecount == 2); + CHECK(secp256k1_musig_partial_sig_adapt(none, &partial_sig_adapted[0], &partial_sig_overflow, sec_adaptor, nonce_is_negated) == 0); + CHECK(ecount == 2); + CHECK(secp256k1_musig_partial_sig_adapt(none, &partial_sig_adapted[0], &partial_sig[0], NULL, 0) == 0); + CHECK(ecount == 3); + CHECK(secp256k1_musig_partial_sig_adapt(none, &partial_sig_adapted[0], &partial_sig[0], ones, nonce_is_negated) == 0); + CHECK(ecount == 3); + + /** Signing combining and verification */ + ecount = 0; + CHECK(secp256k1_musig_partial_sig_combine(none, &session[0], &final_sig, partial_sig_adapted, 2) == 1); + CHECK(secp256k1_musig_partial_sig_combine(none, &session[0], &final_sig_cmp, partial_sig_adapted, 2) == 1); + CHECK(memcmp(&final_sig, &final_sig_cmp, sizeof(final_sig)) == 0); + CHECK(secp256k1_musig_partial_sig_combine(none, &session[0], &final_sig_cmp, partial_sig_adapted, 2) == 1); + CHECK(memcmp(&final_sig, &final_sig_cmp, sizeof(final_sig)) == 0); + + CHECK(secp256k1_musig_partial_sig_combine(none, NULL, &final_sig, partial_sig_adapted, 2) == 0); + CHECK(ecount == 1); + CHECK(secp256k1_musig_partial_sig_combine(none, &session[0], NULL, partial_sig_adapted, 2) == 0); + CHECK(ecount == 2); + CHECK(secp256k1_musig_partial_sig_combine(none, &session[0], &final_sig, NULL, 2) == 0); + CHECK(ecount == 3); + { + secp256k1_musig_partial_signature partial_sig_tmp[2]; + partial_sig_tmp[0] = partial_sig_adapted[0]; + partial_sig_tmp[1] = partial_sig_overflow; + CHECK(secp256k1_musig_partial_sig_combine(none, &session[0], &final_sig, partial_sig_tmp, 2) == 0); + } + CHECK(ecount == 3); + /* Wrong number of partial sigs */ + CHECK(secp256k1_musig_partial_sig_combine(none, &session[0], &final_sig, partial_sig_adapted, 1) == 0); + CHECK(ecount == 3); + + CHECK(secp256k1_schnorrsig_verify(vrfy, &final_sig, msg, &combined_pk) == 1); + + /** Secret adaptor can be extracted from signature */ + ecount = 0; + CHECK(secp256k1_musig_extract_secret_adaptor(none, sec_adaptor1, &final_sig, partial_sig, 2, nonce_is_negated) == 1); + CHECK(memcmp(sec_adaptor, sec_adaptor1, 32) == 0); + CHECK(secp256k1_musig_extract_secret_adaptor(none, NULL, &final_sig, partial_sig, 2, 0) == 0); + CHECK(ecount == 1); + CHECK(secp256k1_musig_extract_secret_adaptor(none, sec_adaptor1, NULL, partial_sig, 2, 0) == 0); + CHECK(ecount == 2); + { + secp256k1_schnorrsig final_sig_tmp = final_sig; + memcpy(&final_sig_tmp.data[32], ones, 32); + CHECK(secp256k1_musig_extract_secret_adaptor(none, sec_adaptor1, &final_sig_tmp, partial_sig, 2, nonce_is_negated) == 0); + } + CHECK(ecount == 2); + CHECK(secp256k1_musig_extract_secret_adaptor(none, sec_adaptor1, &final_sig, NULL, 2, 0) == 0); + CHECK(ecount == 3); + { + secp256k1_musig_partial_signature partial_sig_tmp[2]; + partial_sig_tmp[0] = partial_sig[0]; + partial_sig_tmp[1] = partial_sig_overflow; + CHECK(secp256k1_musig_extract_secret_adaptor(none, sec_adaptor1, &final_sig, partial_sig_tmp, 2, nonce_is_negated) == 0); + } + CHECK(ecount == 3); + CHECK(secp256k1_musig_extract_secret_adaptor(none, sec_adaptor1, &final_sig, partial_sig, 0, 0) == 1); + CHECK(secp256k1_musig_extract_secret_adaptor(none, sec_adaptor1, &final_sig, partial_sig, 2, 1) == 1); + + /** cleanup **/ + memset(&session, 0, sizeof(session)); + secp256k1_context_destroy(none); + secp256k1_context_destroy(sign); + secp256k1_context_destroy(vrfy); +} + +/* Initializes two sessions, one use the given parameters (session_id, + * nonce_commitments, etc.) except that `session_tmp` uses new signers with different + * public keys. The point of this test is to call `musig_session_get_public_nonce` + * with signers from `session_tmp` who have different public keys than the correct + * ones and return the resulting messagehash. This should not result in a different + * messagehash because the public keys of the signers are only used during session + * initialization. */ +int musig_state_machine_diff_signer_msghash_test(unsigned char *msghash, secp256k1_pubkey *pks, secp256k1_pubkey *combined_pk, unsigned char *pk_hash, const unsigned char * const *nonce_commitments, unsigned char *msg, secp256k1_pubkey *nonce_other, unsigned char *sk, unsigned char *session_id) { + secp256k1_musig_session session; + secp256k1_musig_session session_tmp; + unsigned char nonce_commitment[32]; + secp256k1_musig_session_signer_data signers[2]; + secp256k1_musig_session_signer_data signers_tmp[2]; + unsigned char sk_dummy[32]; + secp256k1_pubkey pks_tmp[2]; + secp256k1_pubkey combined_pk_tmp; + unsigned char pk_hash_tmp[32]; + secp256k1_pubkey nonce; + + /* Set up signers with different public keys */ + secp256k1_rand256(sk_dummy); + pks_tmp[0] = pks[0]; + CHECK(secp256k1_ec_pubkey_create(ctx, &pks_tmp[1], sk_dummy) == 1); + CHECK(secp256k1_musig_pubkey_combine(ctx, NULL, &combined_pk_tmp, pk_hash_tmp, pks_tmp, 2) == 1); + CHECK(secp256k1_musig_session_initialize(ctx, &session_tmp, signers_tmp, nonce_commitment, session_id, msg, &combined_pk_tmp, pk_hash_tmp, 2, 0, sk_dummy) == 1); + + CHECK(secp256k1_musig_session_initialize(ctx, &session, signers, nonce_commitment, session_id, msg, combined_pk, pk_hash, 2, 0, sk) == 1); + CHECK(memcmp(nonce_commitment, nonce_commitments[1], 32) == 0); + /* Call get_public_nonce with different signers than the signers the session was + * initialized with. */ + CHECK(secp256k1_musig_session_get_public_nonce(ctx, &session_tmp, signers, &nonce, nonce_commitments, 2) == 1); + CHECK(secp256k1_musig_session_get_public_nonce(ctx, &session, signers_tmp, &nonce, nonce_commitments, 2) == 1); + CHECK(secp256k1_musig_set_nonce(ctx, &signers[0], nonce_other) == 1); + CHECK(secp256k1_musig_set_nonce(ctx, &signers[1], &nonce) == 1); + CHECK(secp256k1_musig_session_combine_nonces(ctx, &session, signers, 2, NULL, NULL) == 1); + + return secp256k1_musig_compute_messagehash(ctx, msghash, &session); +} + +/* Creates a new session (with a different session id) and tries to use that session + * to combine nonces with given signers_other. This should fail, because the nonce + * commitments of signers_other do not match the nonce commitments the new session + * was initialized with. If do_test is 0, the correct signers are being used and + * therefore the function should return 1. */ +int musig_state_machine_diff_signers_combine_nonce_test(secp256k1_pubkey *combined_pk, unsigned char *pk_hash, unsigned char *nonce_commitment_other, secp256k1_pubkey *nonce_other, unsigned char *msg, unsigned char *sk, secp256k1_musig_session_signer_data *signers_other, int do_test) { + secp256k1_musig_session session; + secp256k1_musig_session_signer_data signers[2]; + secp256k1_musig_session_signer_data *signers_to_use; + unsigned char nonce_commitment[32]; + unsigned char session_id[32]; + secp256k1_pubkey nonce; + const unsigned char *ncs[2]; + + /* Initialize new signers */ + secp256k1_rand256(session_id); + CHECK(secp256k1_musig_session_initialize(ctx, &session, signers, nonce_commitment, session_id, msg, combined_pk, pk_hash, 2, 1, sk) == 1); + ncs[0] = nonce_commitment_other; + ncs[1] = nonce_commitment; + CHECK(secp256k1_musig_session_get_public_nonce(ctx, &session, signers, &nonce, ncs, 2) == 1); + CHECK(secp256k1_musig_set_nonce(ctx, &signers[0], nonce_other) == 1); + CHECK(secp256k1_musig_set_nonce(ctx, &signers[1], &nonce) == 1); + CHECK(secp256k1_musig_set_nonce(ctx, &signers[1], &nonce) == 1); + secp256k1_musig_session_combine_nonces(ctx, &session, signers_other, 2, NULL, NULL); + if (do_test) { + signers_to_use = signers_other; + } else { + signers_to_use = signers; + } + return secp256k1_musig_session_combine_nonces(ctx, &session, signers_to_use, 2, NULL, NULL); +} + +/* Recreates a session with the given session_id, signers, pk, msg etc. parameters + * and tries to sign and verify the other signers partial signature. Both should fail + * if msg is NULL. */ +int musig_state_machine_missing_msg_test(secp256k1_pubkey *pks, secp256k1_pubkey *combined_pk, unsigned char *pk_hash, unsigned char *nonce_commitment_other, secp256k1_pubkey *nonce_other, secp256k1_musig_partial_signature *partial_sig_other, unsigned char *sk, unsigned char *session_id, unsigned char *msg) { + secp256k1_musig_session session; + secp256k1_musig_session_signer_data signers[2]; + unsigned char nonce_commitment[32]; + const unsigned char *ncs[2]; + secp256k1_pubkey nonce; + secp256k1_musig_partial_signature partial_sig; + int partial_sign, partial_verify; + + CHECK(secp256k1_musig_session_initialize(ctx, &session, signers, nonce_commitment, session_id, msg, combined_pk, pk_hash, 2, 0, sk) == 1); + ncs[0] = nonce_commitment_other; + ncs[1] = nonce_commitment; + CHECK(secp256k1_musig_session_get_public_nonce(ctx, &session, signers, &nonce, ncs, 2) == 1); + CHECK(secp256k1_musig_set_nonce(ctx, &signers[0], nonce_other) == 1); + CHECK(secp256k1_musig_set_nonce(ctx, &signers[1], &nonce) == 1); + + CHECK(secp256k1_musig_session_combine_nonces(ctx, &session, signers, 2, NULL, NULL) == 1); + partial_sign = secp256k1_musig_partial_sign(ctx, &session, &partial_sig); + partial_verify = secp256k1_musig_partial_sig_verify(ctx, &session, &signers[0], partial_sig_other, &pks[0]); + if (msg != NULL) { + /* Return 1 if both succeeded */ + return partial_sign && partial_verify; + } + /* Return 0 if both failed */ + return partial_sign || partial_verify; +} + +/* Recreates a session with the given session_id, signers, pk, msg etc. parameters + * and tries to verify and combine partial sigs. If do_combine is 0, the + * combine_nonces step is left out. In that case verify and combine should fail and + * this function should return 0. */ +int musig_state_machine_missing_combine_test(secp256k1_pubkey *pks, secp256k1_pubkey *combined_pk, unsigned char *pk_hash, unsigned char *nonce_commitment_other, secp256k1_pubkey *nonce_other, secp256k1_musig_partial_signature *partial_sig_other, unsigned char *msg, unsigned char *sk, unsigned char *session_id, secp256k1_musig_partial_signature *partial_sig, int do_combine) { + secp256k1_musig_session session; + secp256k1_musig_session_signer_data signers[2]; + unsigned char nonce_commitment[32]; + const unsigned char *ncs[2]; + secp256k1_pubkey nonce; + secp256k1_musig_partial_signature partial_sigs[2]; + secp256k1_schnorrsig sig; + int partial_verify, sig_combine; + + CHECK(secp256k1_musig_session_initialize(ctx, &session, signers, nonce_commitment, session_id, msg, combined_pk, pk_hash, 2, 0, sk) == 1); + ncs[0] = nonce_commitment_other; + ncs[1] = nonce_commitment; + CHECK(secp256k1_musig_session_get_public_nonce(ctx, &session, signers, &nonce, ncs, 2) == 1); + CHECK(secp256k1_musig_set_nonce(ctx, &signers[0], nonce_other) == 1); + CHECK(secp256k1_musig_set_nonce(ctx, &signers[1], &nonce) == 1); + + partial_sigs[0] = *partial_sig_other; + partial_sigs[1] = *partial_sig; + if (do_combine != 0) { + CHECK(secp256k1_musig_session_combine_nonces(ctx, &session, signers, 2, NULL, NULL) == 1); + } + partial_verify = secp256k1_musig_partial_sig_verify(ctx, &session, signers, partial_sig_other, &pks[0]); + sig_combine = secp256k1_musig_partial_sig_combine(ctx, &session, &sig, partial_sigs, 2); + if (do_combine != 0) { + /* Return 1 if both succeeded */ + return partial_verify && sig_combine; + } + /* Return 0 if both failed */ + return partial_verify || sig_combine; +} + +void musig_state_machine_tests(secp256k1_scratch_space *scratch) { + size_t i; + secp256k1_musig_session session[2]; + secp256k1_musig_session_signer_data signers0[2]; + secp256k1_musig_session_signer_data signers1[2]; + unsigned char nonce_commitment[2][32]; + unsigned char session_id[2][32]; + unsigned char msg[32]; + unsigned char sk[2][32]; + secp256k1_pubkey pk[2]; + secp256k1_pubkey combined_pk; + unsigned char pk_hash[32]; + secp256k1_pubkey nonce[2]; + const unsigned char *ncs[2]; + secp256k1_musig_partial_signature partial_sig[2]; + unsigned char msghash1[32]; + unsigned char msghash2[32]; + + /* Run state machine with the same objects twice to test that it's allowed to + * reinitialize session and session_signer_data. */ + for (i = 0; i < 2; i++) { + /* Setup */ + secp256k1_rand256(session_id[0]); + secp256k1_rand256(session_id[1]); + secp256k1_rand256(sk[0]); + secp256k1_rand256(sk[1]); + secp256k1_rand256(msg); + CHECK(secp256k1_ec_pubkey_create(ctx, &pk[0], sk[0]) == 1); + CHECK(secp256k1_ec_pubkey_create(ctx, &pk[1], sk[1]) == 1); + CHECK(secp256k1_musig_pubkey_combine(ctx, scratch, &combined_pk, pk_hash, pk, 2) == 1); + CHECK(secp256k1_musig_session_initialize(ctx, &session[0], signers0, nonce_commitment[0], session_id[0], msg, &combined_pk, pk_hash, 2, 0, sk[0]) == 1); + CHECK(secp256k1_musig_session_initialize(ctx, &session[1], signers1, nonce_commitment[1], session_id[1], msg, &combined_pk, pk_hash, 2, 1, sk[1]) == 1); + + /* Set nonce commitments */ + ncs[0] = nonce_commitment[0]; + ncs[1] = nonce_commitment[1]; + CHECK(secp256k1_musig_session_get_public_nonce(ctx, &session[0], signers0, &nonce[0], ncs, 2) == 1); + /* Changing a nonce commitment is not okay */ + ncs[1] = (unsigned char*) "this isn't a nonce commitment..."; + CHECK(secp256k1_musig_session_get_public_nonce(ctx, &session[0], signers0, &nonce[0], ncs, 2) == 0); + /* Repeating with the same nonce commitments is okay */ + ncs[1] = nonce_commitment[1]; + CHECK(secp256k1_musig_session_get_public_nonce(ctx, &session[0], signers0, &nonce[0], ncs, 2) == 1); + + /* Get nonce for signer 1 */ + CHECK(secp256k1_musig_session_get_public_nonce(ctx, &session[1], signers1, &nonce[1], ncs, 2) == 1); + + /* Set nonces */ + CHECK(secp256k1_musig_set_nonce(ctx, &signers0[0], &nonce[0]) == 1); + /* Can't set nonce that doesn't match nonce commitment */ + CHECK(secp256k1_musig_set_nonce(ctx, &signers0[1], &nonce[0]) == 0); + /* Set correct nonce */ + CHECK(secp256k1_musig_set_nonce(ctx, &signers0[1], &nonce[1]) == 1); + + /* Combine nonces */ + CHECK(secp256k1_musig_session_combine_nonces(ctx, &session[0], signers0, 2, NULL, NULL) == 1); + /* Not everyone is present from signer 1's view */ + CHECK(secp256k1_musig_session_combine_nonces(ctx, &session[1], signers1, 2, NULL, NULL) == 0); + /* Make everyone present */ + CHECK(secp256k1_musig_set_nonce(ctx, &signers1[0], &nonce[0]) == 1); + CHECK(secp256k1_musig_set_nonce(ctx, &signers1[1], &nonce[1]) == 1); + + /* Can't combine nonces from signers of a different session */ + CHECK(musig_state_machine_diff_signers_combine_nonce_test(&combined_pk, pk_hash, nonce_commitment[0], &nonce[0], msg, sk[1], signers1, 1) == 0); + CHECK(musig_state_machine_diff_signers_combine_nonce_test(&combined_pk, pk_hash, nonce_commitment[0], &nonce[0], msg, sk[1], signers1, 0) == 1); + + /* Partially sign */ + CHECK(secp256k1_musig_partial_sign(ctx, &session[0], &partial_sig[0]) == 1); + /* Can't verify or sign until nonce is combined */ + CHECK(secp256k1_musig_partial_sig_verify(ctx, &session[1], &signers1[0], &partial_sig[0], &pk[0]) == 0); + CHECK(secp256k1_musig_partial_sign(ctx, &session[1], &partial_sig[1]) == 0); + CHECK(secp256k1_musig_session_combine_nonces(ctx, &session[1], signers1, 2, NULL, NULL) == 1); + CHECK(secp256k1_musig_partial_sig_verify(ctx, &session[1], &signers1[0], &partial_sig[0], &pk[0]) == 1); + /* messagehash should be the same as a session whose get_public_nonce was called + * with different signers (i.e. they diff in public keys). This is because the + * public keys of the signers is set in stone when initializing the session. */ + CHECK(secp256k1_musig_compute_messagehash(ctx, msghash1, &session[1]) == 1); + CHECK(musig_state_machine_diff_signer_msghash_test(msghash2, pk, &combined_pk, pk_hash, ncs, msg, &nonce[0], sk[1], session_id[1]) == 1); + CHECK(memcmp(msghash1, msghash2, 32) == 0); + CHECK(secp256k1_musig_partial_sign(ctx, &session[1], &partial_sig[1]) == 1); + CHECK(secp256k1_musig_partial_sig_verify(ctx, &session[1], &signers1[1], &partial_sig[1], &pk[1]) == 1); + /* Wrong signature */ + CHECK(secp256k1_musig_partial_sig_verify(ctx, &session[1], &signers1[1], &partial_sig[0], &pk[1]) == 0); + /* Can't sign or verify until msg is set */ + CHECK(musig_state_machine_missing_msg_test(pk, &combined_pk, pk_hash, nonce_commitment[0], &nonce[0], &partial_sig[0], sk[1], session_id[1], NULL) == 0); + CHECK(musig_state_machine_missing_msg_test(pk, &combined_pk, pk_hash, nonce_commitment[0], &nonce[0], &partial_sig[0], sk[1], session_id[1], msg) == 1); + + /* Can't verify and combine partial sigs until nonces are combined */ + CHECK(musig_state_machine_missing_combine_test(pk, &combined_pk, pk_hash, nonce_commitment[0], &nonce[0], &partial_sig[0], msg, sk[1], session_id[1], &partial_sig[1], 0) == 0); + CHECK(musig_state_machine_missing_combine_test(pk, &combined_pk, pk_hash, nonce_commitment[0], &nonce[0], &partial_sig[0], msg, sk[1], session_id[1], &partial_sig[1], 1) == 1); + } +} + +void scriptless_atomic_swap(secp256k1_scratch_space *scratch) { + /* Throughout this test "a" and "b" refer to two hypothetical blockchains, + * while the indices 0 and 1 refer to the two signers. Here signer 0 is + * sending a-coins to signer 1, while signer 1 is sending b-coins to signer + * 0. Signer 0 produces the adaptor signatures. */ + secp256k1_schnorrsig final_sig_a; + secp256k1_schnorrsig final_sig_b; + secp256k1_musig_partial_signature partial_sig_a[2]; + secp256k1_musig_partial_signature partial_sig_b_adapted[2]; + secp256k1_musig_partial_signature partial_sig_b[2]; + unsigned char sec_adaptor[32]; + unsigned char sec_adaptor_extracted[32]; + secp256k1_pubkey pub_adaptor; + + unsigned char seckey_a[2][32]; + unsigned char seckey_b[2][32]; + secp256k1_pubkey pk_a[2]; + secp256k1_pubkey pk_b[2]; + unsigned char pk_hash_a[32]; + unsigned char pk_hash_b[32]; + secp256k1_pubkey combined_pk_a; + secp256k1_pubkey combined_pk_b; + secp256k1_musig_session musig_session_a[2]; + secp256k1_musig_session musig_session_b[2]; + unsigned char noncommit_a[2][32]; + unsigned char noncommit_b[2][32]; + const unsigned char *noncommit_a_ptr[2]; + const unsigned char *noncommit_b_ptr[2]; + secp256k1_pubkey pubnon_a[2]; + secp256k1_pubkey pubnon_b[2]; + int nonce_is_negated_a; + int nonce_is_negated_b; + secp256k1_musig_session_signer_data data_a[2]; + secp256k1_musig_session_signer_data data_b[2]; + + const unsigned char seed[32] = "still tired of choosing seeds..."; + const unsigned char msg32_a[32] = "this is the message blockchain a"; + const unsigned char msg32_b[32] = "this is the message blockchain b"; + + /* Step 1: key setup */ + secp256k1_rand256(seckey_a[0]); + secp256k1_rand256(seckey_a[1]); + secp256k1_rand256(seckey_b[0]); + secp256k1_rand256(seckey_b[1]); + secp256k1_rand256(sec_adaptor); + + CHECK(secp256k1_ec_pubkey_create(ctx, &pk_a[0], seckey_a[0])); + CHECK(secp256k1_ec_pubkey_create(ctx, &pk_a[1], seckey_a[1])); + CHECK(secp256k1_ec_pubkey_create(ctx, &pk_b[0], seckey_b[0])); + CHECK(secp256k1_ec_pubkey_create(ctx, &pk_b[1], seckey_b[1])); + CHECK(secp256k1_ec_pubkey_create(ctx, &pub_adaptor, sec_adaptor)); + + CHECK(secp256k1_musig_pubkey_combine(ctx, scratch, &combined_pk_a, pk_hash_a, pk_a, 2)); + CHECK(secp256k1_musig_pubkey_combine(ctx, scratch, &combined_pk_b, pk_hash_b, pk_b, 2)); + + CHECK(secp256k1_musig_session_initialize(ctx, &musig_session_a[0], data_a, noncommit_a[0], seed, msg32_a, &combined_pk_a, pk_hash_a, 2, 0, seckey_a[0])); + CHECK(secp256k1_musig_session_initialize(ctx, &musig_session_a[1], data_a, noncommit_a[1], seed, msg32_a, &combined_pk_a, pk_hash_a, 2, 1, seckey_a[1])); + noncommit_a_ptr[0] = noncommit_a[0]; + noncommit_a_ptr[1] = noncommit_a[1]; + + CHECK(secp256k1_musig_session_initialize(ctx, &musig_session_b[0], data_b, noncommit_b[0], seed, msg32_b, &combined_pk_b, pk_hash_b, 2, 0, seckey_b[0])); + CHECK(secp256k1_musig_session_initialize(ctx, &musig_session_b[1], data_b, noncommit_b[1], seed, msg32_b, &combined_pk_b, pk_hash_b, 2, 1, seckey_b[1])); + noncommit_b_ptr[0] = noncommit_b[0]; + noncommit_b_ptr[1] = noncommit_b[1]; + + /* Step 2: Exchange nonces */ + CHECK(secp256k1_musig_session_get_public_nonce(ctx, &musig_session_a[0], data_a, &pubnon_a[0], noncommit_a_ptr, 2)); + CHECK(secp256k1_musig_session_get_public_nonce(ctx, &musig_session_a[1], data_a, &pubnon_a[1], noncommit_a_ptr, 2)); + CHECK(secp256k1_musig_session_get_public_nonce(ctx, &musig_session_b[0], data_b, &pubnon_b[0], noncommit_b_ptr, 2)); + CHECK(secp256k1_musig_session_get_public_nonce(ctx, &musig_session_b[1], data_b, &pubnon_b[1], noncommit_b_ptr, 2)); + CHECK(secp256k1_musig_set_nonce(ctx, &data_a[0], &pubnon_a[0])); + CHECK(secp256k1_musig_set_nonce(ctx, &data_a[1], &pubnon_a[1])); + CHECK(secp256k1_musig_set_nonce(ctx, &data_b[0], &pubnon_b[0])); + CHECK(secp256k1_musig_set_nonce(ctx, &data_b[1], &pubnon_b[1])); + CHECK(secp256k1_musig_session_combine_nonces(ctx, &musig_session_a[0], data_a, 2, &nonce_is_negated_a, &pub_adaptor)); + CHECK(secp256k1_musig_session_combine_nonces(ctx, &musig_session_a[1], data_a, 2, NULL, &pub_adaptor)); + CHECK(secp256k1_musig_session_combine_nonces(ctx, &musig_session_b[0], data_b, 2, &nonce_is_negated_b, &pub_adaptor)); + CHECK(secp256k1_musig_session_combine_nonces(ctx, &musig_session_b[1], data_b, 2, NULL, &pub_adaptor)); + + /* Step 3: Signer 0 produces partial signatures for both chains. */ + CHECK(secp256k1_musig_partial_sign(ctx, &musig_session_a[0], &partial_sig_a[0])); + CHECK(secp256k1_musig_partial_sign(ctx, &musig_session_b[0], &partial_sig_b[0])); + + /* Step 4: Signer 1 receives partial signatures, verifies them and creates a + * partial signature to send B-coins to signer 0. */ + CHECK(secp256k1_musig_partial_sig_verify(ctx, &musig_session_a[1], data_a, &partial_sig_a[0], &pk_a[0]) == 1); + CHECK(secp256k1_musig_partial_sig_verify(ctx, &musig_session_b[1], data_b, &partial_sig_b[0], &pk_b[0]) == 1); + CHECK(secp256k1_musig_partial_sign(ctx, &musig_session_b[1], &partial_sig_b[1])); + + /* Step 5: Signer 0 adapts its own partial signature and combines it with the + * partial signature from signer 1. This results in a complete signature which + * is broadcasted by signer 0 to take B-coins. */ + CHECK(secp256k1_musig_partial_sig_adapt(ctx, &partial_sig_b_adapted[0], &partial_sig_b[0], sec_adaptor, nonce_is_negated_b)); + memcpy(&partial_sig_b_adapted[1], &partial_sig_b[1], sizeof(partial_sig_b_adapted[1])); + CHECK(secp256k1_musig_partial_sig_combine(ctx, &musig_session_b[0], &final_sig_b, partial_sig_b_adapted, 2) == 1); + CHECK(secp256k1_schnorrsig_verify(ctx, &final_sig_b, msg32_b, &combined_pk_b) == 1); + + /* Step 6: Signer 1 extracts adaptor from the published signature, applies it to + * other partial signature, and takes A-coins. */ + CHECK(secp256k1_musig_extract_secret_adaptor(ctx, sec_adaptor_extracted, &final_sig_b, partial_sig_b, 2, nonce_is_negated_b) == 1); + CHECK(memcmp(sec_adaptor_extracted, sec_adaptor, sizeof(sec_adaptor)) == 0); /* in real life we couldn't check this, of course */ + CHECK(secp256k1_musig_partial_sig_adapt(ctx, &partial_sig_a[0], &partial_sig_a[0], sec_adaptor_extracted, nonce_is_negated_a)); + CHECK(secp256k1_musig_partial_sign(ctx, &musig_session_a[1], &partial_sig_a[1])); + CHECK(secp256k1_musig_partial_sig_combine(ctx, &musig_session_a[1], &final_sig_a, partial_sig_a, 2) == 1); + CHECK(secp256k1_schnorrsig_verify(ctx, &final_sig_a, msg32_a, &combined_pk_a) == 1); +} + +/* Checks that hash initialized by secp256k1_musig_sha256_init_tagged has the + * expected state. */ +void sha256_tag_test(void) { + char tag[17] = "MuSig coefficient"; + secp256k1_sha256 sha; + secp256k1_sha256 sha_tagged; + unsigned char buf[32]; + unsigned char buf2[32]; + size_t i; + + secp256k1_sha256_initialize(&sha); + secp256k1_sha256_write(&sha, (unsigned char *) tag, 17); + secp256k1_sha256_finalize(&sha, buf); + /* buf = SHA256("MuSig coefficient") */ + + secp256k1_sha256_initialize(&sha); + secp256k1_sha256_write(&sha, buf, 32); + secp256k1_sha256_write(&sha, buf, 32); + /* Is buffer fully consumed? */ + CHECK((sha.bytes & 0x3F) == 0); + + /* Compare with tagged SHA */ + secp256k1_musig_sha256_init_tagged(&sha_tagged); + for (i = 0; i < 8; i++) { + CHECK(sha_tagged.s[i] == sha.s[i]); + } + secp256k1_sha256_write(&sha, buf, 32); + secp256k1_sha256_write(&sha_tagged, buf, 32); + secp256k1_sha256_finalize(&sha, buf); + secp256k1_sha256_finalize(&sha_tagged, buf2); + CHECK(memcmp(buf, buf2, 32) == 0); +} + +void run_musig_tests(void) { + int i; + secp256k1_scratch_space *scratch = secp256k1_scratch_space_create(ctx, 1024 * 1024); + + musig_api_tests(scratch); + musig_state_machine_tests(scratch); + for (i = 0; i < count; i++) { + /* Run multiple times to ensure that the nonce is negated in some tests */ + scriptless_atomic_swap(scratch); + } + sha256_tag_test(); + + secp256k1_scratch_space_destroy(scratch); +} + +#endif + diff --git a/src/secp256k1/src/modules/schnorrsig/Makefile.am.include b/src/secp256k1/src/modules/schnorrsig/Makefile.am.include new file mode 100644 index 000000000..0296c1299 --- /dev/null +++ b/src/secp256k1/src/modules/schnorrsig/Makefile.am.include @@ -0,0 +1,9 @@ +include_HEADERS += include/secp256k1_schnorrsig.h +noinst_HEADERS += src/modules/schnorrsig/main_impl.h +noinst_HEADERS += src/modules/schnorrsig/tests_impl.h +if USE_BENCHMARK +noinst_PROGRAMS += bench_schnorrsig +bench_schnorrsig_SOURCES = src/bench_schnorrsig.c +bench_schnorrsig_LDADD = libsecp256k1.la $(SECP_LIBS) $(COMMON_LIB) +endif + diff --git a/src/secp256k1/src/modules/schnorrsig/main_impl.h b/src/secp256k1/src/modules/schnorrsig/main_impl.h new file mode 100644 index 000000000..b366236d8 --- /dev/null +++ b/src/secp256k1/src/modules/schnorrsig/main_impl.h @@ -0,0 +1,339 @@ +/********************************************************************** + * Copyright (c) 2018 Andrew Poelstra * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef _SECP256K1_MODULE_SCHNORRSIG_MAIN_ +#define _SECP256K1_MODULE_SCHNORRSIG_MAIN_ + +#include "include/secp256k1.h" +#include "include/secp256k1_schnorrsig.h" +#include "hash.h" + +int secp256k1_schnorrsig_serialize(const secp256k1_context* ctx, unsigned char *out64, const secp256k1_schnorrsig* sig) { + (void) ctx; + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(out64 != NULL); + ARG_CHECK(sig != NULL); + memcpy(out64, sig->data, 64); + return 1; +} + +int secp256k1_schnorrsig_parse(const secp256k1_context* ctx, secp256k1_schnorrsig* sig, const unsigned char *in64) { + (void) ctx; + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(sig != NULL); + ARG_CHECK(in64 != NULL); + memcpy(sig->data, in64, 64); + return 1; +} + +int secp256k1_schnorrsig_sign(const secp256k1_context* ctx, secp256k1_schnorrsig *sig, int *nonce_is_negated, const unsigned char *msg32, const unsigned char *seckey, secp256k1_nonce_function noncefp, void *ndata) { + secp256k1_scalar x; + secp256k1_scalar e; + secp256k1_scalar k; + secp256k1_gej pkj; + secp256k1_gej rj; + secp256k1_ge pk; + secp256k1_ge r; + secp256k1_sha256 sha; + int overflow; + unsigned char buf[33]; + size_t buflen = sizeof(buf); + + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(secp256k1_ecmult_gen_context_is_built(&ctx->ecmult_gen_ctx)); + ARG_CHECK(sig != NULL); + ARG_CHECK(msg32 != NULL); + ARG_CHECK(seckey != NULL); + + if (noncefp == NULL) { + noncefp = secp256k1_nonce_function_bipschnorr; + } + secp256k1_scalar_set_b32(&x, seckey, &overflow); + /* Fail if the secret key is invalid. */ + if (overflow || secp256k1_scalar_is_zero(&x)) { + memset(sig, 0, sizeof(*sig)); + return 0; + } + + secp256k1_ecmult_gen(&ctx->ecmult_gen_ctx, &pkj, &x); + secp256k1_ge_set_gej(&pk, &pkj); + + if (!noncefp(buf, msg32, seckey, NULL, (void*)ndata, 0)) { + return 0; + } + secp256k1_scalar_set_b32(&k, buf, NULL); + if (secp256k1_scalar_is_zero(&k)) { + return 0; + } + + secp256k1_ecmult_gen(&ctx->ecmult_gen_ctx, &rj, &k); + secp256k1_ge_set_gej(&r, &rj); + + if (nonce_is_negated != NULL) { + *nonce_is_negated = 0; + } + if (!secp256k1_fe_is_quad_var(&r.y)) { + secp256k1_scalar_negate(&k, &k); + if (nonce_is_negated != NULL) { + *nonce_is_negated = 1; + } + } + secp256k1_fe_normalize(&r.x); + secp256k1_fe_get_b32(&sig->data[0], &r.x); + + secp256k1_sha256_initialize(&sha); + secp256k1_sha256_write(&sha, &sig->data[0], 32); + secp256k1_eckey_pubkey_serialize(&pk, buf, &buflen, 1); + secp256k1_sha256_write(&sha, buf, buflen); + secp256k1_sha256_write(&sha, msg32, 32); + secp256k1_sha256_finalize(&sha, buf); + + secp256k1_scalar_set_b32(&e, buf, NULL); + secp256k1_scalar_mul(&e, &e, &x); + secp256k1_scalar_add(&e, &e, &k); + + secp256k1_scalar_get_b32(&sig->data[32], &e); + secp256k1_scalar_clear(&k); + secp256k1_scalar_clear(&x); + + return 1; +} + +/* Helper function for verification and batch verification. + * Computes R = sG - eP. */ +static int secp256k1_schnorrsig_real_verify(const secp256k1_context* ctx, secp256k1_gej *rj, const secp256k1_scalar *s, const secp256k1_scalar *e, const secp256k1_pubkey *pk) { + secp256k1_scalar nege; + secp256k1_ge pkp; + secp256k1_gej pkj; + + secp256k1_scalar_negate(&nege, e); + + if (!secp256k1_pubkey_load(ctx, &pkp, pk)) { + return 0; + } + secp256k1_gej_set_ge(&pkj, &pkp); + + /* rj = s*G + (-e)*pkj */ + secp256k1_ecmult(&ctx->ecmult_ctx, rj, &pkj, &nege, s); + return 1; +} + +int secp256k1_schnorrsig_verify(const secp256k1_context* ctx, const secp256k1_schnorrsig *sig, const unsigned char *msg32, const secp256k1_pubkey *pk) { + secp256k1_scalar s; + secp256k1_scalar e; + secp256k1_gej rj; + secp256k1_fe rx; + secp256k1_sha256 sha; + unsigned char buf[33]; + size_t buflen = sizeof(buf); + int overflow; + + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(secp256k1_ecmult_context_is_built(&ctx->ecmult_ctx)); + ARG_CHECK(sig != NULL); + ARG_CHECK(msg32 != NULL); + ARG_CHECK(pk != NULL); + + if (!secp256k1_fe_set_b32(&rx, &sig->data[0])) { + return 0; + } + + secp256k1_scalar_set_b32(&s, &sig->data[32], &overflow); + if (overflow) { + return 0; + } + + secp256k1_sha256_initialize(&sha); + secp256k1_sha256_write(&sha, &sig->data[0], 32); + secp256k1_ec_pubkey_serialize(ctx, buf, &buflen, pk, SECP256K1_EC_COMPRESSED); + secp256k1_sha256_write(&sha, buf, buflen); + secp256k1_sha256_write(&sha, msg32, 32); + secp256k1_sha256_finalize(&sha, buf); + secp256k1_scalar_set_b32(&e, buf, NULL); + + if (!secp256k1_schnorrsig_real_verify(ctx, &rj, &s, &e, pk) + || !secp256k1_gej_has_quad_y_var(&rj) /* fails if rj is infinity */ + || !secp256k1_gej_eq_x_var(&rx, &rj)) { + return 0; + } + + return 1; +} + +/* Data that is used by the batch verification ecmult callback */ +typedef struct { + const secp256k1_context *ctx; + /* Seed for the random number generator */ + unsigned char chacha_seed[32]; + /* Caches randomizers generated by the PRNG which returns two randomizers per call. Caching + * avoids having to call the PRNG twice as often. The very first randomizer will be set to 1 and + * the PRNG is called at every odd indexed schnorrsig to fill the cache. */ + secp256k1_scalar randomizer_cache[2]; + /* Signature, message, public key tuples to verify */ + const secp256k1_schnorrsig *const *sig; + const unsigned char *const *msg32; + const secp256k1_pubkey *const *pk; + size_t n_sigs; +} secp256k1_schnorrsig_verify_ecmult_context; + +/* Callback function which is called by ecmult_multi in order to convert the ecmult_context + * consisting of signature, message and public key tuples into scalars and points. */ +static int secp256k1_schnorrsig_verify_batch_ecmult_callback(secp256k1_scalar *sc, secp256k1_ge *pt, size_t idx, void *data) { + secp256k1_schnorrsig_verify_ecmult_context *ecmult_context = (secp256k1_schnorrsig_verify_ecmult_context *) data; + + if (idx % 4 == 2) { + /* Every idx corresponds to a (scalar,point)-tuple. So this callback is called with 4 + * consecutive tuples before we need to call the RNG for new randomizers: + * (-randomizer_cache[0], R1) + * (-randomizer_cache[0]*e1, P1) + * (-randomizer_cache[1], R2) + * (-randomizer_cache[1]*e2, P2) */ + secp256k1_scalar_chacha20(&ecmult_context->randomizer_cache[0], &ecmult_context->randomizer_cache[1], ecmult_context->chacha_seed, idx / 4); + } + + /* R */ + if (idx % 2 == 0) { + secp256k1_fe rx; + *sc = ecmult_context->randomizer_cache[(idx / 2) % 2]; + if (!secp256k1_fe_set_b32(&rx, &ecmult_context->sig[idx / 2]->data[0])) { + return 0; + } + if (!secp256k1_ge_set_xquad(pt, &rx)) { + return 0; + } + /* eP */ + } else { + unsigned char buf[33]; + size_t buflen = sizeof(buf); + secp256k1_sha256 sha; + secp256k1_sha256_initialize(&sha); + secp256k1_sha256_write(&sha, &ecmult_context->sig[idx / 2]->data[0], 32); + secp256k1_ec_pubkey_serialize(ecmult_context->ctx, buf, &buflen, ecmult_context->pk[idx / 2], SECP256K1_EC_COMPRESSED); + secp256k1_sha256_write(&sha, buf, buflen); + secp256k1_sha256_write(&sha, ecmult_context->msg32[idx / 2], 32); + secp256k1_sha256_finalize(&sha, buf); + + secp256k1_scalar_set_b32(sc, buf, NULL); + secp256k1_scalar_mul(sc, sc, &ecmult_context->randomizer_cache[(idx / 2) % 2]); + + if (!secp256k1_pubkey_load(ecmult_context->ctx, pt, ecmult_context->pk[idx / 2])) { + return 0; + } + } + return 1; +} + +/** Helper function for batch verification. Hashes signature verification data into the + * randomization seed and initializes ecmult_context. + * + * Returns 1 if the randomizer was successfully initialized. + * + * Args: ctx: a secp256k1 context object + * Out: ecmult_context: context for batch_ecmult_callback + * In/Out sha: an initialized sha256 object which hashes the schnorrsig input in order to get a + * seed for the randomizer PRNG + * In: sig: array of signatures, or NULL if there are no signatures + * msg32: array of messages, or NULL if there are no signatures + * pk: array of public keys, or NULL if there are no signatures + * n_sigs: number of signatures in above arrays (must be 0 if they are NULL) + */ +int secp256k1_schnorrsig_verify_batch_init_randomizer(const secp256k1_context *ctx, secp256k1_schnorrsig_verify_ecmult_context *ecmult_context, secp256k1_sha256 *sha, const secp256k1_schnorrsig *const *sig, const unsigned char *const *msg32, const secp256k1_pubkey *const *pk, size_t n_sigs) { + size_t i; + + if (n_sigs > 0) { + ARG_CHECK(sig != NULL); + ARG_CHECK(msg32 != NULL); + ARG_CHECK(pk != NULL); + } + + for (i = 0; i < n_sigs; i++) { + unsigned char buf[33]; + size_t buflen = sizeof(buf); + secp256k1_sha256_write(sha, sig[i]->data, 64); + secp256k1_sha256_write(sha, msg32[i], 32); + secp256k1_ec_pubkey_serialize(ctx, buf, &buflen, pk[i], SECP256K1_EC_COMPRESSED); + secp256k1_sha256_write(sha, buf, 32); + } + ecmult_context->ctx = ctx; + ecmult_context->sig = sig; + ecmult_context->msg32 = msg32; + ecmult_context->pk = pk; + ecmult_context->n_sigs = n_sigs; + + return 1; +} + +/** Helper function for batch verification. Sums the s part of all signatures multiplied by their + * randomizer. + * + * Returns 1 if s is successfully summed. + * + * In/Out: s: the s part of the input sigs is added to this s argument + * In: chacha_seed: PRNG seed for computing randomizers + * sig: array of signatures, or NULL if there are no signatures + * n_sigs: number of signatures in above array (must be 0 if they are NULL) + */ +int secp256k1_schnorrsig_verify_batch_sum_s(secp256k1_scalar *s, unsigned char *chacha_seed, const secp256k1_schnorrsig *const *sig, size_t n_sigs) { + secp256k1_scalar randomizer_cache[2]; + size_t i; + + secp256k1_scalar_set_int(&randomizer_cache[0], 1); + for (i = 0; i < n_sigs; i++) { + int overflow; + secp256k1_scalar term; + if (i % 2 == 1) { + secp256k1_scalar_chacha20(&randomizer_cache[0], &randomizer_cache[1], chacha_seed, i / 2); + } + + secp256k1_scalar_set_b32(&term, &sig[i]->data[32], &overflow); + if (overflow) { + return 0; + } + secp256k1_scalar_mul(&term, &term, &randomizer_cache[i % 2]); + secp256k1_scalar_add(s, s, &term); + } + return 1; +} + +/* schnorrsig batch verification. + * Seeds a random number generator with the inputs and derives a random number ai for every + * signature i. Fails if y-coordinate of any R is not a quadratic residue or if + * 0 != -(s1 + a2*s2 + ... + au*su)G + R1 + a2*R2 + ... + au*Ru + e1*P1 + (a2*e2)P2 + ... + (au*eu)Pu. */ +int secp256k1_schnorrsig_verify_batch(const secp256k1_context *ctx, secp256k1_scratch *scratch, const secp256k1_schnorrsig *const *sig, const unsigned char *const *msg32, const secp256k1_pubkey *const *pk, size_t n_sigs) { + secp256k1_schnorrsig_verify_ecmult_context ecmult_context; + secp256k1_sha256 sha; + secp256k1_scalar s; + secp256k1_gej rj; + + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(secp256k1_ecmult_context_is_built(&ctx->ecmult_ctx)); + ARG_CHECK(scratch != NULL); + /* Check that n_sigs is less than half of the maximum size_t value. This is necessary because + * the number of points given to ecmult_multi is 2*n_sigs. */ + ARG_CHECK(n_sigs <= SIZE_MAX / 2); + /* Check that n_sigs is less than 2^31 to ensure the same behavior of this function on 32-bit + * and 64-bit platforms. */ + ARG_CHECK(n_sigs < (size_t)(1 << 31)); + + secp256k1_sha256_initialize(&sha); + if (!secp256k1_schnorrsig_verify_batch_init_randomizer(ctx, &ecmult_context, &sha, sig, msg32, pk, n_sigs)) { + return 0; + } + secp256k1_sha256_finalize(&sha, ecmult_context.chacha_seed); + secp256k1_scalar_set_int(&ecmult_context.randomizer_cache[0], 1); + + secp256k1_scalar_clear(&s); + if (!secp256k1_schnorrsig_verify_batch_sum_s(&s, ecmult_context.chacha_seed, sig, n_sigs)) { + return 0; + } + secp256k1_scalar_negate(&s, &s); + + return secp256k1_ecmult_multi_var(&ctx->ecmult_ctx, scratch, &rj, &s, secp256k1_schnorrsig_verify_batch_ecmult_callback, (void *) &ecmult_context, 2 * n_sigs) + && secp256k1_gej_is_infinity(&rj); +} + +#endif + diff --git a/src/secp256k1/src/modules/schnorrsig/tests_impl.h b/src/secp256k1/src/modules/schnorrsig/tests_impl.h new file mode 100644 index 000000000..de84992a9 --- /dev/null +++ b/src/secp256k1/src/modules/schnorrsig/tests_impl.h @@ -0,0 +1,727 @@ +/********************************************************************** + * Copyright (c) 2018 Andrew Poelstra * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef _SECP256K1_MODULE_SCHNORRSIG_TESTS_ +#define _SECP256K1_MODULE_SCHNORRSIG_TESTS_ + +#include "secp256k1_schnorrsig.h" + +void test_schnorrsig_serialize(void) { + secp256k1_schnorrsig sig; + unsigned char in[64]; + unsigned char out[64]; + + memset(in, 0x12, 64); + CHECK(secp256k1_schnorrsig_parse(ctx, &sig, in)); + CHECK(secp256k1_schnorrsig_serialize(ctx, out, &sig)); + CHECK(memcmp(in, out, 64) == 0); +} + +void test_schnorrsig_api(secp256k1_scratch_space *scratch) { + unsigned char sk1[32]; + unsigned char sk2[32]; + unsigned char sk3[32]; + unsigned char msg[32]; + unsigned char sig64[64]; + secp256k1_pubkey pk[3]; + secp256k1_schnorrsig sig; + const secp256k1_schnorrsig *sigptr = &sig; + const unsigned char *msgptr = msg; + const secp256k1_pubkey *pkptr = &pk[0]; + int nonce_is_negated; + + /** setup **/ + secp256k1_context *none = secp256k1_context_create(SECP256K1_CONTEXT_NONE); + secp256k1_context *sign = secp256k1_context_create(SECP256K1_CONTEXT_SIGN); + secp256k1_context *vrfy = secp256k1_context_create(SECP256K1_CONTEXT_VERIFY); + secp256k1_context *both = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); + int ecount; + + secp256k1_context_set_error_callback(none, counting_illegal_callback_fn, &ecount); + secp256k1_context_set_error_callback(sign, counting_illegal_callback_fn, &ecount); + secp256k1_context_set_error_callback(vrfy, counting_illegal_callback_fn, &ecount); + secp256k1_context_set_error_callback(both, counting_illegal_callback_fn, &ecount); + secp256k1_context_set_illegal_callback(none, counting_illegal_callback_fn, &ecount); + secp256k1_context_set_illegal_callback(sign, counting_illegal_callback_fn, &ecount); + secp256k1_context_set_illegal_callback(vrfy, counting_illegal_callback_fn, &ecount); + secp256k1_context_set_illegal_callback(both, counting_illegal_callback_fn, &ecount); + + secp256k1_rand256(sk1); + secp256k1_rand256(sk2); + secp256k1_rand256(sk3); + secp256k1_rand256(msg); + CHECK(secp256k1_ec_pubkey_create(ctx, &pk[0], sk1) == 1); + CHECK(secp256k1_ec_pubkey_create(ctx, &pk[1], sk2) == 1); + CHECK(secp256k1_ec_pubkey_create(ctx, &pk[2], sk3) == 1); + + /** main test body **/ + ecount = 0; + CHECK(secp256k1_schnorrsig_sign(none, &sig, &nonce_is_negated, msg, sk1, NULL, NULL) == 0); + CHECK(ecount == 1); + CHECK(secp256k1_schnorrsig_sign(vrfy, &sig, &nonce_is_negated, msg, sk1, NULL, NULL) == 0); + CHECK(ecount == 2); + CHECK(secp256k1_schnorrsig_sign(sign, &sig, &nonce_is_negated, msg, sk1, NULL, NULL) == 1); + CHECK(ecount == 2); + CHECK(secp256k1_schnorrsig_sign(sign, NULL, &nonce_is_negated, msg, sk1, NULL, NULL) == 0); + CHECK(ecount == 3); + CHECK(secp256k1_schnorrsig_sign(sign, &sig, NULL, msg, sk1, NULL, NULL) == 1); + CHECK(ecount == 3); + CHECK(secp256k1_schnorrsig_sign(sign, &sig, &nonce_is_negated, NULL, sk1, NULL, NULL) == 0); + CHECK(ecount == 4); + CHECK(secp256k1_schnorrsig_sign(sign, &sig, &nonce_is_negated, msg, NULL, NULL, NULL) == 0); + CHECK(ecount == 5); + + ecount = 0; + CHECK(secp256k1_schnorrsig_serialize(none, sig64, &sig) == 1); + CHECK(ecount == 0); + CHECK(secp256k1_schnorrsig_serialize(none, NULL, &sig) == 0); + CHECK(ecount == 1); + CHECK(secp256k1_schnorrsig_serialize(none, sig64, NULL) == 0); + CHECK(ecount == 2); + CHECK(secp256k1_schnorrsig_parse(none, &sig, sig64) == 1); + CHECK(ecount == 2); + CHECK(secp256k1_schnorrsig_parse(none, NULL, sig64) == 0); + CHECK(ecount == 3); + CHECK(secp256k1_schnorrsig_parse(none, &sig, NULL) == 0); + CHECK(ecount == 4); + + ecount = 0; + CHECK(secp256k1_schnorrsig_verify(none, &sig, msg, &pk[0]) == 0); + CHECK(ecount == 1); + CHECK(secp256k1_schnorrsig_verify(sign, &sig, msg, &pk[0]) == 0); + CHECK(ecount == 2); + CHECK(secp256k1_schnorrsig_verify(vrfy, &sig, msg, &pk[0]) == 1); + CHECK(ecount == 2); + CHECK(secp256k1_schnorrsig_verify(vrfy, NULL, msg, &pk[0]) == 0); + CHECK(ecount == 3); + CHECK(secp256k1_schnorrsig_verify(vrfy, &sig, NULL, &pk[0]) == 0); + CHECK(ecount == 4); + CHECK(secp256k1_schnorrsig_verify(vrfy, &sig, msg, NULL) == 0); + CHECK(ecount == 5); + + ecount = 0; + CHECK(secp256k1_schnorrsig_verify_batch(none, scratch, &sigptr, &msgptr, &pkptr, 1) == 0); + CHECK(ecount == 1); + CHECK(secp256k1_schnorrsig_verify_batch(sign, scratch, &sigptr, &msgptr, &pkptr, 1) == 0); + CHECK(ecount == 2); + CHECK(secp256k1_schnorrsig_verify_batch(vrfy, scratch, &sigptr, &msgptr, &pkptr, 1) == 1); + CHECK(ecount == 2); + CHECK(secp256k1_schnorrsig_verify_batch(vrfy, scratch, NULL, NULL, NULL, 0) == 1); + CHECK(ecount == 2); + CHECK(secp256k1_schnorrsig_verify_batch(vrfy, scratch, NULL, &msgptr, &pkptr, 1) == 0); + CHECK(ecount == 3); + CHECK(secp256k1_schnorrsig_verify_batch(vrfy, scratch, &sigptr, NULL, &pkptr, 1) == 0); + CHECK(ecount == 4); + CHECK(secp256k1_schnorrsig_verify_batch(vrfy, scratch, &sigptr, &msgptr, NULL, 1) == 0); + CHECK(ecount == 5); + CHECK(secp256k1_schnorrsig_verify_batch(vrfy, scratch, &sigptr, &msgptr, &pkptr, (size_t)1 << (sizeof(size_t)*8-1)) == 0); + CHECK(ecount == 6); + CHECK(secp256k1_schnorrsig_verify_batch(vrfy, scratch, &sigptr, &msgptr, &pkptr, 1 << 31) == 0); + CHECK(ecount == 7); + + secp256k1_context_destroy(none); + secp256k1_context_destroy(sign); + secp256k1_context_destroy(vrfy); + secp256k1_context_destroy(both); +} + +/* Helper function for schnorrsig_bip_vectors + * Signs the message and checks that it's the same as expected_sig. */ +void test_schnorrsig_bip_vectors_check_signing(const unsigned char *sk, const unsigned char *pk_serialized, const unsigned char *msg, const unsigned char *expected_sig, const int expected_nonce_is_negated) { + secp256k1_schnorrsig sig; + unsigned char serialized_sig[64]; + secp256k1_pubkey pk; + int nonce_is_negated; + + CHECK(secp256k1_schnorrsig_sign(ctx, &sig, &nonce_is_negated, msg, sk, NULL, NULL)); + CHECK(nonce_is_negated == expected_nonce_is_negated); + CHECK(secp256k1_schnorrsig_serialize(ctx, serialized_sig, &sig)); + CHECK(memcmp(serialized_sig, expected_sig, 64) == 0); + + CHECK(secp256k1_ec_pubkey_parse(ctx, &pk, pk_serialized, 33)); + CHECK(secp256k1_schnorrsig_verify(ctx, &sig, msg, &pk)); +} + +/* Helper function for schnorrsig_bip_vectors + * Checks that both verify and verify_batch return the same value as expected. */ +void test_schnorrsig_bip_vectors_check_verify(secp256k1_scratch_space *scratch, const unsigned char *pk_serialized, const unsigned char *msg32, const unsigned char *sig_serialized, int expected) { + const unsigned char *msg_arr[1]; + const secp256k1_schnorrsig *sig_arr[1]; + const secp256k1_pubkey *pk_arr[1]; + secp256k1_pubkey pk; + secp256k1_schnorrsig sig; + + CHECK(secp256k1_ec_pubkey_parse(ctx, &pk, pk_serialized, 33)); + CHECK(secp256k1_schnorrsig_parse(ctx, &sig, sig_serialized)); + + sig_arr[0] = &sig; + msg_arr[0] = msg32; + pk_arr[0] = &pk; + + CHECK(expected == secp256k1_schnorrsig_verify(ctx, &sig, msg32, &pk)); + CHECK(expected == secp256k1_schnorrsig_verify_batch(ctx, scratch, sig_arr, msg_arr, pk_arr, 1)); +} + +/* Test vectors according to BIP-schnorr + * (https://github.com/sipa/bips/blob/7f6a73e53c8bbcf2d008ea0546f76433e22094a8/bip-schnorr/test-vectors.csv). + */ +void test_schnorrsig_bip_vectors(secp256k1_scratch_space *scratch) { + { + /* Test vector 1 */ + const unsigned char sk1[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 + }; + const unsigned char pk1[33] = { + 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 + }; + const unsigned char msg1[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, 0x00 + }; + const unsigned char sig1[64] = { + 0x78, 0x7A, 0x84, 0x8E, 0x71, 0x04, 0x3D, 0x28, + 0x0C, 0x50, 0x47, 0x0E, 0x8E, 0x15, 0x32, 0xB2, + 0xDD, 0x5D, 0x20, 0xEE, 0x91, 0x2A, 0x45, 0xDB, + 0xDD, 0x2B, 0xD1, 0xDF, 0xBF, 0x18, 0x7E, 0xF6, + 0x70, 0x31, 0xA9, 0x88, 0x31, 0x85, 0x9D, 0xC3, + 0x4D, 0xFF, 0xEE, 0xDD, 0xA8, 0x68, 0x31, 0x84, + 0x2C, 0xCD, 0x00, 0x79, 0xE1, 0xF9, 0x2A, 0xF1, + 0x77, 0xF7, 0xF2, 0x2C, 0xC1, 0xDC, 0xED, 0x05 + }; + test_schnorrsig_bip_vectors_check_signing(sk1, pk1, msg1, sig1, 1); + test_schnorrsig_bip_vectors_check_verify(scratch, pk1, msg1, sig1, 1); + } + { + /* Test vector 2 */ + const unsigned char sk2[32] = { + 0xB7, 0xE1, 0x51, 0x62, 0x8A, 0xED, 0x2A, 0x6A, + 0xBF, 0x71, 0x58, 0x80, 0x9C, 0xF4, 0xF3, 0xC7, + 0x62, 0xE7, 0x16, 0x0F, 0x38, 0xB4, 0xDA, 0x56, + 0xA7, 0x84, 0xD9, 0x04, 0x51, 0x90, 0xCF, 0xEF + }; + const unsigned char pk2[33] = { + 0x02, 0xDF, 0xF1, 0xD7, 0x7F, 0x2A, 0x67, 0x1C, + 0x5F, 0x36, 0x18, 0x37, 0x26, 0xDB, 0x23, 0x41, + 0xBE, 0x58, 0xFE, 0xAE, 0x1D, 0xA2, 0xDE, 0xCE, + 0xD8, 0x43, 0x24, 0x0F, 0x7B, 0x50, 0x2B, 0xA6, + 0x59 + }; + const unsigned char msg2[32] = { + 0x24, 0x3F, 0x6A, 0x88, 0x85, 0xA3, 0x08, 0xD3, + 0x13, 0x19, 0x8A, 0x2E, 0x03, 0x70, 0x73, 0x44, + 0xA4, 0x09, 0x38, 0x22, 0x29, 0x9F, 0x31, 0xD0, + 0x08, 0x2E, 0xFA, 0x98, 0xEC, 0x4E, 0x6C, 0x89 + }; + const unsigned char sig2[64] = { + 0x2A, 0x29, 0x8D, 0xAC, 0xAE, 0x57, 0x39, 0x5A, + 0x15, 0xD0, 0x79, 0x5D, 0xDB, 0xFD, 0x1D, 0xCB, + 0x56, 0x4D, 0xA8, 0x2B, 0x0F, 0x26, 0x9B, 0xC7, + 0x0A, 0x74, 0xF8, 0x22, 0x04, 0x29, 0xBA, 0x1D, + 0x1E, 0x51, 0xA2, 0x2C, 0xCE, 0xC3, 0x55, 0x99, + 0xB8, 0xF2, 0x66, 0x91, 0x22, 0x81, 0xF8, 0x36, + 0x5F, 0xFC, 0x2D, 0x03, 0x5A, 0x23, 0x04, 0x34, + 0xA1, 0xA6, 0x4D, 0xC5, 0x9F, 0x70, 0x13, 0xFD + }; + test_schnorrsig_bip_vectors_check_signing(sk2, pk2, msg2, sig2, 0); + test_schnorrsig_bip_vectors_check_verify(scratch, pk2, msg2, sig2, 1); + } + { + /* Test vector 3 */ + const unsigned char sk3[32] = { + 0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34, + 0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1, + 0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74, + 0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x14, 0xE5, 0xC7 + }; + const unsigned char pk3[33] = { + 0x03, 0xFA, 0xC2, 0x11, 0x4C, 0x2F, 0xBB, 0x09, + 0x15, 0x27, 0xEB, 0x7C, 0x64, 0xEC, 0xB1, 0x1F, + 0x80, 0x21, 0xCB, 0x45, 0xE8, 0xE7, 0x80, 0x9D, + 0x3C, 0x09, 0x38, 0xE4, 0xB8, 0xC0, 0xE5, 0xF8, + 0x4B + }; + const unsigned char msg3[32] = { + 0x5E, 0x2D, 0x58, 0xD8, 0xB3, 0xBC, 0xDF, 0x1A, + 0xBA, 0xDE, 0xC7, 0x82, 0x90, 0x54, 0xF9, 0x0D, + 0xDA, 0x98, 0x05, 0xAA, 0xB5, 0x6C, 0x77, 0x33, + 0x30, 0x24, 0xB9, 0xD0, 0xA5, 0x08, 0xB7, 0x5C + }; + const unsigned char sig3[64] = { + 0x00, 0xDA, 0x9B, 0x08, 0x17, 0x2A, 0x9B, 0x6F, + 0x04, 0x66, 0xA2, 0xDE, 0xFD, 0x81, 0x7F, 0x2D, + 0x7A, 0xB4, 0x37, 0xE0, 0xD2, 0x53, 0xCB, 0x53, + 0x95, 0xA9, 0x63, 0x86, 0x6B, 0x35, 0x74, 0xBE, + 0x00, 0x88, 0x03, 0x71, 0xD0, 0x17, 0x66, 0x93, + 0x5B, 0x92, 0xD2, 0xAB, 0x4C, 0xD5, 0xC8, 0xA2, + 0xA5, 0x83, 0x7E, 0xC5, 0x7F, 0xED, 0x76, 0x60, + 0x77, 0x3A, 0x05, 0xF0, 0xDE, 0x14, 0x23, 0x80 + }; + test_schnorrsig_bip_vectors_check_signing(sk3, pk3, msg3, sig3, 0); + test_schnorrsig_bip_vectors_check_verify(scratch, pk3, msg3, sig3, 1); + } + { + /* Test vector 4 */ + const unsigned char pk4[33] = { + 0x03, 0xDE, 0xFD, 0xEA, 0x4C, 0xDB, 0x67, 0x77, + 0x50, 0xA4, 0x20, 0xFE, 0xE8, 0x07, 0xEA, 0xCF, + 0x21, 0xEB, 0x98, 0x98, 0xAE, 0x79, 0xB9, 0x76, + 0x87, 0x66, 0xE4, 0xFA, 0xA0, 0x4A, 0x2D, 0x4A, + 0x34 + }; + const unsigned char msg4[32] = { + 0x4D, 0xF3, 0xC3, 0xF6, 0x8F, 0xCC, 0x83, 0xB2, + 0x7E, 0x9D, 0x42, 0xC9, 0x04, 0x31, 0xA7, 0x24, + 0x99, 0xF1, 0x78, 0x75, 0xC8, 0x1A, 0x59, 0x9B, + 0x56, 0x6C, 0x98, 0x89, 0xB9, 0x69, 0x67, 0x03 + }; + const unsigned char sig4[64] = { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x3B, 0x78, 0xCE, 0x56, 0x3F, + 0x89, 0xA0, 0xED, 0x94, 0x14, 0xF5, 0xAA, 0x28, + 0xAD, 0x0D, 0x96, 0xD6, 0x79, 0x5F, 0x9C, 0x63, + 0x02, 0xA8, 0xDC, 0x32, 0xE6, 0x4E, 0x86, 0xA3, + 0x33, 0xF2, 0x0E, 0xF5, 0x6E, 0xAC, 0x9B, 0xA3, + 0x0B, 0x72, 0x46, 0xD6, 0xD2, 0x5E, 0x22, 0xAD, + 0xB8, 0xC6, 0xBE, 0x1A, 0xEB, 0x08, 0xD4, 0x9D + }; + test_schnorrsig_bip_vectors_check_verify(scratch, pk4, msg4, sig4, 1); + } + { + /* Test vector 5 */ + const unsigned char pk5[33] = { + 0x03, 0x1B, 0x84, 0xC5, 0x56, 0x7B, 0x12, 0x64, + 0x40, 0x99, 0x5D, 0x3E, 0xD5, 0xAA, 0xBA, 0x05, + 0x65, 0xD7, 0x1E, 0x18, 0x34, 0x60, 0x48, 0x19, + 0xFF, 0x9C, 0x17, 0xF5, 0xE9, 0xD5, 0xDD, 0x07, + 0x8F + }; + const unsigned char msg5[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, 0x00 + }; + const unsigned char sig5[64] = { + 0x52, 0x81, 0x85, 0x79, 0xAC, 0xA5, 0x97, 0x67, + 0xE3, 0x29, 0x1D, 0x91, 0xB7, 0x6B, 0x63, 0x7B, + 0xEF, 0x06, 0x20, 0x83, 0x28, 0x49, 0x92, 0xF2, + 0xD9, 0x5F, 0x56, 0x4C, 0xA6, 0xCB, 0x4E, 0x35, + 0x30, 0xB1, 0xDA, 0x84, 0x9C, 0x8E, 0x83, 0x04, + 0xAD, 0xC0, 0xCF, 0xE8, 0x70, 0x66, 0x03, 0x34, + 0xB3, 0xCF, 0xC1, 0x8E, 0x82, 0x5E, 0xF1, 0xDB, + 0x34, 0xCF, 0xAE, 0x3D, 0xFC, 0x5D, 0x81, 0x87 + }; + test_schnorrsig_bip_vectors_check_verify(scratch, pk5, msg5, sig5, 1); + } + { + /* Test vector 6 */ + const unsigned char pk6[33] = { + 0x03, 0xFA, 0xC2, 0x11, 0x4C, 0x2F, 0xBB, 0x09, + 0x15, 0x27, 0xEB, 0x7C, 0x64, 0xEC, 0xB1, 0x1F, + 0x80, 0x21, 0xCB, 0x45, 0xE8, 0xE7, 0x80, 0x9D, + 0x3C, 0x09, 0x38, 0xE4, 0xB8, 0xC0, 0xE5, 0xF8, + 0x4B + }; + const unsigned char msg6[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 + }; + const unsigned char sig6[64] = { + 0x57, 0x0D, 0xD4, 0xCA, 0x83, 0xD4, 0xE6, 0x31, + 0x7B, 0x8E, 0xE6, 0xBA, 0xE8, 0x34, 0x67, 0xA1, + 0xBF, 0x41, 0x9D, 0x07, 0x67, 0x12, 0x2D, 0xE4, + 0x09, 0x39, 0x44, 0x14, 0xB0, 0x50, 0x80, 0xDC, + 0xE9, 0xEE, 0x5F, 0x23, 0x7C, 0xBD, 0x10, 0x8E, + 0xAB, 0xAE, 0x1E, 0x37, 0x75, 0x9A, 0xE4, 0x7F, + 0x8E, 0x42, 0x03, 0xDA, 0x35, 0x32, 0xEB, 0x28, + 0xDB, 0x86, 0x0F, 0x33, 0xD6, 0x2D, 0x49, 0xBD + }; + test_schnorrsig_bip_vectors_check_verify(scratch, pk6, msg6, sig6, 1); + } + { + /* Test vector 7 */ + const unsigned char pk7[33] = { + 0x03, 0xEE, 0xFD, 0xEA, 0x4C, 0xDB, 0x67, 0x77, + 0x50, 0xA4, 0x20, 0xFE, 0xE8, 0x07, 0xEA, 0xCF, + 0x21, 0xEB, 0x98, 0x98, 0xAE, 0x79, 0xB9, 0x76, + 0x87, 0x66, 0xE4, 0xFA, 0xA0, 0x4A, 0x2D, 0x4A, + 0x34 + }; + secp256k1_pubkey pk7_parsed; + /* No need to check the signature of the test vector as parsing the pubkey already fails */ + CHECK(!secp256k1_ec_pubkey_parse(ctx, &pk7_parsed, pk7, 33)); + } + { + /* Test vector 8 */ + const unsigned char pk8[33] = { + 0x02, 0xDF, 0xF1, 0xD7, 0x7F, 0x2A, 0x67, 0x1C, + 0x5F, 0x36, 0x18, 0x37, 0x26, 0xDB, 0x23, 0x41, + 0xBE, 0x58, 0xFE, 0xAE, 0x1D, 0xA2, 0xDE, 0xCE, + 0xD8, 0x43, 0x24, 0x0F, 0x7B, 0x50, 0x2B, 0xA6, + 0x59 + }; + const unsigned char msg8[32] = { + 0x24, 0x3F, 0x6A, 0x88, 0x85, 0xA3, 0x08, 0xD3, + 0x13, 0x19, 0x8A, 0x2E, 0x03, 0x70, 0x73, 0x44, + 0xA4, 0x09, 0x38, 0x22, 0x29, 0x9F, 0x31, 0xD0, + 0x08, 0x2E, 0xFA, 0x98, 0xEC, 0x4E, 0x6C, 0x89 + }; + const unsigned char sig8[64] = { + 0x2A, 0x29, 0x8D, 0xAC, 0xAE, 0x57, 0x39, 0x5A, + 0x15, 0xD0, 0x79, 0x5D, 0xDB, 0xFD, 0x1D, 0xCB, + 0x56, 0x4D, 0xA8, 0x2B, 0x0F, 0x26, 0x9B, 0xC7, + 0x0A, 0x74, 0xF8, 0x22, 0x04, 0x29, 0xBA, 0x1D, + 0xFA, 0x16, 0xAE, 0xE0, 0x66, 0x09, 0x28, 0x0A, + 0x19, 0xB6, 0x7A, 0x24, 0xE1, 0x97, 0x7E, 0x46, + 0x97, 0x71, 0x2B, 0x5F, 0xD2, 0x94, 0x39, 0x14, + 0xEC, 0xD5, 0xF7, 0x30, 0x90, 0x1B, 0x4A, 0xB7 + }; + test_schnorrsig_bip_vectors_check_verify(scratch, pk8, msg8, sig8, 0); + } + { + /* Test vector 9 */ + const unsigned char pk9[33] = { + 0x03, 0xFA, 0xC2, 0x11, 0x4C, 0x2F, 0xBB, 0x09, + 0x15, 0x27, 0xEB, 0x7C, 0x64, 0xEC, 0xB1, 0x1F, + 0x80, 0x21, 0xCB, 0x45, 0xE8, 0xE7, 0x80, 0x9D, + 0x3C, 0x09, 0x38, 0xE4, 0xB8, 0xC0, 0xE5, 0xF8, + 0x4B + }; + const unsigned char msg9[32] = { + 0x5E, 0x2D, 0x58, 0xD8, 0xB3, 0xBC, 0xDF, 0x1A, + 0xBA, 0xDE, 0xC7, 0x82, 0x90, 0x54, 0xF9, 0x0D, + 0xDA, 0x98, 0x05, 0xAA, 0xB5, 0x6C, 0x77, 0x33, + 0x30, 0x24, 0xB9, 0xD0, 0xA5, 0x08, 0xB7, 0x5C + }; + const unsigned char sig9[64] = { + 0x00, 0xDA, 0x9B, 0x08, 0x17, 0x2A, 0x9B, 0x6F, + 0x04, 0x66, 0xA2, 0xDE, 0xFD, 0x81, 0x7F, 0x2D, + 0x7A, 0xB4, 0x37, 0xE0, 0xD2, 0x53, 0xCB, 0x53, + 0x95, 0xA9, 0x63, 0x86, 0x6B, 0x35, 0x74, 0xBE, + 0xD0, 0x92, 0xF9, 0xD8, 0x60, 0xF1, 0x77, 0x6A, + 0x1F, 0x74, 0x12, 0xAD, 0x8A, 0x1E, 0xB5, 0x0D, + 0xAC, 0xCC, 0x22, 0x2B, 0xC8, 0xC0, 0xE2, 0x6B, + 0x20, 0x56, 0xDF, 0x2F, 0x27, 0x3E, 0xFD, 0xEC + }; + test_schnorrsig_bip_vectors_check_verify(scratch, pk9, msg9, sig9, 0); + } + { + /* Test vector 10 */ + const unsigned char pk10[33] = { + 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 + }; + const unsigned char msg10[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, 0x00 + }; + const unsigned char sig10[64] = { + 0x78, 0x7A, 0x84, 0x8E, 0x71, 0x04, 0x3D, 0x28, + 0x0C, 0x50, 0x47, 0x0E, 0x8E, 0x15, 0x32, 0xB2, + 0xDD, 0x5D, 0x20, 0xEE, 0x91, 0x2A, 0x45, 0xDB, + 0xDD, 0x2B, 0xD1, 0xDF, 0xBF, 0x18, 0x7E, 0xF6, + 0x8F, 0xCE, 0x56, 0x77, 0xCE, 0x7A, 0x62, 0x3C, + 0xB2, 0x00, 0x11, 0x22, 0x57, 0x97, 0xCE, 0x7A, + 0x8D, 0xE1, 0xDC, 0x6C, 0xCD, 0x4F, 0x75, 0x4A, + 0x47, 0xDA, 0x6C, 0x60, 0x0E, 0x59, 0x54, 0x3C + }; + test_schnorrsig_bip_vectors_check_verify(scratch, pk10, msg10, sig10, 0); + } + { + /* Test vector 11 */ + const unsigned char pk11[33] = { + 0x03, 0xDF, 0xF1, 0xD7, 0x7F, 0x2A, 0x67, 0x1C, + 0x5F, 0x36, 0x18, 0x37, 0x26, 0xDB, 0x23, 0x41, + 0xBE, 0x58, 0xFE, 0xAE, 0x1D, 0xA2, 0xDE, 0xCE, + 0xD8, 0x43, 0x24, 0x0F, 0x7B, 0x50, 0x2B, 0xA6, + 0x59 + }; + const unsigned char msg11[32] = { + 0x24, 0x3F, 0x6A, 0x88, 0x85, 0xA3, 0x08, 0xD3, + 0x13, 0x19, 0x8A, 0x2E, 0x03, 0x70, 0x73, 0x44, + 0xA4, 0x09, 0x38, 0x22, 0x29, 0x9F, 0x31, 0xD0, + 0x08, 0x2E, 0xFA, 0x98, 0xEC, 0x4E, 0x6C, 0x89 + }; + const unsigned char sig11[64] = { + 0x2A, 0x29, 0x8D, 0xAC, 0xAE, 0x57, 0x39, 0x5A, + 0x15, 0xD0, 0x79, 0x5D, 0xDB, 0xFD, 0x1D, 0xCB, + 0x56, 0x4D, 0xA8, 0x2B, 0x0F, 0x26, 0x9B, 0xC7, + 0x0A, 0x74, 0xF8, 0x22, 0x04, 0x29, 0xBA, 0x1D, + 0x1E, 0x51, 0xA2, 0x2C, 0xCE, 0xC3, 0x55, 0x99, + 0xB8, 0xF2, 0x66, 0x91, 0x22, 0x81, 0xF8, 0x36, + 0x5F, 0xFC, 0x2D, 0x03, 0x5A, 0x23, 0x04, 0x34, + 0xA1, 0xA6, 0x4D, 0xC5, 0x9F, 0x70, 0x13, 0xFD + }; + test_schnorrsig_bip_vectors_check_verify(scratch, pk11, msg11, sig11, 0); + } + { + /* Test vector 12 */ + const unsigned char pk12[33] = { + 0x02, 0xDF, 0xF1, 0xD7, 0x7F, 0x2A, 0x67, 0x1C, + 0x5F, 0x36, 0x18, 0x37, 0x26, 0xDB, 0x23, 0x41, + 0xBE, 0x58, 0xFE, 0xAE, 0x1D, 0xA2, 0xDE, 0xCE, + 0xD8, 0x43, 0x24, 0x0F, 0x7B, 0x50, 0x2B, 0xA6, + 0x59 + }; + const unsigned char msg12[32] = { + 0x24, 0x3F, 0x6A, 0x88, 0x85, 0xA3, 0x08, 0xD3, + 0x13, 0x19, 0x8A, 0x2E, 0x03, 0x70, 0x73, 0x44, + 0xA4, 0x09, 0x38, 0x22, 0x29, 0x9F, 0x31, 0xD0, + 0x08, 0x2E, 0xFA, 0x98, 0xEC, 0x4E, 0x6C, 0x89 + }; + const unsigned char sig12[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, 0x00, + 0x9E, 0x9D, 0x01, 0xAF, 0x98, 0x8B, 0x5C, 0xED, + 0xCE, 0x47, 0x22, 0x1B, 0xFA, 0x9B, 0x22, 0x27, + 0x21, 0xF3, 0xFA, 0x40, 0x89, 0x15, 0x44, 0x4A, + 0x4B, 0x48, 0x90, 0x21, 0xDB, 0x55, 0x77, 0x5F + }; + test_schnorrsig_bip_vectors_check_verify(scratch, pk12, msg12, sig12, 0); + } + { + /* Test vector 13 */ + const unsigned char pk13[33] = { + 0x02, 0xDF, 0xF1, 0xD7, 0x7F, 0x2A, 0x67, 0x1C, + 0x5F, 0x36, 0x18, 0x37, 0x26, 0xDB, 0x23, 0x41, + 0xBE, 0x58, 0xFE, 0xAE, 0x1D, 0xA2, 0xDE, 0xCE, + 0xD8, 0x43, 0x24, 0x0F, 0x7B, 0x50, 0x2B, 0xA6, + 0x59 + }; + const unsigned char msg13[32] = { + 0x24, 0x3F, 0x6A, 0x88, 0x85, 0xA3, 0x08, 0xD3, + 0x13, 0x19, 0x8A, 0x2E, 0x03, 0x70, 0x73, 0x44, + 0xA4, 0x09, 0x38, 0x22, 0x29, 0x9F, 0x31, 0xD0, + 0x08, 0x2E, 0xFA, 0x98, 0xEC, 0x4E, 0x6C, 0x89 + }; + const unsigned char sig13[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, + 0xD3, 0x7D, 0xDF, 0x02, 0x54, 0x35, 0x18, 0x36, + 0xD8, 0x4B, 0x1B, 0xD6, 0xA7, 0x95, 0xFD, 0x5D, + 0x52, 0x30, 0x48, 0xF2, 0x98, 0xC4, 0x21, 0x4D, + 0x18, 0x7F, 0xE4, 0x89, 0x29, 0x47, 0xF7, 0x28 + }; + test_schnorrsig_bip_vectors_check_verify(scratch, pk13, msg13, sig13, 0); + } + { + /* Test vector 14 */ + const unsigned char pk14[33] = { + 0x02, 0xDF, 0xF1, 0xD7, 0x7F, 0x2A, 0x67, 0x1C, + 0x5F, 0x36, 0x18, 0x37, 0x26, 0xDB, 0x23, 0x41, + 0xBE, 0x58, 0xFE, 0xAE, 0x1D, 0xA2, 0xDE, 0xCE, + 0xD8, 0x43, 0x24, 0x0F, 0x7B, 0x50, 0x2B, 0xA6, + 0x59 + }; + const unsigned char msg14[32] = { + 0x24, 0x3F, 0x6A, 0x88, 0x85, 0xA3, 0x08, 0xD3, + 0x14, 0x19, 0x8A, 0x2E, 0x03, 0x70, 0x73, 0x44, + 0xA4, 0x09, 0x38, 0x22, 0x29, 0x9F, 0x31, 0xD0, + 0x08, 0x2E, 0xFA, 0x98, 0xEC, 0x4E, 0x6C, 0x89 + }; + const unsigned char sig14[64] = { + 0x4A, 0x29, 0x8D, 0xAC, 0xAE, 0x57, 0x39, 0x5A, + 0x15, 0xD0, 0x79, 0x5D, 0xDB, 0xFD, 0x1D, 0xCB, + 0x56, 0x4D, 0xA8, 0x2B, 0x0F, 0x26, 0x9B, 0xC7, + 0x0A, 0x74, 0xF8, 0x22, 0x04, 0x29, 0xBA, 0x1D, + 0x1E, 0x51, 0xA2, 0x2C, 0xCE, 0xC3, 0x55, 0x99, + 0xB8, 0xF2, 0x66, 0x91, 0x22, 0x81, 0xF8, 0x36, + 0x5F, 0xFC, 0x2D, 0x03, 0x5A, 0x23, 0x04, 0x34, + 0xA1, 0xA6, 0x4D, 0xC5, 0x9F, 0x70, 0x13, 0xFD + }; + test_schnorrsig_bip_vectors_check_verify(scratch, pk14, msg14, sig14, 0); + } + { + /* Test vector 15 */ + const unsigned char pk15[33] = { + 0x02, 0xDF, 0xF1, 0xD7, 0x7F, 0x2A, 0x67, 0x1C, + 0x5F, 0x36, 0x18, 0x37, 0x26, 0xDB, 0x23, 0x41, + 0xBE, 0x58, 0xFE, 0xAE, 0x1D, 0xA2, 0xDE, 0xCE, + 0xD8, 0x43, 0x24, 0x0F, 0x7B, 0x50, 0x2B, 0xA6, + 0x59 + }; + const unsigned char msg15[32] = { + 0x24, 0x3F, 0x6A, 0x88, 0x85, 0xA3, 0x08, 0xD3, + 0x13, 0x19, 0x8A, 0x2E, 0x03, 0x70, 0x73, 0x44, + 0xA4, 0x09, 0x38, 0x22, 0x29, 0x9F, 0x31, 0xD0, + 0x08, 0x2E, 0xFA, 0x98, 0xEC, 0x4E, 0x6C, 0x89 + }; + const unsigned char sig15[64] = { + 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, 0xFC, 0x2F, + 0x1E, 0x51, 0xA2, 0x2C, 0xCE, 0xC3, 0x55, 0x99, + 0xB8, 0xF2, 0x66, 0x91, 0x22, 0x81, 0xF8, 0x36, + 0x5F, 0xFC, 0x2D, 0x03, 0x5A, 0x23, 0x04, 0x34, + 0xA1, 0xA6, 0x4D, 0xC5, 0x9F, 0x70, 0x13, 0xFD + }; + test_schnorrsig_bip_vectors_check_verify(scratch, pk15, msg15, sig15, 0); + } + { + /* Test vector 16 */ + const unsigned char pk16[33] = { + 0x02, 0xDF, 0xF1, 0xD7, 0x7F, 0x2A, 0x67, 0x1C, + 0x5F, 0x36, 0x18, 0x37, 0x26, 0xDB, 0x23, 0x41, + 0xBE, 0x58, 0xFE, 0xAE, 0x1D, 0xA2, 0xDE, 0xCE, + 0xD8, 0x43, 0x24, 0x0F, 0x7B, 0x50, 0x2B, 0xA6, + 0x59 + }; + const unsigned char msg16[32] = { + 0x24, 0x3F, 0x6A, 0x88, 0x85, 0xA3, 0x08, 0xD3, + 0x13, 0x19, 0x8A, 0x2E, 0x03, 0x70, 0x73, 0x44, + 0xA4, 0x09, 0x38, 0x22, 0x29, 0x9F, 0x31, 0xD0, + 0x08, 0x2E, 0xFA, 0x98, 0xEC, 0x4E, 0x6C, 0x89 + }; + const unsigned char sig16[64] = { + 0x2A, 0x29, 0x8D, 0xAC, 0xAE, 0x57, 0x39, 0x5A, + 0x15, 0xD0, 0x79, 0x5D, 0xDB, 0xFD, 0x1D, 0xCB, + 0x56, 0x4D, 0xA8, 0x2B, 0x0F, 0x26, 0x9B, 0xC7, + 0x0A, 0x74, 0xF8, 0x22, 0x04, 0x29, 0xBA, 0x1D, + 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 + }; + test_schnorrsig_bip_vectors_check_verify(scratch, pk16, msg16, sig16, 0); + } +} + +/* Nonce function that returns constant 0 */ +static int nonce_function_failing(unsigned char *nonce32, const unsigned char *msg32, const unsigned char *key32, const unsigned char *algo16, void *data, unsigned int counter) { + (void) msg32; + (void) key32; + (void) algo16; + (void) data; + (void) counter; + (void) nonce32; + return 0; +} + +/* Nonce function that sets nonce to 0 */ +static int nonce_function_0(unsigned char *nonce32, const unsigned char *msg32, const unsigned char *key32, const unsigned char *algo16, void *data, unsigned int counter) { + (void) msg32; + (void) key32; + (void) algo16; + (void) data; + (void) counter; + + memset(nonce32, 0, 32); + return 1; +} + +void test_schnorrsig_sign(void) { + unsigned char sk[32]; + const unsigned char msg[32] = "this is a msg for a schnorrsig.."; + secp256k1_schnorrsig sig; + + memset(sk, 23, sizeof(sk)); + CHECK(secp256k1_schnorrsig_sign(ctx, &sig, NULL, msg, sk, NULL, NULL) == 1); + + /* Overflowing secret key */ + memset(sk, 0xFF, sizeof(sk)); + CHECK(secp256k1_schnorrsig_sign(ctx, &sig, NULL, msg, sk, NULL, NULL) == 0); + memset(sk, 23, sizeof(sk)); + + CHECK(secp256k1_schnorrsig_sign(ctx, &sig, NULL, msg, sk, nonce_function_failing, NULL) == 0); + CHECK(secp256k1_schnorrsig_sign(ctx, &sig, NULL, msg, sk, nonce_function_0, NULL) == 0); +} + +#define N_SIGS 200 +/* Creates N_SIGS valid signatures and verifies them with verify and verify_batch. Then flips some + * bits and checks that verification now fails. */ +void test_schnorrsig_sign_verify(secp256k1_scratch_space *scratch) { + const unsigned char sk[32] = "shhhhhhhh! this key is a secret."; + unsigned char msg[N_SIGS][32]; + secp256k1_schnorrsig sig[N_SIGS]; + size_t i; + const secp256k1_schnorrsig *sig_arr[N_SIGS]; + const unsigned char *msg_arr[N_SIGS]; + const secp256k1_pubkey *pk_arr[N_SIGS]; + secp256k1_pubkey pk; + + CHECK(secp256k1_ec_pubkey_create(ctx, &pk, sk)); + + CHECK(secp256k1_schnorrsig_verify_batch(ctx, scratch, NULL, NULL, NULL, 0)); + + for (i = 0; i < N_SIGS; i++) { + secp256k1_rand256(msg[i]); + CHECK(secp256k1_schnorrsig_sign(ctx, &sig[i], NULL, msg[i], sk, NULL, NULL)); + CHECK(secp256k1_schnorrsig_verify(ctx, &sig[i], msg[i], &pk)); + sig_arr[i] = &sig[i]; + msg_arr[i] = msg[i]; + pk_arr[i] = &pk; + } + + CHECK(secp256k1_schnorrsig_verify_batch(ctx, scratch, sig_arr, msg_arr, pk_arr, 1)); + CHECK(secp256k1_schnorrsig_verify_batch(ctx, scratch, sig_arr, msg_arr, pk_arr, 2)); + CHECK(secp256k1_schnorrsig_verify_batch(ctx, scratch, sig_arr, msg_arr, pk_arr, 4)); + CHECK(secp256k1_schnorrsig_verify_batch(ctx, scratch, sig_arr, msg_arr, pk_arr, N_SIGS)); + + { + /* Flip a few bits in the signature and in the message and check that + * verify and verify_batch fail */ + size_t sig_idx = secp256k1_rand_int(4); + size_t byte_idx = secp256k1_rand_int(32); + unsigned char xorbyte = secp256k1_rand_int(254)+1; + sig[sig_idx].data[byte_idx] ^= xorbyte; + CHECK(!secp256k1_schnorrsig_verify(ctx, &sig[sig_idx], msg[sig_idx], &pk)); + CHECK(!secp256k1_schnorrsig_verify_batch(ctx, scratch, sig_arr, msg_arr, pk_arr, 4)); + sig[sig_idx].data[byte_idx] ^= xorbyte; + + byte_idx = secp256k1_rand_int(32); + sig[sig_idx].data[32+byte_idx] ^= xorbyte; + CHECK(!secp256k1_schnorrsig_verify(ctx, &sig[sig_idx], msg[sig_idx], &pk)); + CHECK(!secp256k1_schnorrsig_verify_batch(ctx, scratch, sig_arr, msg_arr, pk_arr, 4)); + sig[sig_idx].data[32+byte_idx] ^= xorbyte; + + byte_idx = secp256k1_rand_int(32); + msg[sig_idx][byte_idx] ^= xorbyte; + CHECK(!secp256k1_schnorrsig_verify(ctx, &sig[sig_idx], msg[sig_idx], &pk)); + CHECK(!secp256k1_schnorrsig_verify_batch(ctx, scratch, sig_arr, msg_arr, pk_arr, 4)); + msg[sig_idx][byte_idx] ^= xorbyte; + + /* Check that above bitflips have been reversed correctly */ + CHECK(secp256k1_schnorrsig_verify(ctx, &sig[sig_idx], msg[sig_idx], &pk)); + CHECK(secp256k1_schnorrsig_verify_batch(ctx, scratch, sig_arr, msg_arr, pk_arr, 4)); + } +} +#undef N_SIGS + +void run_schnorrsig_tests(void) { + secp256k1_scratch_space *scratch = secp256k1_scratch_space_create(ctx, 1024 * 1024); + + test_schnorrsig_serialize(); + test_schnorrsig_api(scratch); + test_schnorrsig_bip_vectors(scratch); + test_schnorrsig_sign(); + test_schnorrsig_sign_verify(scratch); + + secp256k1_scratch_space_destroy(scratch); +} + +#endif + diff --git a/src/secp256k1/src/scalar.h b/src/secp256k1/src/scalar.h index 59304cb66..3d972dc84 100644 --- a/src/secp256k1/src/scalar.h +++ b/src/secp256k1/src/scalar.h @@ -1,3 +1,5 @@ +#ifdef ENABLE_MODULE_MUSIG + /********************************************************************** * Copyright (c) 2014 Pieter Wuille * * Distributed under the MIT software license, see the accompanying * @@ -104,3 +106,236 @@ static void secp256k1_scalar_split_lambda(secp256k1_scalar *r1, secp256k1_scalar static void secp256k1_scalar_mul_shift_var(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b, unsigned int shift); #endif /* SECP256K1_SCALAR_H */ + +#else + +/********************************************************************** + * 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_H +#define SECP256K1_SCALAR_H + +#include "num.h" + +#if defined HAVE_CONFIG_H +#include "libsecp256k1-config.h" +#endif + +#if defined(EXHAUSTIVE_TEST_ORDER) +#include "scalar_low.h" +#elif 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 *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 *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 *a, unsigned int offset, unsigned int count); + +/** Set a scalar from a big endian byte array. */ +static void secp256k1_scalar_set_b32(secp256k1_scalar *r, const unsigned char *bin, int *overflow); + +/** Set a scalar to an unsigned integer. */ +static void secp256k1_scalar_set_int(secp256k1_scalar *r, unsigned int v); + +/** Set a scalar to an unsigned 64-bit integer */ +static void secp256k1_scalar_set_u64(secp256k1_scalar *r, uint64_t v); + +/** Convert a scalar to a byte array. */ +static void secp256k1_scalar_get_b32(unsigned char *bin, const secp256k1_scalar* a); + +/** Add two scalars together (modulo the group order). Returns whether it overflowed. */ +static int secp256k1_scalar_add(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b); + +/** Conditionally add a power of two to a scalar. The result is not allowed to overflow. */ +static void secp256k1_scalar_cadd_bit(secp256k1_scalar *r, unsigned int bit, int flag); + +/** Multiply two scalars (modulo the group order). */ +static void secp256k1_scalar_mul(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b); + +/** Shift a scalar right by some amount strictly between 0 and 16, returning + * the low bits that were shifted off */ +static int secp256k1_scalar_shr_int(secp256k1_scalar *r, int n); + +/** Compute the square of a scalar (modulo the group order). */ +static void secp256k1_scalar_sqr(secp256k1_scalar *r, const secp256k1_scalar *a); + +/** Compute the inverse of a scalar (modulo the group order). */ +static void secp256k1_scalar_inverse(secp256k1_scalar *r, const secp256k1_scalar *a); + +/** Compute the inverse of a scalar (modulo the group order), without constant-time guarantee. */ +static void secp256k1_scalar_inverse_var(secp256k1_scalar *r, const secp256k1_scalar *a); + +/** Compute the complement of a scalar (modulo the group order). */ +static void secp256k1_scalar_negate(secp256k1_scalar *r, const secp256k1_scalar *a); + +/** Check whether a scalar equals zero. */ +static int secp256k1_scalar_is_zero(const secp256k1_scalar *a); + +/** Check whether a scalar equals one. */ +static int secp256k1_scalar_is_one(const secp256k1_scalar *a); + +/** Check whether a scalar, considered as an nonnegative integer, is even. */ +static int secp256k1_scalar_is_even(const secp256k1_scalar *a); + +/** Check whether a scalar is higher than the group order divided by 2. */ +static int secp256k1_scalar_is_high(const secp256k1_scalar *a); + +/** Conditionally negate a number, in constant time. + * Returns -1 if the number was negated, 1 otherwise */ +static int secp256k1_scalar_cond_negate(secp256k1_scalar *a, int flag); + +#ifndef USE_NUM_NONE +/** Convert a scalar to a number. */ +static void secp256k1_scalar_get_num(secp256k1_num *r, const secp256k1_scalar *a); + +/** Get the order of the group as a number. */ +static void secp256k1_scalar_order_get_num(secp256k1_num *r); +#endif + +/** Compare two scalars. */ +static int secp256k1_scalar_eq(const secp256k1_scalar *a, const secp256k1_scalar *b); + +#ifdef USE_ENDOMORPHISM +/** Find r1 and r2 such that r1+r2*2^128 = a. */ +static void secp256k1_scalar_split_128(secp256k1_scalar *r1, secp256k1_scalar *r2, const secp256k1_scalar *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(secp256k1_scalar *r1, secp256k1_scalar *r2, const secp256k1_scalar *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 *r, const secp256k1_scalar *a, const secp256k1_scalar *b, unsigned int shift); + +/** Generate two scalars from a 32-byte seed and an integer using the chacha20 stream cipher */ +static void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx); + +#endif /* SECP256K1_SCALAR_H */ +#endif + +#else + +/********************************************************************** + * 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_H +#define SECP256K1_SCALAR_H + +#include "num.h" + +#if defined HAVE_CONFIG_H +#include "libsecp256k1-config.h" +#endif + +#if defined(EXHAUSTIVE_TEST_ORDER) +#include "scalar_low.h" +#elif 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 *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 *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 *a, unsigned int offset, unsigned int count); + +/** Set a scalar from a big endian byte array. */ +static void secp256k1_scalar_set_b32(secp256k1_scalar *r, const unsigned char *bin, int *overflow); + +/** Set a scalar to an unsigned integer. */ +static void secp256k1_scalar_set_int(secp256k1_scalar *r, unsigned int v); + +/** Set a scalar to an unsigned 64-bit integer */ +static void secp256k1_scalar_set_u64(secp256k1_scalar *r, uint64_t v); + +/** Convert a scalar to a byte array. */ +static void secp256k1_scalar_get_b32(unsigned char *bin, const secp256k1_scalar* a); + +/** Add two scalars together (modulo the group order). Returns whether it overflowed. */ +static int secp256k1_scalar_add(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b); + +/** Conditionally add a power of two to a scalar. The result is not allowed to overflow. */ +static void secp256k1_scalar_cadd_bit(secp256k1_scalar *r, unsigned int bit, int flag); + +/** Multiply two scalars (modulo the group order). */ +static void secp256k1_scalar_mul(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b); + +/** Shift a scalar right by some amount strictly between 0 and 16, returning + * the low bits that were shifted off */ +static int secp256k1_scalar_shr_int(secp256k1_scalar *r, int n); + +/** Compute the square of a scalar (modulo the group order). */ +static void secp256k1_scalar_sqr(secp256k1_scalar *r, const secp256k1_scalar *a); + +/** Compute the inverse of a scalar (modulo the group order). */ +static void secp256k1_scalar_inverse(secp256k1_scalar *r, const secp256k1_scalar *a); + +/** Compute the inverse of a scalar (modulo the group order), without constant-time guarantee. */ +static void secp256k1_scalar_inverse_var(secp256k1_scalar *r, const secp256k1_scalar *a); + +/** Compute the complement of a scalar (modulo the group order). */ +static void secp256k1_scalar_negate(secp256k1_scalar *r, const secp256k1_scalar *a); + +/** Check whether a scalar equals zero. */ +static int secp256k1_scalar_is_zero(const secp256k1_scalar *a); + +/** Check whether a scalar equals one. */ +static int secp256k1_scalar_is_one(const secp256k1_scalar *a); + +/** Check whether a scalar, considered as an nonnegative integer, is even. */ +static int secp256k1_scalar_is_even(const secp256k1_scalar *a); + +/** Check whether a scalar is higher than the group order divided by 2. */ +static int secp256k1_scalar_is_high(const secp256k1_scalar *a); + +/** Conditionally negate a number, in constant time. + * Returns -1 if the number was negated, 1 otherwise */ +static int secp256k1_scalar_cond_negate(secp256k1_scalar *a, int flag); + +#ifndef USE_NUM_NONE +/** Convert a scalar to a number. */ +static void secp256k1_scalar_get_num(secp256k1_num *r, const secp256k1_scalar *a); + +/** Get the order of the group as a number. */ +static void secp256k1_scalar_order_get_num(secp256k1_num *r); +#endif + +/** Compare two scalars. */ +static int secp256k1_scalar_eq(const secp256k1_scalar *a, const secp256k1_scalar *b); + +#ifdef USE_ENDOMORPHISM +/** Find r1 and r2 such that r1+r2*2^128 = a. */ +static void secp256k1_scalar_split_128(secp256k1_scalar *r1, secp256k1_scalar *r2, const secp256k1_scalar *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(secp256k1_scalar *r1, secp256k1_scalar *r2, const secp256k1_scalar *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 *r, const secp256k1_scalar *a, const secp256k1_scalar *b, unsigned int shift); + +/** Generate two scalars from a 32-byte seed and an integer using the chacha20 stream cipher */ +static void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx); + +#endif /* SECP256K1_SCALAR_H */ +#endif + diff --git a/src/secp256k1/src/scalar_4x64.h b/src/secp256k1/src/scalar_4x64.h index 19c7495d1..326afd6b5 100644 --- a/src/secp256k1/src/scalar_4x64.h +++ b/src/secp256k1/src/scalar_4x64.h @@ -1,3 +1,5 @@ +#ifdef ENABLE_MODULE_MUSIG + /********************************************************************** * Copyright (c) 2014 Pieter Wuille * * Distributed under the MIT software license, see the accompanying * @@ -17,3 +19,50 @@ typedef struct { #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 /* SECP256K1_SCALAR_REPR_H */ + +#else +/********************************************************************** + * 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_H +#define SECP256K1_SCALAR_REPR_H + +#include + +/** A scalar modulo the group order of the secp256k1 curve. */ +typedef struct { + uint64_t d[4]; +} secp256k1_scalar; + +#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 /* SECP256K1_SCALAR_REPR_H */ +#endif + + +#else +/********************************************************************** + * 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_H +#define SECP256K1_SCALAR_REPR_H + +#include + +/** A scalar modulo the group order of the secp256k1 curve. */ +typedef struct { + uint64_t d[4]; +} secp256k1_scalar; + +#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 /* SECP256K1_SCALAR_REPR_H */ +#endif + + diff --git a/src/secp256k1/src/scalar_4x64_impl.h b/src/secp256k1/src/scalar_4x64_impl.h index db1ebf94b..ee75ad51e 100644 --- a/src/secp256k1/src/scalar_4x64_impl.h +++ b/src/secp256k1/src/scalar_4x64_impl.h @@ -1,3 +1,5 @@ +#ifdef ENABLE_MODULE_MUSIG + /********************************************************************** * Copyright (c) 2013, 2014 Pieter Wuille * * Distributed under the MIT software license, see the accompanying * @@ -947,3 +949,1057 @@ SECP256K1_INLINE static void secp256k1_scalar_mul_shift_var(secp256k1_scalar *r, } #endif /* SECP256K1_SCALAR_REPR_IMPL_H */ + + +#else +/********************************************************************** + * 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 + +#include "scalar.h" +#include + +/* 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 *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 *r, unsigned int v) { + r->d[0] = v; + r->d[1] = 0; + r->d[2] = 0; + r->d[3] = 0; +} + +SECP256K1_INLINE static void secp256k1_scalar_set_u64(secp256k1_scalar *r, uint64_t 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 *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 *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 *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 *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 *r, const secp256k1_scalar *a, const secp256k1_scalar *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_cadd_bit(secp256k1_scalar *r, unsigned int bit, int flag) { + uint128_t t; + VERIFY_CHECK(bit < 256); + bit += ((uint32_t) flag - 1) & 0x100; /* forcing (bit >> 6) > 3 makes this a noop */ + 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 *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* 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 *a) { + return (a->d[0] | a->d[1] | a->d[2] | a->d[3]) == 0; +} + +static void secp256k1_scalar_negate(secp256k1_scalar *r, const secp256k1_scalar *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 *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 *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; +} + +static int secp256k1_scalar_cond_negate(secp256k1_scalar *r, int flag) { + /* If we are flag = 0, mask = 00...00 and this is a no-op; + * if we are flag = 1, mask = 11...11 and this is identical to secp256k1_scalar_negate */ + uint64_t mask = !flag - 1; + uint64_t nonzero = (secp256k1_scalar_is_zero(r) != 0) - 1; + uint128_t t = (uint128_t)(r->d[0] ^ mask) + ((SECP256K1_N_0 + 1) & mask); + r->d[0] = t & nonzero; t >>= 64; + t += (uint128_t)(r->d[1] ^ mask) + (SECP256K1_N_1 & mask); + r->d[1] = t & nonzero; t >>= 64; + t += (uint128_t)(r->d[2] ^ mask) + (SECP256K1_N_2 & mask); + r->d[2] = t & nonzero; t >>= 64; + t += (uint128_t)(r->d[3] ^ mask) + (SECP256K1_N_3 & mask); + r->d[3] = t & nonzero; + return 2 * (mask == 0) - 1; +} + +/* 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 *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" + "xorq %%r9, %%r9\n" + "xorq %%r10, %%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" + "xorq %%r8, %%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" + "xorq %%r9, %%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" + "xorq %%r10, %%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" + "xorq %%r8, %%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" + "xorq %%r9, %%r9\n" + "xorq %%r10, %%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" + "xorq %%r8, %%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" + "xorq %%r9, %%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" + "xorq %%r9, %%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" + "xorq %%r8, %%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" + "xorq %%r9, %%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 *a, const secp256k1_scalar *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 *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 *r, const secp256k1_scalar *a, const secp256k1_scalar *b) { + uint64_t l[8]; + secp256k1_scalar_mul_512(l, a, b); + secp256k1_scalar_reduce_512(r, l); +} + +static int secp256k1_scalar_shr_int(secp256k1_scalar *r, int n) { + int ret; + VERIFY_CHECK(n > 0); + VERIFY_CHECK(n < 16); + ret = r->d[0] & ((1 << n) - 1); + r->d[0] = (r->d[0] >> n) + (r->d[1] << (64 - n)); + r->d[1] = (r->d[1] >> n) + (r->d[2] << (64 - n)); + r->d[2] = (r->d[2] >> n) + (r->d[3] << (64 - n)); + r->d[3] = (r->d[3] >> n); + return ret; +} + +static void secp256k1_scalar_sqr(secp256k1_scalar *r, const secp256k1_scalar *a) { + uint64_t l[8]; + secp256k1_scalar_sqr_512(l, a); + secp256k1_scalar_reduce_512(r, l); +} + +#ifdef USE_ENDOMORPHISM +static void secp256k1_scalar_split_128(secp256k1_scalar *r1, secp256k1_scalar *r2, const secp256k1_scalar *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; +} +#endif + +SECP256K1_INLINE static int secp256k1_scalar_eq(const secp256k1_scalar *a, const secp256k1_scalar *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 *r, const secp256k1_scalar *a, const secp256k1_scalar *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; + secp256k1_scalar_cadd_bit(r, 0, (l[(shift - 1) >> 6] >> ((shift - 1) & 0x3f)) & 1); +} + +#define ROTL32(x,n) ((x) << (n) | (x) >> (32-(n))) +#define QUARTERROUND(a,b,c,d) \ +a += b; d = ROTL32(d ^ a, 16); \ +c += d; b = ROTL32(b ^ c, 12); \ +a += b; d = ROTL32(d ^ a, 8); \ +c += d; b = ROTL32(b ^ c, 7); + +#ifdef WORDS_BIGENDIAN +#define LE32(p) ((((p) & 0xFF) << 24) | (((p) & 0xFF00) << 8) | (((p) & 0xFF0000) >> 8) | (((p) & 0xFF000000) >> 24)) +#define BE32(p) (p) +#else +#define BE32(p) ((((p) & 0xFF) << 24) | (((p) & 0xFF00) << 8) | (((p) & 0xFF0000) >> 8) | (((p) & 0xFF000000) >> 24)) +#define LE32(p) (p) +#endif + +static void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx) { + size_t n; + size_t over_count = 0; + uint32_t seed32[8]; + uint32_t x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15; + int over1, over2; + + memcpy((void *) seed32, (const void *) seed, 32); + do { + x0 = 0x61707865; + x1 = 0x3320646e; + x2 = 0x79622d32; + x3 = 0x6b206574; + x4 = LE32(seed32[0]); + x5 = LE32(seed32[1]); + x6 = LE32(seed32[2]); + x7 = LE32(seed32[3]); + x8 = LE32(seed32[4]); + x9 = LE32(seed32[5]); + x10 = LE32(seed32[6]); + x11 = LE32(seed32[7]); + x12 = idx; + x13 = idx >> 32; + x14 = 0; + x15 = over_count; + + n = 10; + while (n--) { + QUARTERROUND(x0, x4, x8,x12) + QUARTERROUND(x1, x5, x9,x13) + QUARTERROUND(x2, x6,x10,x14) + QUARTERROUND(x3, x7,x11,x15) + QUARTERROUND(x0, x5,x10,x15) + QUARTERROUND(x1, x6,x11,x12) + QUARTERROUND(x2, x7, x8,x13) + QUARTERROUND(x3, x4, x9,x14) + } + + x0 += 0x61707865; + x1 += 0x3320646e; + x2 += 0x79622d32; + x3 += 0x6b206574; + x4 += LE32(seed32[0]); + x5 += LE32(seed32[1]); + x6 += LE32(seed32[2]); + x7 += LE32(seed32[3]); + x8 += LE32(seed32[4]); + x9 += LE32(seed32[5]); + x10 += LE32(seed32[6]); + x11 += LE32(seed32[7]); + x12 += idx; + x13 += idx >> 32; + x14 += 0; + x15 += over_count; + + r1->d[3] = LE32((uint64_t) x0) << 32 | LE32(x1); + r1->d[2] = LE32((uint64_t) x2) << 32 | LE32(x3); + r1->d[1] = LE32((uint64_t) x4) << 32 | LE32(x5); + r1->d[0] = LE32((uint64_t) x6) << 32 | LE32(x7); + r2->d[3] = LE32((uint64_t) x8) << 32 | LE32(x9); + r2->d[2] = LE32((uint64_t) x10) << 32 | LE32(x11); + r2->d[1] = LE32((uint64_t) x12) << 32 | LE32(x13); + r2->d[0] = LE32((uint64_t) x14) << 32 | LE32(x15); + + over1 = secp256k1_scalar_check_overflow(r1); + over2 = secp256k1_scalar_check_overflow(r2); + over_count++; + } while (over1 | over2); +} + +#undef ROTL32 +#undef QUARTERROUND +#undef BE32 +#undef LE32 + +#endif /* SECP256K1_SCALAR_REPR_IMPL_H */ +#endif + diff --git a/src/secp256k1/src/scalar_8x32.h b/src/secp256k1/src/scalar_8x32.h index 2c9a348e2..68a2c0428 100644 --- a/src/secp256k1/src/scalar_8x32.h +++ b/src/secp256k1/src/scalar_8x32.h @@ -1,3 +1,5 @@ +#ifdef ENABLE_MODULE_MUSIG + /********************************************************************** * Copyright (c) 2014 Pieter Wuille * * Distributed under the MIT software license, see the accompanying * @@ -17,3 +19,25 @@ typedef struct { #define SECP256K1_SCALAR_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {{(d0), (d1), (d2), (d3), (d4), (d5), (d6), (d7)}} #endif /* SECP256K1_SCALAR_REPR_H */ + +#else +/********************************************************************** + * 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_H +#define SECP256K1_SCALAR_REPR_H + +#include + +/** A scalar modulo the group order of the secp256k1 curve. */ +typedef struct { + uint32_t d[8]; +} secp256k1_scalar; + +#define SECP256K1_SCALAR_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {{(d0), (d1), (d2), (d3), (d4), (d5), (d6), (d7)}} + +#endif /* SECP256K1_SCALAR_REPR_H */ +#endif diff --git a/src/secp256k1/src/scalar_8x32_impl.h b/src/secp256k1/src/scalar_8x32_impl.h index 4f9ed61fe..e1299cbaa 100644 --- a/src/secp256k1/src/scalar_8x32_impl.h +++ b/src/secp256k1/src/scalar_8x32_impl.h @@ -1,3 +1,5 @@ +#ifdef ENABLE_MODULE_MUSIG + /********************************************************************** * Copyright (c) 2014 Pieter Wuille * * Distributed under the MIT software license, see the accompanying * @@ -719,3 +721,839 @@ SECP256K1_INLINE static void secp256k1_scalar_mul_shift_var(secp256k1_scalar *r, } #endif /* SECP256K1_SCALAR_REPR_IMPL_H */ + +#else +/********************************************************************** + * 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 + +#include + +/* 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 *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 *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 void secp256k1_scalar_set_u64(secp256k1_scalar *r, uint64_t v) { + r->d[0] = v; + r->d[1] = v >> 32; + 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 *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 *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 *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 *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 *r, const secp256k1_scalar *a, const secp256k1_scalar *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_cadd_bit(secp256k1_scalar *r, unsigned int bit, int flag) { + uint64_t t; + VERIFY_CHECK(bit < 256); + bit += ((uint32_t) flag - 1) & 0x100; /* forcing (bit >> 5) > 7 makes this a noop */ + 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 *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* 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 *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 *r, const secp256k1_scalar *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 *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 *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; +} + +static int secp256k1_scalar_cond_negate(secp256k1_scalar *r, int flag) { + /* If we are flag = 0, mask = 00...00 and this is a no-op; + * if we are flag = 1, mask = 11...11 and this is identical to secp256k1_scalar_negate */ + uint32_t mask = !flag - 1; + uint32_t nonzero = 0xFFFFFFFFUL * (secp256k1_scalar_is_zero(r) == 0); + uint64_t t = (uint64_t)(r->d[0] ^ mask) + ((SECP256K1_N_0 + 1) & mask); + r->d[0] = t & nonzero; t >>= 32; + t += (uint64_t)(r->d[1] ^ mask) + (SECP256K1_N_1 & mask); + r->d[1] = t & nonzero; t >>= 32; + t += (uint64_t)(r->d[2] ^ mask) + (SECP256K1_N_2 & mask); + r->d[2] = t & nonzero; t >>= 32; + t += (uint64_t)(r->d[3] ^ mask) + (SECP256K1_N_3 & mask); + r->d[3] = t & nonzero; t >>= 32; + t += (uint64_t)(r->d[4] ^ mask) + (SECP256K1_N_4 & mask); + r->d[4] = t & nonzero; t >>= 32; + t += (uint64_t)(r->d[5] ^ mask) + (SECP256K1_N_5 & mask); + r->d[5] = t & nonzero; t >>= 32; + t += (uint64_t)(r->d[6] ^ mask) + (SECP256K1_N_6 & mask); + r->d[6] = t & nonzero; t >>= 32; + t += (uint64_t)(r->d[7] ^ mask) + (SECP256K1_N_7 & mask); + r->d[7] = t & nonzero; + return 2 * (mask == 0) - 1; +} + + +/* 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 *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 *a, const secp256k1_scalar *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 *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 *r, const secp256k1_scalar *a, const secp256k1_scalar *b) { + uint32_t l[16]; + secp256k1_scalar_mul_512(l, a, b); + secp256k1_scalar_reduce_512(r, l); +} + +static int secp256k1_scalar_shr_int(secp256k1_scalar *r, int n) { + int ret; + VERIFY_CHECK(n > 0); + VERIFY_CHECK(n < 16); + ret = r->d[0] & ((1 << n) - 1); + r->d[0] = (r->d[0] >> n) + (r->d[1] << (32 - n)); + r->d[1] = (r->d[1] >> n) + (r->d[2] << (32 - n)); + r->d[2] = (r->d[2] >> n) + (r->d[3] << (32 - n)); + r->d[3] = (r->d[3] >> n) + (r->d[4] << (32 - n)); + r->d[4] = (r->d[4] >> n) + (r->d[5] << (32 - n)); + r->d[5] = (r->d[5] >> n) + (r->d[6] << (32 - n)); + r->d[6] = (r->d[6] >> n) + (r->d[7] << (32 - n)); + r->d[7] = (r->d[7] >> n); + return ret; +} + +static void secp256k1_scalar_sqr(secp256k1_scalar *r, const secp256k1_scalar *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 *r1, secp256k1_scalar *r2, const secp256k1_scalar *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 *a, const secp256k1_scalar *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 *r, const secp256k1_scalar *a, const secp256k1_scalar *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; + secp256k1_scalar_cadd_bit(r, 0, (l[(shift - 1) >> 5] >> ((shift - 1) & 0x1f)) & 1); +} + +#define ROTL32(x,n) ((x) << (n) | (x) >> (32-(n))) +#define QUARTERROUND(a,b,c,d) \ +a += b; d = ROTL32(d ^ a, 16); \ +c += d; b = ROTL32(b ^ c, 12); \ +a += b; d = ROTL32(d ^ a, 8); \ +c += d; b = ROTL32(b ^ c, 7); + +#ifdef WORDS_BIGENDIAN +#define LE32(p) ((((p) & 0xFF) << 24) | (((p) & 0xFF00) << 8) | (((p) & 0xFF0000) >> 8) | (((p) & 0xFF000000) >> 24)) +#define BE32(p) (p) +#else +#define BE32(p) ((((p) & 0xFF) << 24) | (((p) & 0xFF00) << 8) | (((p) & 0xFF0000) >> 8) | (((p) & 0xFF000000) >> 24)) +#define LE32(p) (p) +#endif + +static void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx) { + size_t n; + size_t over_count = 0; + uint32_t seed32[8]; + uint32_t x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15; + int over1, over2; + + memcpy((void *) seed32, (const void *) seed, 32); + do { + x0 = 0x61707865; + x1 = 0x3320646e; + x2 = 0x79622d32; + x3 = 0x6b206574; + x4 = LE32(seed32[0]); + x5 = LE32(seed32[1]); + x6 = LE32(seed32[2]); + x7 = LE32(seed32[3]); + x8 = LE32(seed32[4]); + x9 = LE32(seed32[5]); + x10 = LE32(seed32[6]); + x11 = LE32(seed32[7]); + x12 = idx; + x13 = idx >> 32; + x14 = 0; + x15 = over_count; + + n = 10; + while (n--) { + QUARTERROUND(x0, x4, x8,x12) + QUARTERROUND(x1, x5, x9,x13) + QUARTERROUND(x2, x6,x10,x14) + QUARTERROUND(x3, x7,x11,x15) + QUARTERROUND(x0, x5,x10,x15) + QUARTERROUND(x1, x6,x11,x12) + QUARTERROUND(x2, x7, x8,x13) + QUARTERROUND(x3, x4, x9,x14) + } + + x0 += 0x61707865; + x1 += 0x3320646e; + x2 += 0x79622d32; + x3 += 0x6b206574; + x4 += LE32(seed32[0]); + x5 += LE32(seed32[1]); + x6 += LE32(seed32[2]); + x7 += LE32(seed32[3]); + x8 += LE32(seed32[4]); + x9 += LE32(seed32[5]); + x10 += LE32(seed32[6]); + x11 += LE32(seed32[7]); + x12 += idx; + x13 += idx >> 32; + x14 += 0; + x15 += over_count; + + r1->d[7] = LE32(x0); + r1->d[6] = LE32(x1); + r1->d[5] = LE32(x2); + r1->d[4] = LE32(x3); + r1->d[3] = LE32(x4); + r1->d[2] = LE32(x5); + r1->d[1] = LE32(x6); + r1->d[0] = LE32(x7); + r2->d[7] = LE32(x8); + r2->d[6] = LE32(x9); + r2->d[5] = LE32(x10); + r2->d[4] = LE32(x11); + r2->d[3] = LE32(x12); + r2->d[2] = LE32(x13); + r2->d[1] = LE32(x14); + r2->d[0] = LE32(x15); + + over1 = secp256k1_scalar_check_overflow(r1); + over2 = secp256k1_scalar_check_overflow(r2); + over_count++; + } while (over1 | over2); +} + +#undef ROTL32 +#undef QUARTERROUND +#undef BE32 +#undef LE32 + +#endif /* SECP256K1_SCALAR_REPR_IMPL_H */ +#endif + diff --git a/src/secp256k1/src/scalar_impl.h b/src/secp256k1/src/scalar_impl.h index fa790570f..494168e53 100644 --- a/src/secp256k1/src/scalar_impl.h +++ b/src/secp256k1/src/scalar_impl.h @@ -1,3 +1,5 @@ +#ifdef ENABLE_MODULE_MUSIG + /********************************************************************** * Copyright (c) 2014 Pieter Wuille * * Distributed under the MIT software license, see the accompanying * @@ -331,3 +333,341 @@ static void secp256k1_scalar_split_lambda(secp256k1_scalar *r1, secp256k1_scalar #endif #endif /* SECP256K1_SCALAR_IMPL_H */ + + +#else +/********************************************************************** + * 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 "group.h" +#include "scalar.h" + +#if defined HAVE_CONFIG_H +#include "libsecp256k1-config.h" +#endif + +#if defined(EXHAUSTIVE_TEST_ORDER) +#include "scalar_low_impl.h" +#elif 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 *r, const secp256k1_scalar *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 *r) { +#if defined(EXHAUSTIVE_TEST_ORDER) + static const unsigned char order[32] = { + 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,EXHAUSTIVE_TEST_ORDER + }; +#else + 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 + }; +#endif + secp256k1_num_set_bin(r, order, 32); +} +#endif + +static void secp256k1_scalar_inverse(secp256k1_scalar *r, const secp256k1_scalar *x) { +#if defined(EXHAUSTIVE_TEST_ORDER) + int i; + *r = 0; + for (i = 0; i < EXHAUSTIVE_TEST_ORDER; i++) + if ((i * *x) % EXHAUSTIVE_TEST_ORDER == 1) + *r = i; + /* If this VERIFY_CHECK triggers we were given a noninvertible scalar (and thus + * have a composite group order; fix it in exhaustive_tests.c). */ + VERIFY_CHECK(*r != 0); +} +#else +secp256k1_scalar *t; +int i; +/* First compute xN as x ^ (2^N - 1) for some values of N, + * and uM as x ^ M for some values of M. */ +secp256k1_scalar x2, x3, x6, x8, x14, x28, x56, x112, x126; +secp256k1_scalar u2, u5, u9, u11, u13; + +secp256k1_scalar_sqr(&u2, x); +secp256k1_scalar_mul(&x2, &u2, x); +secp256k1_scalar_mul(&u5, &u2, &x2); +secp256k1_scalar_mul(&x3, &u5, &u2); +secp256k1_scalar_mul(&u9, &x3, &u2); +secp256k1_scalar_mul(&u11, &u9, &u2); +secp256k1_scalar_mul(&u13, &u11, &u2); + +secp256k1_scalar_sqr(&x6, &u13); +secp256k1_scalar_sqr(&x6, &x6); +secp256k1_scalar_mul(&x6, &x6, &u11); + +secp256k1_scalar_sqr(&x8, &x6); +secp256k1_scalar_sqr(&x8, &x8); +secp256k1_scalar_mul(&x8, &x8, &x2); + +secp256k1_scalar_sqr(&x14, &x8); +for (i = 0; i < 5; i++) { + secp256k1_scalar_sqr(&x14, &x14); +} +secp256k1_scalar_mul(&x14, &x14, &x6); + +secp256k1_scalar_sqr(&x28, &x14); +for (i = 0; i < 13; i++) { + secp256k1_scalar_sqr(&x28, &x28); +} +secp256k1_scalar_mul(&x28, &x28, &x14); + +secp256k1_scalar_sqr(&x56, &x28); +for (i = 0; i < 27; i++) { + secp256k1_scalar_sqr(&x56, &x56); +} +secp256k1_scalar_mul(&x56, &x56, &x28); + +secp256k1_scalar_sqr(&x112, &x56); +for (i = 0; i < 55; i++) { + secp256k1_scalar_sqr(&x112, &x112); +} +secp256k1_scalar_mul(&x112, &x112, &x56); + +secp256k1_scalar_sqr(&x126, &x112); +for (i = 0; i < 13; i++) { + secp256k1_scalar_sqr(&x126, &x126); +} +secp256k1_scalar_mul(&x126, &x126, &x14); + +/* Then accumulate the final result (t starts at x126). */ +t = &x126; +for (i = 0; i < 3; i++) { + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u5); /* 101 */ +for (i = 0; i < 4; i++) { /* 0 */ + 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, &u5); /* 101 */ +for (i = 0; i < 5; i++) { /* 0 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u11); /* 1011 */ +for (i = 0; i < 4; i++) { + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u11); /* 1011 */ +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 < 6; i++) { /* 00 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u13); /* 1101 */ +for (i = 0; i < 4; i++) { /* 0 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u5); /* 101 */ +for (i = 0; i < 3; i++) { + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &x3); /* 111 */ +for (i = 0; i < 5; i++) { /* 0 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u9); /* 1001 */ +for (i = 0; i < 6; i++) { /* 000 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u5); /* 101 */ +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 < 5; i++) { /* 0 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u9); /* 1001 */ +for (i = 0; i < 6; i++) { /* 00 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u11); /* 1011 */ +for (i = 0; i < 4; i++) { + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u13); /* 1101 */ +for (i = 0; i < 5; i++) { + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &x2); /* 11 */ +for (i = 0; i < 6; i++) { /* 00 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u13); /* 1101 */ +for (i = 0; i < 10; i++) { /* 000000 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u13); /* 1101 */ +for (i = 0; i < 4; i++) { + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u9); /* 1001 */ +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 */ +} + +SECP256K1_INLINE static int secp256k1_scalar_is_even(const secp256k1_scalar *a) { + return !(a->d[0] & 1); +} +#endif + +static void secp256k1_scalar_inverse_var(secp256k1_scalar *r, const secp256k1_scalar *x) { +#if defined(USE_SCALAR_INV_BUILTIN) + secp256k1_scalar_inverse(r, x); +#elif defined(USE_SCALAR_INV_NUM) + unsigned char b[32]; + secp256k1_num n, m; + secp256k1_scalar t = *x; + secp256k1_scalar_get_b32(b, &t); + 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); + /* Verify that the inverse was computed correctly, without GMP code. */ + secp256k1_scalar_mul(&t, &t, r); + CHECK(secp256k1_scalar_is_one(&t)); +#else +#error "Please select scalar inverse implementation" +#endif +} + +#ifdef USE_ENDOMORPHISM +#if defined(EXHAUSTIVE_TEST_ORDER) +/** + * Find k1 and k2 given k, such that k1 + k2 * lambda == k mod n; unlike in the + * full case we don't bother making k1 and k2 be small, we just want them to be + * nontrivial to get full test coverage for the exhaustive tests. We therefore + * (arbitrarily) set k2 = k + 5 and k1 = k - k2 * lambda. + */ +static void secp256k1_scalar_split_lambda(secp256k1_scalar *r1, secp256k1_scalar *r2, const secp256k1_scalar *a) { + *r2 = (*a + 5) % EXHAUSTIVE_TEST_ORDER; + *r1 = (*a + (EXHAUSTIVE_TEST_ORDER - *r2) * EXHAUSTIVE_TEST_LAMBDA) % EXHAUSTIVE_TEST_ORDER; +} +#else +/** + * 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(secp256k1_scalar *r1, secp256k1_scalar *r2, const secp256k1_scalar *a) { + secp256k1_scalar c1, c2; + static const secp256k1_scalar minus_lambda = SECP256K1_SCALAR_CONST( + 0xAC9C52B3UL, 0x3FA3CF1FUL, 0x5AD9E3FDUL, 0x77ED9BA4UL, + 0xA880B9FCUL, 0x8EC739C2UL, 0xE0CFC810UL, 0xB51283CFUL + ); + static const secp256k1_scalar minus_b1 = SECP256K1_SCALAR_CONST( + 0x00000000UL, 0x00000000UL, 0x00000000UL, 0x00000000UL, + 0xE4437ED6UL, 0x010E8828UL, 0x6F547FA9UL, 0x0ABFE4C3UL + ); + static const secp256k1_scalar minus_b2 = SECP256K1_SCALAR_CONST( + 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFEUL, + 0x8A280AC5UL, 0x0774346DUL, 0xD765CDA8UL, 0x3DB1562CUL + ); + static const secp256k1_scalar g1 = SECP256K1_SCALAR_CONST( + 0x00000000UL, 0x00000000UL, 0x00000000UL, 0x00003086UL, + 0xD221A7D4UL, 0x6BCDE86CUL, 0x90E49284UL, 0xEB153DABUL + ); + static const secp256k1_scalar g2 = SECP256K1_SCALAR_CONST( + 0x00000000UL, 0x00000000UL, 0x00000000UL, 0x0000E443UL, + 0x7ED6010EUL, 0x88286F54UL, 0x7FA90ABFUL, 0xE4C42212UL + ); + VERIFY_CHECK(r1 != a); + VERIFY_CHECK(r2 != a); + /* these _var calls are constant time since the shift amount is constant */ + 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 + +#endif /* SECP256K1_SCALAR_IMPL_H */ +#endif + diff --git a/src/secp256k1/src/scalar_low.h b/src/secp256k1/src/scalar_low.h index 5836febc5..2039aafc7 100644 --- a/src/secp256k1/src/scalar_low.h +++ b/src/secp256k1/src/scalar_low.h @@ -1,3 +1,5 @@ +#ifdef ENABLE_MODULE_MUSIG + /********************************************************************** * Copyright (c) 2015 Andrew Poelstra * * Distributed under the MIT software license, see the accompanying * @@ -13,3 +15,21 @@ typedef uint32_t secp256k1_scalar; #endif /* SECP256K1_SCALAR_REPR_H */ + +#else +/********************************************************************** + * Copyright (c) 2015 Andrew Poelstra * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_SCALAR_REPR_H +#define SECP256K1_SCALAR_REPR_H + +#include + +/** A scalar modulo the group order of the secp256k1 curve. */ +typedef uint32_t secp256k1_scalar; + +#endif /* SECP256K1_SCALAR_REPR_H */ +#endif diff --git a/src/secp256k1/src/scalar_low_impl.h b/src/secp256k1/src/scalar_low_impl.h index c80e70c5a..99689a4fd 100644 --- a/src/secp256k1/src/scalar_low_impl.h +++ b/src/secp256k1/src/scalar_low_impl.h @@ -1,3 +1,5 @@ +#ifdef ENABLE_MODULE_MUSIG + /********************************************************************** * Copyright (c) 2015 Andrew Poelstra * * Distributed under the MIT software license, see the accompanying * @@ -112,3 +114,127 @@ SECP256K1_INLINE static int secp256k1_scalar_eq(const secp256k1_scalar *a, const } #endif /* SECP256K1_SCALAR_REPR_IMPL_H */ + +#else +/********************************************************************** + * Copyright (c) 2015 Andrew Poelstra * + * 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 + +#include "scalar.h" + +#include + +SECP256K1_INLINE static int secp256k1_scalar_is_even(const secp256k1_scalar *a) { + return !(*a & 1); +} + +SECP256K1_INLINE static void secp256k1_scalar_clear(secp256k1_scalar *r) { *r = 0; } +SECP256K1_INLINE static void secp256k1_scalar_set_int(secp256k1_scalar *r, unsigned int v) { *r = v; } +SECP256K1_INLINE static void secp256k1_scalar_set_u64(secp256k1_scalar *r, uint64_t v) { *r = v % EXHAUSTIVE_TEST_ORDER; } + +SECP256K1_INLINE static unsigned int secp256k1_scalar_get_bits(const secp256k1_scalar *a, unsigned int offset, unsigned int count) { + if (offset < 32) + return ((*a >> offset) & ((((uint32_t)1) << count) - 1)); + else + return 0; +} + +SECP256K1_INLINE static unsigned int secp256k1_scalar_get_bits_var(const secp256k1_scalar *a, unsigned int offset, unsigned int count) { + return secp256k1_scalar_get_bits(a, offset, count); +} + +SECP256K1_INLINE static int secp256k1_scalar_check_overflow(const secp256k1_scalar *a) { return *a >= EXHAUSTIVE_TEST_ORDER; } + +static int secp256k1_scalar_add(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b) { + *r = (*a + *b) % EXHAUSTIVE_TEST_ORDER; + return *r < *b; +} + +static void secp256k1_scalar_cadd_bit(secp256k1_scalar *r, unsigned int bit, int flag) { + if (flag && bit < 32) + *r += (1 << bit); +#ifdef VERIFY + VERIFY_CHECK(secp256k1_scalar_check_overflow(r) == 0); +#endif +} + +static void secp256k1_scalar_set_b32(secp256k1_scalar *r, const unsigned char *b32, int *overflow) { + const int base = 0x100 % EXHAUSTIVE_TEST_ORDER; + int i; + *r = 0; + for (i = 0; i < 32; i++) { + *r = ((*r * base) + b32[i]) % EXHAUSTIVE_TEST_ORDER; + } + /* just deny overflow, it basically always happens */ + if (overflow) *overflow = 0; +} + +static void secp256k1_scalar_get_b32(unsigned char *bin, const secp256k1_scalar* a) { + memset(bin, 0, 32); + bin[28] = *a >> 24; bin[29] = *a >> 16; bin[30] = *a >> 8; bin[31] = *a; +} + +SECP256K1_INLINE static int secp256k1_scalar_is_zero(const secp256k1_scalar *a) { + return *a == 0; +} + +static void secp256k1_scalar_negate(secp256k1_scalar *r, const secp256k1_scalar *a) { + if (*a == 0) { + *r = 0; + } else { + *r = EXHAUSTIVE_TEST_ORDER - *a; + } +} + +SECP256K1_INLINE static int secp256k1_scalar_is_one(const secp256k1_scalar *a) { + return *a == 1; +} + +static int secp256k1_scalar_is_high(const secp256k1_scalar *a) { + return *a > EXHAUSTIVE_TEST_ORDER / 2; +} + +static int secp256k1_scalar_cond_negate(secp256k1_scalar *r, int flag) { + if (flag) secp256k1_scalar_negate(r, r); + return flag ? -1 : 1; +} + +static void secp256k1_scalar_mul(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b) { + *r = (*a * *b) % EXHAUSTIVE_TEST_ORDER; +} + +static int secp256k1_scalar_shr_int(secp256k1_scalar *r, int n) { + int ret; + VERIFY_CHECK(n > 0); + VERIFY_CHECK(n < 16); + ret = *r & ((1 << n) - 1); + *r >>= n; + return ret; +} + +static void secp256k1_scalar_sqr(secp256k1_scalar *r, const secp256k1_scalar *a) { + *r = (*a * *a) % EXHAUSTIVE_TEST_ORDER; +} + +static void secp256k1_scalar_split_128(secp256k1_scalar *r1, secp256k1_scalar *r2, const secp256k1_scalar *a) { + *r1 = *a; + *r2 = 0; +} + +SECP256K1_INLINE static int secp256k1_scalar_eq(const secp256k1_scalar *a, const secp256k1_scalar *b) { + return *a == *b; +} + +SECP256K1_INLINE static void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t n) { + *r1 = (seed[0] + n) % EXHAUSTIVE_TEST_ORDER; + *r2 = (seed[1] + n) % EXHAUSTIVE_TEST_ORDER; +} + +#endif /* SECP256K1_SCALAR_REPR_IMPL_H */ +#endif + From cf2a4fb66a2f714b78f9cfc69f28a08cdcd1f603 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 06:36:26 -1100 Subject: [PATCH 091/390] AM_CONDITIONAL --- src/secp256k1/configure.ac | 1 + 1 file changed, 1 insertion(+) diff --git a/src/secp256k1/configure.ac b/src/secp256k1/configure.ac index e5fcbcb4e..4c46f321f 100644 --- a/src/secp256k1/configure.ac +++ b/src/secp256k1/configure.ac @@ -479,6 +479,7 @@ AM_CONDITIONAL([USE_TESTS], [test x"$use_tests" != x"no"]) AM_CONDITIONAL([USE_EXHAUSTIVE_TESTS], [test x"$use_exhaustive_tests" != x"no"]) AM_CONDITIONAL([USE_BENCHMARK], [test x"$use_benchmark" = x"yes"]) AM_CONDITIONAL([USE_ECMULT_STATIC_PRECOMPUTATION], [test x"$set_precomp" = x"yes"]) +AM_CONDITIONAL([ENABLE_MODULE_MUSIG], [test x"$enable_module_musig" = x"yes"]) AM_CONDITIONAL([ENABLE_MODULE_ECDH], [test x"$enable_module_ecdh" = x"yes"]) AM_CONDITIONAL([ENABLE_MODULE_RECOVERY], [test x"$enable_module_recovery" = x"yes"]) AM_CONDITIONAL([USE_JNI], [test x"$use_jni" == x"yes"]) From a8b89a2d87884db14f7398a29c75164e792fcca8 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 06:43:01 -1100 Subject: [PATCH 092/390] #include "scratch_impl.h" --- src/secp256k1/Makefile.am | 2 + src/secp256k1/src/scalar.h | 117 ------------------------------- src/secp256k1/src/scalar_4x64.h | 24 ------- src/secp256k1/src/scratch.h | 40 +++++++++++ src/secp256k1/src/scratch_impl.h | 87 +++++++++++++++++++++++ src/secp256k1/src/secp256k1.c | 1 + 6 files changed, 130 insertions(+), 141 deletions(-) create mode 100644 src/secp256k1/src/scratch.h create mode 100644 src/secp256k1/src/scratch_impl.h diff --git a/src/secp256k1/Makefile.am b/src/secp256k1/Makefile.am index ff5a2c50c..36d56a9ac 100644 --- a/src/secp256k1/Makefile.am +++ b/src/secp256k1/Makefile.am @@ -42,6 +42,8 @@ noinst_HEADERS += src/field_5x52_asm_impl.h noinst_HEADERS += src/java/org_bitcoin_NativeSecp256k1.h noinst_HEADERS += src/java/org_bitcoin_Secp256k1Context.h noinst_HEADERS += src/util.h +noinst_HEADERS += src/scratch.h +noinst_HEADERS += src/scratch_impl.h noinst_HEADERS += src/testrand.h noinst_HEADERS += src/testrand_impl.h noinst_HEADERS += src/hash.h diff --git a/src/secp256k1/src/scalar.h b/src/secp256k1/src/scalar.h index 3d972dc84..aa1cc3286 100644 --- a/src/secp256k1/src/scalar.h +++ b/src/secp256k1/src/scalar.h @@ -222,120 +222,3 @@ static void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2 #endif /* SECP256K1_SCALAR_H */ #endif - -#else - -/********************************************************************** - * 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_H -#define SECP256K1_SCALAR_H - -#include "num.h" - -#if defined HAVE_CONFIG_H -#include "libsecp256k1-config.h" -#endif - -#if defined(EXHAUSTIVE_TEST_ORDER) -#include "scalar_low.h" -#elif 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 *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 *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 *a, unsigned int offset, unsigned int count); - -/** Set a scalar from a big endian byte array. */ -static void secp256k1_scalar_set_b32(secp256k1_scalar *r, const unsigned char *bin, int *overflow); - -/** Set a scalar to an unsigned integer. */ -static void secp256k1_scalar_set_int(secp256k1_scalar *r, unsigned int v); - -/** Set a scalar to an unsigned 64-bit integer */ -static void secp256k1_scalar_set_u64(secp256k1_scalar *r, uint64_t v); - -/** Convert a scalar to a byte array. */ -static void secp256k1_scalar_get_b32(unsigned char *bin, const secp256k1_scalar* a); - -/** Add two scalars together (modulo the group order). Returns whether it overflowed. */ -static int secp256k1_scalar_add(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b); - -/** Conditionally add a power of two to a scalar. The result is not allowed to overflow. */ -static void secp256k1_scalar_cadd_bit(secp256k1_scalar *r, unsigned int bit, int flag); - -/** Multiply two scalars (modulo the group order). */ -static void secp256k1_scalar_mul(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b); - -/** Shift a scalar right by some amount strictly between 0 and 16, returning - * the low bits that were shifted off */ -static int secp256k1_scalar_shr_int(secp256k1_scalar *r, int n); - -/** Compute the square of a scalar (modulo the group order). */ -static void secp256k1_scalar_sqr(secp256k1_scalar *r, const secp256k1_scalar *a); - -/** Compute the inverse of a scalar (modulo the group order). */ -static void secp256k1_scalar_inverse(secp256k1_scalar *r, const secp256k1_scalar *a); - -/** Compute the inverse of a scalar (modulo the group order), without constant-time guarantee. */ -static void secp256k1_scalar_inverse_var(secp256k1_scalar *r, const secp256k1_scalar *a); - -/** Compute the complement of a scalar (modulo the group order). */ -static void secp256k1_scalar_negate(secp256k1_scalar *r, const secp256k1_scalar *a); - -/** Check whether a scalar equals zero. */ -static int secp256k1_scalar_is_zero(const secp256k1_scalar *a); - -/** Check whether a scalar equals one. */ -static int secp256k1_scalar_is_one(const secp256k1_scalar *a); - -/** Check whether a scalar, considered as an nonnegative integer, is even. */ -static int secp256k1_scalar_is_even(const secp256k1_scalar *a); - -/** Check whether a scalar is higher than the group order divided by 2. */ -static int secp256k1_scalar_is_high(const secp256k1_scalar *a); - -/** Conditionally negate a number, in constant time. - * Returns -1 if the number was negated, 1 otherwise */ -static int secp256k1_scalar_cond_negate(secp256k1_scalar *a, int flag); - -#ifndef USE_NUM_NONE -/** Convert a scalar to a number. */ -static void secp256k1_scalar_get_num(secp256k1_num *r, const secp256k1_scalar *a); - -/** Get the order of the group as a number. */ -static void secp256k1_scalar_order_get_num(secp256k1_num *r); -#endif - -/** Compare two scalars. */ -static int secp256k1_scalar_eq(const secp256k1_scalar *a, const secp256k1_scalar *b); - -#ifdef USE_ENDOMORPHISM -/** Find r1 and r2 such that r1+r2*2^128 = a. */ -static void secp256k1_scalar_split_128(secp256k1_scalar *r1, secp256k1_scalar *r2, const secp256k1_scalar *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(secp256k1_scalar *r1, secp256k1_scalar *r2, const secp256k1_scalar *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 *r, const secp256k1_scalar *a, const secp256k1_scalar *b, unsigned int shift); - -/** Generate two scalars from a 32-byte seed and an integer using the chacha20 stream cipher */ -static void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx); - -#endif /* SECP256K1_SCALAR_H */ -#endif - diff --git a/src/secp256k1/src/scalar_4x64.h b/src/secp256k1/src/scalar_4x64.h index 326afd6b5..1768966cf 100644 --- a/src/secp256k1/src/scalar_4x64.h +++ b/src/secp256k1/src/scalar_4x64.h @@ -42,27 +42,3 @@ typedef struct { #endif /* SECP256K1_SCALAR_REPR_H */ #endif - -#else -/********************************************************************** - * 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_H -#define SECP256K1_SCALAR_REPR_H - -#include - -/** A scalar modulo the group order of the secp256k1 curve. */ -typedef struct { - uint64_t d[4]; -} secp256k1_scalar; - -#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 /* SECP256K1_SCALAR_REPR_H */ -#endif - - diff --git a/src/secp256k1/src/scratch.h b/src/secp256k1/src/scratch.h new file mode 100644 index 000000000..04faa9f0a --- /dev/null +++ b/src/secp256k1/src/scratch.h @@ -0,0 +1,40 @@ +/********************************************************************** + * Copyright (c) 2017 Andrew Poelstra * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef _SECP256K1_SCRATCH_ +#define _SECP256K1_SCRATCH_ + +#define SECP256K1_SCRATCH_MAX_FRAMES 5 + +/* The typedef is used internally; the struct name is used in the public API + * (where it is exposed as a different typedef) */ +typedef struct secp256k1_scratch_space_struct { + void *data[SECP256K1_SCRATCH_MAX_FRAMES]; + size_t offset[SECP256K1_SCRATCH_MAX_FRAMES]; + size_t frame_size[SECP256K1_SCRATCH_MAX_FRAMES]; + size_t frame; + size_t max_size; + const secp256k1_callback* error_callback; +} secp256k1_scratch; + +static secp256k1_scratch* secp256k1_scratch_create(const secp256k1_callback* error_callback, size_t max_size); + +static void secp256k1_scratch_destroy(secp256k1_scratch* scratch); + +/** Attempts to allocate a new stack frame with `n` available bytes. Returns 1 on success, 0 on failure */ +static int secp256k1_scratch_allocate_frame(secp256k1_scratch* scratch, size_t n, size_t objects); + +/** Deallocates a stack frame */ +static void secp256k1_scratch_deallocate_frame(secp256k1_scratch* scratch); + +/** Returns the maximum allocation the scratch space will allow */ +static size_t secp256k1_scratch_max_allocation(const secp256k1_scratch* scratch, size_t n_objects); + +/** Returns a pointer into the most recently allocated frame, or NULL if there is insufficient available space */ +static void *secp256k1_scratch_alloc(secp256k1_scratch* scratch, size_t n); + +#endif + diff --git a/src/secp256k1/src/scratch_impl.h b/src/secp256k1/src/scratch_impl.h new file mode 100644 index 000000000..1ce3ff9b0 --- /dev/null +++ b/src/secp256k1/src/scratch_impl.h @@ -0,0 +1,87 @@ +/********************************************************************** + * Copyright (c) 2017 Andrew Poelstra * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef _SECP256K1_SCRATCH_IMPL_H_ +#define _SECP256K1_SCRATCH_IMPL_H_ + +#include "scratch.h" + +/* Using 16 bytes alignment because common architectures never have alignment + * requirements above 8 for any of the types we care about. In addition we + * leave some room because currently we don't care about a few bytes. + * TODO: Determine this at configure time. */ +#define ALIGNMENT 16 + +static secp256k1_scratch* secp256k1_scratch_create(const secp256k1_callback* error_callback, size_t max_size) { + secp256k1_scratch* ret = (secp256k1_scratch*)checked_malloc(error_callback, sizeof(*ret)); + if (ret != NULL) { + memset(ret, 0, sizeof(*ret)); + ret->max_size = max_size; + ret->error_callback = error_callback; + } + return ret; +} + +static void secp256k1_scratch_destroy(secp256k1_scratch* scratch) { + if (scratch != NULL) { + VERIFY_CHECK(scratch->frame == 0); + free(scratch); + } +} + +static size_t secp256k1_scratch_max_allocation(const secp256k1_scratch* scratch, size_t objects) { + size_t i = 0; + size_t allocated = 0; + for (i = 0; i < scratch->frame; i++) { + allocated += scratch->frame_size[i]; + } + if (scratch->max_size - allocated <= objects * ALIGNMENT) { + return 0; + } + return scratch->max_size - allocated - objects * ALIGNMENT; +} + +static int secp256k1_scratch_allocate_frame(secp256k1_scratch* scratch, size_t n, size_t objects) { + VERIFY_CHECK(scratch->frame < SECP256K1_SCRATCH_MAX_FRAMES); + + if (n <= secp256k1_scratch_max_allocation(scratch, objects)) { + n += objects * ALIGNMENT; + scratch->data[scratch->frame] = checked_malloc(scratch->error_callback, n); + if (scratch->data[scratch->frame] == NULL) { + return 0; + } + scratch->frame_size[scratch->frame] = n; + scratch->offset[scratch->frame] = 0; + scratch->frame++; + return 1; + } else { + return 0; + } +} + +static void secp256k1_scratch_deallocate_frame(secp256k1_scratch* scratch) { + VERIFY_CHECK(scratch->frame > 0); + scratch->frame -= 1; + free(scratch->data[scratch->frame]); +} + +static void *secp256k1_scratch_alloc(secp256k1_scratch* scratch, size_t size) { + void *ret; + size_t frame = scratch->frame - 1; + size = ((size + ALIGNMENT - 1) / ALIGNMENT) * ALIGNMENT; + + if (scratch->frame == 0 || size + scratch->offset[frame] > scratch->frame_size[frame]) { + return NULL; + } + ret = (void *) ((unsigned char *) scratch->data[frame] + scratch->offset[frame]); + memset(ret, 0, size); + scratch->offset[frame] += size; + + return ret; +} + +#endif + diff --git a/src/secp256k1/src/secp256k1.c b/src/secp256k1/src/secp256k1.c index cecb1550b..b89a7c04a 100644 --- a/src/secp256k1/src/secp256k1.c +++ b/src/secp256k1/src/secp256k1.c @@ -17,6 +17,7 @@ #include "ecdsa_impl.h" #include "eckey_impl.h" #include "hash_impl.h" +#include "scratch_impl.h" #define ARG_CHECK(cond) do { \ if (EXPECT(!(cond), 0)) { \ From f9482fe0fe5ec7a3f89d1b09f195a5b93ad8218f Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 06:45:11 -1100 Subject: [PATCH 093/390] ENABLE_MODULE_MUSIG --- src/secp256k1/Makefile.am | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/secp256k1/Makefile.am b/src/secp256k1/Makefile.am index 36d56a9ac..84359ddb9 100644 --- a/src/secp256k1/Makefile.am +++ b/src/secp256k1/Makefile.am @@ -148,7 +148,7 @@ endif if USE_ECMULT_STATIC_PRECOMPUTATION CPPFLAGS_FOR_BUILD +=-I$(top_srcdir) -CFLAGS_FOR_BUILD += -Wall -Wextra -Wno-unused-function +CFLAGS_FOR_BUILD += -Wall -Wextra -Wno-unused-function -DENABLE_MODULE_MUSIG gen_context_OBJECTS = gen_context.o gen_context_BIN = gen_context$(BUILD_EXEEXT) From 20c08245a251ea332cd8ddb7bfcaf42fc93ff181 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 06:47:51 -1100 Subject: [PATCH 094/390] Test --- src/secp256k1/src/scalar_4x64_impl.h | 1 + 1 file changed, 1 insertion(+) diff --git a/src/secp256k1/src/scalar_4x64_impl.h b/src/secp256k1/src/scalar_4x64_impl.h index ee75ad51e..192874529 100644 --- a/src/secp256k1/src/scalar_4x64_impl.h +++ b/src/secp256k1/src/scalar_4x64_impl.h @@ -2001,5 +2001,6 @@ static void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2 #undef LE32 #endif /* SECP256K1_SCALAR_REPR_IMPL_H */ +xxx #endif From 03f15db75cc1c94bb7b5d8897419539b56fc0bb9 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 06:59:00 -1100 Subject: [PATCH 095/390] -DENABLE_MODULE_MUSIG --- src/secp256k1/Makefile.am | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/secp256k1/Makefile.am b/src/secp256k1/Makefile.am index 84359ddb9..d8c03e96b 100644 --- a/src/secp256k1/Makefile.am +++ b/src/secp256k1/Makefile.am @@ -1,5 +1,7 @@ ACLOCAL_AMFLAGS = -I build-aux/m4 +CFLAGS += -DENABLE_MODULE_MUSIG + lib_LTLIBRARIES = libsecp256k1.la if USE_JNI JNI_LIB = libsecp256k1_jni.la @@ -148,7 +150,7 @@ endif if USE_ECMULT_STATIC_PRECOMPUTATION CPPFLAGS_FOR_BUILD +=-I$(top_srcdir) -CFLAGS_FOR_BUILD += -Wall -Wextra -Wno-unused-function -DENABLE_MODULE_MUSIG +CFLAGS_FOR_BUILD += -Wall -Wextra -Wno-unused-function gen_context_OBJECTS = gen_context.o gen_context_BIN = gen_context$(BUILD_EXEEXT) From 4a3fc65631cece063441797421e0a685acd66133 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 07:15:31 -1100 Subject: [PATCH 096/390] Test --- configure.ac | 2 +- src/secp256k1/Makefile.am | 2 -- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/configure.ac b/configure.ac index 9a1a75f53..b3863f368 100644 --- a/configure.ac +++ b/configure.ac @@ -960,7 +960,7 @@ PKGCONFIG_LIBDIR_TEMP="$PKG_CONFIG_LIBDIR" unset PKG_CONFIG_LIBDIR PKG_CONFIG_LIBDIR="$PKGCONFIG_LIBDIR_TEMP" -ac_configure_args="${ac_configure_args} --disable-shared --with-pic --with-bignum=no --enable-module-recovery" +ac_configure_args="${ac_configure_args} -DENABLE_MODULE_MUSIG --disable-shared --with-pic --with-bignum=no --enable-module-recovery" AC_CONFIG_SUBDIRS([src/secp256k1 src/snark src/univalue src/cryptoconditions]) AC_OUTPUT diff --git a/src/secp256k1/Makefile.am b/src/secp256k1/Makefile.am index d8c03e96b..36d56a9ac 100644 --- a/src/secp256k1/Makefile.am +++ b/src/secp256k1/Makefile.am @@ -1,7 +1,5 @@ ACLOCAL_AMFLAGS = -I build-aux/m4 -CFLAGS += -DENABLE_MODULE_MUSIG - lib_LTLIBRARIES = libsecp256k1.la if USE_JNI JNI_LIB = libsecp256k1_jni.la From fbbd542ab8d55ae0a85020410685b8270fb73cc1 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 07:20:34 -1100 Subject: [PATCH 097/390] Test --- src/Makefile.am | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Makefile.am b/src/Makefile.am index 53331ee8f..03a34a140 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -67,7 +67,7 @@ LIBBITCOIN_WALLET=libbitcoin_wallet.a endif $(LIBSECP256K1): $(wildcard secp256k1/src/*) $(wildcard secp256k1/include/*) - $(AM_V_at)$(MAKE) $(AM_MAKEFLAGS) -C $(@D) $(@F) OPTFLAGS="-O2 -march=x86-64 -g " + $(AM_V_at)$(MAKE) $(AM_MAKEFLAGS) -C $(@D) $(@F) OPTFLAGS="-O2 -march=x86-64 -g -DENABLE_MODULE_MUSIG" LIBSNARK_CXXFLAGS = $(AM_CXXFLAGS) $(PIC_FLAGS) -DBINARY_OUTPUT -DNO_PT_COMPRESSION=1 -fstack-protector-all LIBSNARK_CONFIG_FLAGS = CURVE=ALT_BN128 NO_PROCPS=1 NO_DOCS=1 STATIC=1 NO_SUPERCOP=1 FEATUREFLAGS=-DMONTGOMERY_OUTPUT NO_COPY_DEPINST=1 NO_COMPILE_LIBGTEST=1 From e735d1e89cb567bacc01b387223abc7ce39e9a8f Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 07:26:23 -1100 Subject: [PATCH 098/390] Fixes --- configure.ac | 2 +- src/Makefile.am | 2 +- src/secp256k1/Makefile.am | 2 +- src/secp256k1/configure.ac | 1 - 4 files changed, 3 insertions(+), 4 deletions(-) diff --git a/configure.ac b/configure.ac index b3863f368..9a1a75f53 100644 --- a/configure.ac +++ b/configure.ac @@ -960,7 +960,7 @@ PKGCONFIG_LIBDIR_TEMP="$PKG_CONFIG_LIBDIR" unset PKG_CONFIG_LIBDIR PKG_CONFIG_LIBDIR="$PKGCONFIG_LIBDIR_TEMP" -ac_configure_args="${ac_configure_args} -DENABLE_MODULE_MUSIG --disable-shared --with-pic --with-bignum=no --enable-module-recovery" +ac_configure_args="${ac_configure_args} --disable-shared --with-pic --with-bignum=no --enable-module-recovery" AC_CONFIG_SUBDIRS([src/secp256k1 src/snark src/univalue src/cryptoconditions]) AC_OUTPUT diff --git a/src/Makefile.am b/src/Makefile.am index 03a34a140..53331ee8f 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -67,7 +67,7 @@ LIBBITCOIN_WALLET=libbitcoin_wallet.a endif $(LIBSECP256K1): $(wildcard secp256k1/src/*) $(wildcard secp256k1/include/*) - $(AM_V_at)$(MAKE) $(AM_MAKEFLAGS) -C $(@D) $(@F) OPTFLAGS="-O2 -march=x86-64 -g -DENABLE_MODULE_MUSIG" + $(AM_V_at)$(MAKE) $(AM_MAKEFLAGS) -C $(@D) $(@F) OPTFLAGS="-O2 -march=x86-64 -g " LIBSNARK_CXXFLAGS = $(AM_CXXFLAGS) $(PIC_FLAGS) -DBINARY_OUTPUT -DNO_PT_COMPRESSION=1 -fstack-protector-all LIBSNARK_CONFIG_FLAGS = CURVE=ALT_BN128 NO_PROCPS=1 NO_DOCS=1 STATIC=1 NO_SUPERCOP=1 FEATUREFLAGS=-DMONTGOMERY_OUTPUT NO_COPY_DEPINST=1 NO_COMPILE_LIBGTEST=1 diff --git a/src/secp256k1/Makefile.am b/src/secp256k1/Makefile.am index 36d56a9ac..5aa22dfd3 100644 --- a/src/secp256k1/Makefile.am +++ b/src/secp256k1/Makefile.am @@ -73,7 +73,7 @@ endif endif libsecp256k1_la_SOURCES = src/secp256k1.c -libsecp256k1_la_CPPFLAGS = -DSECP256K1_BUILD -I$(top_srcdir)/include -I$(top_srcdir)/src $(SECP_INCLUDES) +libsecp256k1_la_CPPFLAGS = -DENABLE_MODULE_MUSIG -DSECP256K1_BUILD -I$(top_srcdir)/include -I$(top_srcdir)/src $(SECP_INCLUDES) libsecp256k1_la_LIBADD = $(JNI_LIB) $(SECP_LIBS) $(COMMON_LIB) libsecp256k1_jni_la_SOURCES = src/java/org_bitcoin_NativeSecp256k1.c src/java/org_bitcoin_Secp256k1Context.c diff --git a/src/secp256k1/configure.ac b/src/secp256k1/configure.ac index 4c46f321f..e5fcbcb4e 100644 --- a/src/secp256k1/configure.ac +++ b/src/secp256k1/configure.ac @@ -479,7 +479,6 @@ AM_CONDITIONAL([USE_TESTS], [test x"$use_tests" != x"no"]) AM_CONDITIONAL([USE_EXHAUSTIVE_TESTS], [test x"$use_exhaustive_tests" != x"no"]) AM_CONDITIONAL([USE_BENCHMARK], [test x"$use_benchmark" = x"yes"]) AM_CONDITIONAL([USE_ECMULT_STATIC_PRECOMPUTATION], [test x"$set_precomp" = x"yes"]) -AM_CONDITIONAL([ENABLE_MODULE_MUSIG], [test x"$enable_module_musig" = x"yes"]) AM_CONDITIONAL([ENABLE_MODULE_ECDH], [test x"$enable_module_ecdh" = x"yes"]) AM_CONDITIONAL([ENABLE_MODULE_RECOVERY], [test x"$enable_module_recovery" = x"yes"]) AM_CONDITIONAL([USE_JNI], [test x"$use_jni" == x"yes"]) From f238a35805d13220e4c2727524b20dde08702576 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 07:29:14 -1100 Subject: [PATCH 099/390] Includes --- src/secp256k1/Makefile.am | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/secp256k1/Makefile.am b/src/secp256k1/Makefile.am index 5aa22dfd3..676415834 100644 --- a/src/secp256k1/Makefile.am +++ b/src/secp256k1/Makefile.am @@ -174,10 +174,10 @@ if ENABLE_MODULE_ECDH include src/modules/ecdh/Makefile.am.include endif -if ENABLE_MODULE_MUSIG +#if ENABLE_MODULE_MUSIG include src/modules/schnorrsig/Makefile.am.include include src/modules/musig/Makefile.am.include -endif +#endif if ENABLE_MODULE_RECOVERY include src/modules/recovery/Makefile.am.include From 00e80034568ba83651160988df86798d6cc9a0fd Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 07:32:52 -1100 Subject: [PATCH 100/390] Ifndef! --- src/secp256k1/src/ecmult.h | 2 +- src/secp256k1/src/scalar.h | 2 +- src/secp256k1/src/scalar_4x64.h | 2 +- src/secp256k1/src/scalar_4x64_impl.h | 2 +- src/secp256k1/src/scalar_8x32.h | 2 +- src/secp256k1/src/scalar_8x32_impl.h | 2 +- src/secp256k1/src/scalar_impl.h | 2 +- src/secp256k1/src/scalar_low.h | 2 +- src/secp256k1/src/scalar_low_impl.h | 2 +- 9 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/secp256k1/src/ecmult.h b/src/secp256k1/src/ecmult.h index 7fe619b21..4f12090a7 100644 --- a/src/secp256k1/src/ecmult.h +++ b/src/secp256k1/src/ecmult.h @@ -1,4 +1,4 @@ -#ifdef ENABLE_MODULE_MUSIG +#ifndef ENABLE_MODULE_MUSIG /********************************************************************** * Copyright (c) 2013, 2014 Pieter Wuille * diff --git a/src/secp256k1/src/scalar.h b/src/secp256k1/src/scalar.h index aa1cc3286..3213d302b 100644 --- a/src/secp256k1/src/scalar.h +++ b/src/secp256k1/src/scalar.h @@ -1,4 +1,4 @@ -#ifdef ENABLE_MODULE_MUSIG +#ifndef ENABLE_MODULE_MUSIG /********************************************************************** * Copyright (c) 2014 Pieter Wuille * diff --git a/src/secp256k1/src/scalar_4x64.h b/src/secp256k1/src/scalar_4x64.h index 1768966cf..68096f2a9 100644 --- a/src/secp256k1/src/scalar_4x64.h +++ b/src/secp256k1/src/scalar_4x64.h @@ -1,4 +1,4 @@ -#ifdef ENABLE_MODULE_MUSIG +#ifndef ENABLE_MODULE_MUSIG /********************************************************************** * Copyright (c) 2014 Pieter Wuille * diff --git a/src/secp256k1/src/scalar_4x64_impl.h b/src/secp256k1/src/scalar_4x64_impl.h index 192874529..a12c80626 100644 --- a/src/secp256k1/src/scalar_4x64_impl.h +++ b/src/secp256k1/src/scalar_4x64_impl.h @@ -1,4 +1,4 @@ -#ifdef ENABLE_MODULE_MUSIG +#ifndef ENABLE_MODULE_MUSIG /********************************************************************** * Copyright (c) 2013, 2014 Pieter Wuille * diff --git a/src/secp256k1/src/scalar_8x32.h b/src/secp256k1/src/scalar_8x32.h index 68a2c0428..8a630ac40 100644 --- a/src/secp256k1/src/scalar_8x32.h +++ b/src/secp256k1/src/scalar_8x32.h @@ -1,4 +1,4 @@ -#ifdef ENABLE_MODULE_MUSIG +#ifndef ENABLE_MODULE_MUSIG /********************************************************************** * Copyright (c) 2014 Pieter Wuille * diff --git a/src/secp256k1/src/scalar_8x32_impl.h b/src/secp256k1/src/scalar_8x32_impl.h index e1299cbaa..ff7bf5ee4 100644 --- a/src/secp256k1/src/scalar_8x32_impl.h +++ b/src/secp256k1/src/scalar_8x32_impl.h @@ -1,4 +1,4 @@ -#ifdef ENABLE_MODULE_MUSIG +#ifndef ENABLE_MODULE_MUSIG /********************************************************************** * Copyright (c) 2014 Pieter Wuille * diff --git a/src/secp256k1/src/scalar_impl.h b/src/secp256k1/src/scalar_impl.h index 494168e53..d69a94880 100644 --- a/src/secp256k1/src/scalar_impl.h +++ b/src/secp256k1/src/scalar_impl.h @@ -1,4 +1,4 @@ -#ifdef ENABLE_MODULE_MUSIG +#ifndef ENABLE_MODULE_MUSIG /********************************************************************** * Copyright (c) 2014 Pieter Wuille * diff --git a/src/secp256k1/src/scalar_low.h b/src/secp256k1/src/scalar_low.h index 2039aafc7..16b167f9c 100644 --- a/src/secp256k1/src/scalar_low.h +++ b/src/secp256k1/src/scalar_low.h @@ -1,4 +1,4 @@ -#ifdef ENABLE_MODULE_MUSIG +#ifndef ENABLE_MODULE_MUSIG /********************************************************************** * Copyright (c) 2015 Andrew Poelstra * diff --git a/src/secp256k1/src/scalar_low_impl.h b/src/secp256k1/src/scalar_low_impl.h index 99689a4fd..c6c65ff5b 100644 --- a/src/secp256k1/src/scalar_low_impl.h +++ b/src/secp256k1/src/scalar_low_impl.h @@ -1,4 +1,4 @@ -#ifdef ENABLE_MODULE_MUSIG +#ifndef ENABLE_MODULE_MUSIG /********************************************************************** * Copyright (c) 2015 Andrew Poelstra * From 26ed5d691909e90e7473b1ce87118bf67b7546c0 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 07:38:31 -1100 Subject: [PATCH 101/390] const_imple --- src/secp256k1/src/ecmult_const_impl.h | 264 ++++++++++++++++++++++++++ 1 file changed, 264 insertions(+) diff --git a/src/secp256k1/src/ecmult_const_impl.h b/src/secp256k1/src/ecmult_const_impl.h index 7d7a172b7..d8697e0e9 100644 --- a/src/secp256k1/src/ecmult_const_impl.h +++ b/src/secp256k1/src/ecmult_const_impl.h @@ -1,3 +1,5 @@ +#ifndef ENABLE_MODULE_MUSIG + /********************************************************************** * Copyright (c) 2015 Pieter Wuille, Andrew Poelstra * * Distributed under the MIT software license, see the accompanying * @@ -238,3 +240,265 @@ static void secp256k1_ecmult_const(secp256k1_gej *r, const secp256k1_ge *a, cons } #endif /* SECP256K1_ECMULT_CONST_IMPL_H */ + +#else +/********************************************************************** + * Copyright (c) 2015 Pieter Wuille, Andrew Poelstra * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_ECMULT_CONST_IMPL_H +#define SECP256K1_ECMULT_CONST_IMPL_H + +#include "scalar.h" +#include "group.h" +#include "ecmult_const.h" +#include "ecmult_impl.h" + +/* This is like `ECMULT_TABLE_GET_GE` but is constant time */ +#define ECMULT_CONST_TABLE_GET_GE(r,pre,n,w) do { \ +int m; \ +int abs_n = (n) * (((n) > 0) * 2 - 1); \ +int idx_n = abs_n / 2; \ +secp256k1_fe neg_y; \ +VERIFY_CHECK(((n) & 1) == 1); \ +VERIFY_CHECK((n) >= -((1 << ((w)-1)) - 1)); \ +VERIFY_CHECK((n) <= ((1 << ((w)-1)) - 1)); \ +VERIFY_SETUP(secp256k1_fe_clear(&(r)->x)); \ +VERIFY_SETUP(secp256k1_fe_clear(&(r)->y)); \ +for (m = 0; m < ECMULT_TABLE_SIZE(w); m++) { \ +/* This loop is used to avoid secret data in array indices. See +* the comment in ecmult_gen_impl.h for rationale. */ \ +secp256k1_fe_cmov(&(r)->x, &(pre)[m].x, m == idx_n); \ +secp256k1_fe_cmov(&(r)->y, &(pre)[m].y, m == idx_n); \ +} \ +(r)->infinity = 0; \ +secp256k1_fe_negate(&neg_y, &(r)->y, 1); \ +secp256k1_fe_cmov(&(r)->y, &neg_y, (n) != abs_n); \ +} while(0) + + +/** Convert a number to WNAF notation. + * The number becomes represented by sum(2^{wi} * wnaf[i], i=0..WNAF_SIZE(w)+1) - return_val. + * It has the following guarantees: + * - each wnaf[i] an odd integer between -(1 << w) and (1 << w) + * - each wnaf[i] is nonzero + * - the number of words set is always WNAF_SIZE(w) + 1 + * + * Adapted from `The Width-w NAF Method Provides Small Memory and Fast Elliptic Scalar + * Multiplications Secure against Side Channel Attacks`, Okeya and Tagaki. M. Joye (Ed.) + * CT-RSA 2003, LNCS 2612, pp. 328-443, 2003. Springer-Verlagy Berlin Heidelberg 2003 + * + * Numbers reference steps of `Algorithm SPA-resistant Width-w NAF with Odd Scalar` on pp. 335 + */ +static int secp256k1_wnaf_const(int *wnaf, secp256k1_scalar s, int w, int size) { + int global_sign; + int skew = 0; + int word = 0; + + /* 1 2 3 */ + int u_last; + int u; + + int flip; + int bit; + secp256k1_scalar neg_s; + int not_neg_one; + /* Note that we cannot handle even numbers by negating them to be odd, as is + * done in other implementations, since if our scalars were specified to have + * width < 256 for performance reasons, their negations would have width 256 + * and we'd lose any performance benefit. Instead, we use a technique from + * Section 4.2 of the Okeya/Tagaki paper, which is to add either 1 (for even) + * or 2 (for odd) to the number we are encoding, returning a skew value indicating + * this, and having the caller compensate after doing the multiplication. + * + * In fact, we _do_ want to negate numbers to minimize their bit-lengths (and in + * particular, to ensure that the outputs from the endomorphism-split fit into + * 128 bits). If we negate, the parity of our number flips, inverting which of + * {1, 2} we want to add to the scalar when ensuring that it's odd. Further + * complicating things, -1 interacts badly with `secp256k1_scalar_cadd_bit` and + * we need to special-case it in this logic. */ + flip = secp256k1_scalar_is_high(&s); + /* We add 1 to even numbers, 2 to odd ones, noting that negation flips parity */ + bit = flip ^ !secp256k1_scalar_is_even(&s); + /* We check for negative one, since adding 2 to it will cause an overflow */ + secp256k1_scalar_negate(&neg_s, &s); + not_neg_one = !secp256k1_scalar_is_one(&neg_s); + secp256k1_scalar_cadd_bit(&s, bit, not_neg_one); + /* If we had negative one, flip == 1, s.d[0] == 0, bit == 1, so caller expects + * that we added two to it and flipped it. In fact for -1 these operations are + * identical. We only flipped, but since skewing is required (in the sense that + * the skew must be 1 or 2, never zero) and flipping is not, we need to change + * our flags to claim that we only skewed. */ + global_sign = secp256k1_scalar_cond_negate(&s, flip); + global_sign *= not_neg_one * 2 - 1; + skew = 1 << bit; + + /* 4 */ + u_last = secp256k1_scalar_shr_int(&s, w); + while (word * w < size) { + int sign; + int even; + + /* 4.1 4.4 */ + u = secp256k1_scalar_shr_int(&s, w); + /* 4.2 */ + even = ((u & 1) == 0); + sign = 2 * (u_last > 0) - 1; + u += sign * even; + u_last -= sign * even * (1 << w); + + /* 4.3, adapted for global sign change */ + wnaf[word++] = u_last * global_sign; + + u_last = u; + } + wnaf[word] = u * global_sign; + + VERIFY_CHECK(secp256k1_scalar_is_zero(&s)); + VERIFY_CHECK(word == WNAF_SIZE_BITS(size, w)); + return skew; +} + +static void secp256k1_ecmult_const(secp256k1_gej *r, const secp256k1_ge *a, const secp256k1_scalar *scalar, int size) { + secp256k1_ge pre_a[ECMULT_TABLE_SIZE(WINDOW_A)]; + secp256k1_ge tmpa; + secp256k1_fe Z; + + int skew_1; +#ifdef USE_ENDOMORPHISM + secp256k1_ge pre_a_lam[ECMULT_TABLE_SIZE(WINDOW_A)]; + int wnaf_lam[1 + WNAF_SIZE(WINDOW_A - 1)]; + int skew_lam; + secp256k1_scalar q_1, q_lam; +#endif + int wnaf_1[1 + WNAF_SIZE(WINDOW_A - 1)]; + + int i; + secp256k1_scalar sc = *scalar; + + /* build wnaf representation for q. */ + int rsize = size; +#ifdef USE_ENDOMORPHISM + if (size > 128) { + rsize = 128; + /* split q into q_1 and q_lam (where q = q_1 + q_lam*lambda, and q_1 and q_lam are ~128 bit) */ + secp256k1_scalar_split_lambda(&q_1, &q_lam, &sc); + skew_1 = secp256k1_wnaf_const(wnaf_1, q_1, WINDOW_A - 1, 128); + skew_lam = secp256k1_wnaf_const(wnaf_lam, q_lam, WINDOW_A - 1, 128); + } else +#endif + { + skew_1 = secp256k1_wnaf_const(wnaf_1, sc, WINDOW_A - 1, size); +#ifdef USE_ENDOMORPHISM + skew_lam = 0; +#endif + } + + /* Calculate odd multiples of a. + * All multiples are brought to the same Z 'denominator', which is stored + * in Z. Due to secp256k1' isomorphism we can do all operations pretending + * that the Z coordinate was 1, use affine addition formulae, and correct + * the Z coordinate of the result once at the end. + */ + secp256k1_gej_set_ge(r, a); + secp256k1_ecmult_odd_multiples_table_globalz_windowa(pre_a, &Z, r); + for (i = 0; i < ECMULT_TABLE_SIZE(WINDOW_A); i++) { + secp256k1_fe_normalize_weak(&pre_a[i].y); + } +#ifdef USE_ENDOMORPHISM + if (size > 128) { + for (i = 0; i < ECMULT_TABLE_SIZE(WINDOW_A); i++) { + secp256k1_ge_mul_lambda(&pre_a_lam[i], &pre_a[i]); + } + } +#endif + + /* first loop iteration (separated out so we can directly set r, rather + * than having it start at infinity, get doubled several times, then have + * its new value added to it) */ + i = wnaf_1[WNAF_SIZE_BITS(rsize, WINDOW_A - 1)]; + VERIFY_CHECK(i != 0); + ECMULT_CONST_TABLE_GET_GE(&tmpa, pre_a, i, WINDOW_A); + secp256k1_gej_set_ge(r, &tmpa); +#ifdef USE_ENDOMORPHISM + if (size > 128) { + i = wnaf_lam[WNAF_SIZE_BITS(rsize, WINDOW_A - 1)]; + VERIFY_CHECK(i != 0); + ECMULT_CONST_TABLE_GET_GE(&tmpa, pre_a_lam, i, WINDOW_A); + secp256k1_gej_add_ge(r, r, &tmpa); + } +#endif + /* remaining loop iterations */ + for (i = WNAF_SIZE_BITS(rsize, WINDOW_A - 1) - 1; i >= 0; i--) { + int n; + int j; + for (j = 0; j < WINDOW_A - 1; ++j) { + secp256k1_gej_double_nonzero(r, r, NULL); + } + + n = wnaf_1[i]; + ECMULT_CONST_TABLE_GET_GE(&tmpa, pre_a, n, WINDOW_A); + VERIFY_CHECK(n != 0); + secp256k1_gej_add_ge(r, r, &tmpa); +#ifdef USE_ENDOMORPHISM + if (size > 128) { + n = wnaf_lam[i]; + ECMULT_CONST_TABLE_GET_GE(&tmpa, pre_a_lam, n, WINDOW_A); + VERIFY_CHECK(n != 0); + secp256k1_gej_add_ge(r, r, &tmpa); + } +#endif + } + + secp256k1_fe_mul(&r->z, &r->z, &Z); + + { + /* Correct for wNAF skew */ + secp256k1_ge correction = *a; + secp256k1_ge_storage correction_1_stor; +#ifdef USE_ENDOMORPHISM + secp256k1_ge_storage correction_lam_stor; +#endif + secp256k1_ge_storage a2_stor; + secp256k1_gej tmpj; + secp256k1_gej_set_ge(&tmpj, &correction); + secp256k1_gej_double_var(&tmpj, &tmpj, NULL); + secp256k1_ge_set_gej(&correction, &tmpj); + secp256k1_ge_to_storage(&correction_1_stor, a); +#ifdef USE_ENDOMORPHISM + if (size > 128) { + secp256k1_ge_to_storage(&correction_lam_stor, a); + } +#endif + secp256k1_ge_to_storage(&a2_stor, &correction); + + /* For odd numbers this is 2a (so replace it), for even ones a (so no-op) */ + secp256k1_ge_storage_cmov(&correction_1_stor, &a2_stor, skew_1 == 2); +#ifdef USE_ENDOMORPHISM + if (size > 128) { + secp256k1_ge_storage_cmov(&correction_lam_stor, &a2_stor, skew_lam == 2); + } +#endif + + /* Apply the correction */ + secp256k1_ge_from_storage(&correction, &correction_1_stor); + secp256k1_ge_neg(&correction, &correction); + secp256k1_gej_add_ge(r, r, &correction); + +#ifdef USE_ENDOMORPHISM + if (size > 128) { + secp256k1_ge_from_storage(&correction, &correction_lam_stor); + secp256k1_ge_neg(&correction, &correction); + secp256k1_ge_mul_lambda(&correction, &correction); + secp256k1_gej_add_ge(r, r, &correction); + } +#endif + } +} + +#endif /* SECP256K1_ECMULT_CONST_IMPL_H */ + +#endif + From 0765b151fe12438759076262be9fdc5c3b45466d Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 07:44:44 -1100 Subject: [PATCH 102/390] ,256 --- .../src/include/secp256k1/src/ecmult_const.h | 24 +++++++++++++++++++ src/secp256k1/src/modules/ecdh/main_impl.h | 2 +- src/secp256k1/src/tests.c | 18 +++++++------- src/secp256k1/src/tests_exhaustive.c | 2 +- 4 files changed, 35 insertions(+), 11 deletions(-) diff --git a/src/cryptoconditions/src/include/secp256k1/src/ecmult_const.h b/src/cryptoconditions/src/include/secp256k1/src/ecmult_const.h index 72bf7d758..bdb9ae43a 100644 --- a/src/cryptoconditions/src/include/secp256k1/src/ecmult_const.h +++ b/src/cryptoconditions/src/include/secp256k1/src/ecmult_const.h @@ -1,3 +1,5 @@ +#ifndef ENABLE_MODULE_MUSIG + /********************************************************************** * Copyright (c) 2015 Andrew Poelstra * * Distributed under the MIT software license, see the accompanying * @@ -13,3 +15,25 @@ static void secp256k1_ecmult_const(secp256k1_gej *r, const secp256k1_ge *a, const secp256k1_scalar *q); #endif /* SECP256K1_ECMULT_CONST_H */ + +#else + +/********************************************************************** + * Copyright (c) 2015 Andrew Poelstra * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_ECMULT_CONST_H +#define SECP256K1_ECMULT_CONST_H + +#include "scalar.h" +#include "group.h" + +/* Here `bits` should be set to the maximum bitlength of the _absolute value_ of `q`, plus + * one because we internally sometimes add 2 to the number during the WNAF conversion. */ +static void secp256k1_ecmult_const(secp256k1_gej *r, const secp256k1_ge *a, const secp256k1_scalar *q, int bits); + + +#endif + diff --git a/src/secp256k1/src/modules/ecdh/main_impl.h b/src/secp256k1/src/modules/ecdh/main_impl.h index bd8739eeb..74332ba1d 100644 --- a/src/secp256k1/src/modules/ecdh/main_impl.h +++ b/src/secp256k1/src/modules/ecdh/main_impl.h @@ -30,7 +30,7 @@ int secp256k1_ecdh(const secp256k1_context* ctx, unsigned char *result, const se unsigned char y[1]; secp256k1_sha256 sha; - secp256k1_ecmult_const(&res, &pt, &s); + secp256k1_ecmult_const(&res, &pt, &s,256); secp256k1_ge_set_gej(&pt, &res); /* Compute a hash of the point in compressed form * Note we cannot use secp256k1_eckey_pubkey_serialize here since it does not diff --git a/src/secp256k1/src/tests.c b/src/secp256k1/src/tests.c index f307b99d5..345fb0bdf 100644 --- a/src/secp256k1/src/tests.c +++ b/src/secp256k1/src/tests.c @@ -2405,7 +2405,7 @@ void ecmult_const_random_mult(void) { 0xb84e4e1b, 0xfb77e21f, 0x96baae2a, 0x63dec956 ); secp256k1_gej b; - secp256k1_ecmult_const(&b, &a, &xn); + secp256k1_ecmult_const(&b, &a, &xn,256); CHECK(secp256k1_ge_is_valid_var(&a)); ge_equals_gej(&expected_b, &b); @@ -2421,12 +2421,12 @@ void ecmult_const_commutativity(void) { random_scalar_order_test(&a); random_scalar_order_test(&b); - secp256k1_ecmult_const(&res1, &secp256k1_ge_const_g, &a); - secp256k1_ecmult_const(&res2, &secp256k1_ge_const_g, &b); + secp256k1_ecmult_const(&res1, &secp256k1_ge_const_g, &a,256); + secp256k1_ecmult_const(&res2, &secp256k1_ge_const_g, &b,256); secp256k1_ge_set_gej(&mid1, &res1); secp256k1_ge_set_gej(&mid2, &res2); - secp256k1_ecmult_const(&res1, &mid1, &b); - secp256k1_ecmult_const(&res2, &mid2, &a); + secp256k1_ecmult_const(&res1, &mid1, &b,256); + secp256k1_ecmult_const(&res2, &mid2, &a,256); secp256k1_ge_set_gej(&mid1, &res1); secp256k1_ge_set_gej(&mid2, &res2); ge_equals_ge(&mid1, &mid2); @@ -2442,13 +2442,13 @@ void ecmult_const_mult_zero_one(void) { secp256k1_scalar_negate(&negone, &one); random_group_element_test(&point); - secp256k1_ecmult_const(&res1, &point, &zero); + secp256k1_ecmult_const(&res1, &point, &zero,256); secp256k1_ge_set_gej(&res2, &res1); CHECK(secp256k1_ge_is_infinity(&res2)); - secp256k1_ecmult_const(&res1, &point, &one); + secp256k1_ecmult_const(&res1, &point, &one,256); secp256k1_ge_set_gej(&res2, &res1); ge_equals_ge(&res2, &point); - secp256k1_ecmult_const(&res1, &point, &negone); + secp256k1_ecmult_const(&res1, &point, &negone,256); secp256k1_gej_neg(&res1, &res1); secp256k1_ge_set_gej(&res2, &res1); ge_equals_ge(&res2, &point); @@ -2474,7 +2474,7 @@ void ecmult_const_chain_multiply(void) { for (i = 0; i < 100; ++i) { secp256k1_ge tmp; secp256k1_ge_set_gej(&tmp, &point); - secp256k1_ecmult_const(&point, &tmp, &scalar); + secp256k1_ecmult_const(&point, &tmp, &scalar,256); } secp256k1_ge_set_gej(&res, &point); ge_equals_gej(&res, &expected_point); diff --git a/src/secp256k1/src/tests_exhaustive.c b/src/secp256k1/src/tests_exhaustive.c index b040bb073..1e58c3b5f 100644 --- a/src/secp256k1/src/tests_exhaustive.c +++ b/src/secp256k1/src/tests_exhaustive.c @@ -174,7 +174,7 @@ void test_exhaustive_ecmult(const secp256k1_context *ctx, const secp256k1_ge *gr ge_equals_gej(&group[(i * r_log + j) % order], &tmp); if (i > 0) { - secp256k1_ecmult_const(&tmp, &group[i], &ng); + secp256k1_ecmult_const(&tmp, &group[i], &ng,256); ge_equals_gej(&group[(i * j) % order], &tmp); } } From 1be8baf63beed94548f05f6fa59ac020244cc16e Mon Sep 17 00:00:00 2001 From: ca333 Date: Tue, 19 Feb 2019 19:44:50 +0100 Subject: [PATCH 103/390] add ifndef WIN --- src/cc/rogue/cursesd.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/cc/rogue/cursesd.c b/src/cc/rogue/cursesd.c index 202cc4acb..6c295fc94 100644 --- a/src/cc/rogue/cursesd.c +++ b/src/cc/rogue/cursesd.c @@ -410,11 +410,13 @@ int32_t wgetnstr(WINDOW *win, char *str, int32_t n) // stub return(0); } +#ifndef __MINGW32__ int32_t getch(void) { fprintf(stderr,"unexpected and unsupported call to getch\n"); return(0); } +#endif int32_t md_readchar(void) { From 3fcb317a842cdec6c36dc392a7f28b57f9f89078 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 07:46:50 -1100 Subject: [PATCH 104/390] fix --- src/secp256k1/src/ecmult_const.h | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/src/secp256k1/src/ecmult_const.h b/src/secp256k1/src/ecmult_const.h index 72bf7d758..0d32fa389 100644 --- a/src/secp256k1/src/ecmult_const.h +++ b/src/secp256k1/src/ecmult_const.h @@ -1,3 +1,5 @@ +#ifndef ENABLE_MODULE_MUSIG + /********************************************************************** * Copyright (c) 2015 Andrew Poelstra * * Distributed under the MIT software license, see the accompanying * @@ -13,3 +15,24 @@ static void secp256k1_ecmult_const(secp256k1_gej *r, const secp256k1_ge *a, const secp256k1_scalar *q); #endif /* SECP256K1_ECMULT_CONST_H */ + +#else +/********************************************************************** + * Copyright (c) 2015 Andrew Poelstra * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_ECMULT_CONST_H +#define SECP256K1_ECMULT_CONST_H + +#include "scalar.h" +#include "group.h" + +/* Here `bits` should be set to the maximum bitlength of the _absolute value_ of `q`, plus + * one because we internally sometimes add 2 to the number during the WNAF conversion. */ +static void secp256k1_ecmult_const(secp256k1_gej *r, const secp256k1_ge *a, const secp256k1_scalar *q, int bits); + +#endif /* SECP256K1_ECMULT_CONST_H */ +#endif + From 093421dc4e3143809f9798969e556d262bbb2eac Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 07:49:06 -1100 Subject: [PATCH 105/390] Undo --- src/secp256k1/src/scalar_impl.h | 338 -------------------------------- 1 file changed, 338 deletions(-) diff --git a/src/secp256k1/src/scalar_impl.h b/src/secp256k1/src/scalar_impl.h index d69a94880..dec541aed 100644 --- a/src/secp256k1/src/scalar_impl.h +++ b/src/secp256k1/src/scalar_impl.h @@ -1,4 +1,3 @@ -#ifndef ENABLE_MODULE_MUSIG /********************************************************************** * Copyright (c) 2014 Pieter Wuille * @@ -334,340 +333,3 @@ static void secp256k1_scalar_split_lambda(secp256k1_scalar *r1, secp256k1_scalar #endif /* SECP256K1_SCALAR_IMPL_H */ - -#else -/********************************************************************** - * 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 "group.h" -#include "scalar.h" - -#if defined HAVE_CONFIG_H -#include "libsecp256k1-config.h" -#endif - -#if defined(EXHAUSTIVE_TEST_ORDER) -#include "scalar_low_impl.h" -#elif 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 *r, const secp256k1_scalar *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 *r) { -#if defined(EXHAUSTIVE_TEST_ORDER) - static const unsigned char order[32] = { - 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,EXHAUSTIVE_TEST_ORDER - }; -#else - 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 - }; -#endif - secp256k1_num_set_bin(r, order, 32); -} -#endif - -static void secp256k1_scalar_inverse(secp256k1_scalar *r, const secp256k1_scalar *x) { -#if defined(EXHAUSTIVE_TEST_ORDER) - int i; - *r = 0; - for (i = 0; i < EXHAUSTIVE_TEST_ORDER; i++) - if ((i * *x) % EXHAUSTIVE_TEST_ORDER == 1) - *r = i; - /* If this VERIFY_CHECK triggers we were given a noninvertible scalar (and thus - * have a composite group order; fix it in exhaustive_tests.c). */ - VERIFY_CHECK(*r != 0); -} -#else -secp256k1_scalar *t; -int i; -/* First compute xN as x ^ (2^N - 1) for some values of N, - * and uM as x ^ M for some values of M. */ -secp256k1_scalar x2, x3, x6, x8, x14, x28, x56, x112, x126; -secp256k1_scalar u2, u5, u9, u11, u13; - -secp256k1_scalar_sqr(&u2, x); -secp256k1_scalar_mul(&x2, &u2, x); -secp256k1_scalar_mul(&u5, &u2, &x2); -secp256k1_scalar_mul(&x3, &u5, &u2); -secp256k1_scalar_mul(&u9, &x3, &u2); -secp256k1_scalar_mul(&u11, &u9, &u2); -secp256k1_scalar_mul(&u13, &u11, &u2); - -secp256k1_scalar_sqr(&x6, &u13); -secp256k1_scalar_sqr(&x6, &x6); -secp256k1_scalar_mul(&x6, &x6, &u11); - -secp256k1_scalar_sqr(&x8, &x6); -secp256k1_scalar_sqr(&x8, &x8); -secp256k1_scalar_mul(&x8, &x8, &x2); - -secp256k1_scalar_sqr(&x14, &x8); -for (i = 0; i < 5; i++) { - secp256k1_scalar_sqr(&x14, &x14); -} -secp256k1_scalar_mul(&x14, &x14, &x6); - -secp256k1_scalar_sqr(&x28, &x14); -for (i = 0; i < 13; i++) { - secp256k1_scalar_sqr(&x28, &x28); -} -secp256k1_scalar_mul(&x28, &x28, &x14); - -secp256k1_scalar_sqr(&x56, &x28); -for (i = 0; i < 27; i++) { - secp256k1_scalar_sqr(&x56, &x56); -} -secp256k1_scalar_mul(&x56, &x56, &x28); - -secp256k1_scalar_sqr(&x112, &x56); -for (i = 0; i < 55; i++) { - secp256k1_scalar_sqr(&x112, &x112); -} -secp256k1_scalar_mul(&x112, &x112, &x56); - -secp256k1_scalar_sqr(&x126, &x112); -for (i = 0; i < 13; i++) { - secp256k1_scalar_sqr(&x126, &x126); -} -secp256k1_scalar_mul(&x126, &x126, &x14); - -/* Then accumulate the final result (t starts at x126). */ -t = &x126; -for (i = 0; i < 3; i++) { - secp256k1_scalar_sqr(t, t); -} -secp256k1_scalar_mul(t, t, &u5); /* 101 */ -for (i = 0; i < 4; i++) { /* 0 */ - 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, &u5); /* 101 */ -for (i = 0; i < 5; i++) { /* 0 */ - secp256k1_scalar_sqr(t, t); -} -secp256k1_scalar_mul(t, t, &u11); /* 1011 */ -for (i = 0; i < 4; i++) { - secp256k1_scalar_sqr(t, t); -} -secp256k1_scalar_mul(t, t, &u11); /* 1011 */ -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 < 6; i++) { /* 00 */ - secp256k1_scalar_sqr(t, t); -} -secp256k1_scalar_mul(t, t, &u13); /* 1101 */ -for (i = 0; i < 4; i++) { /* 0 */ - secp256k1_scalar_sqr(t, t); -} -secp256k1_scalar_mul(t, t, &u5); /* 101 */ -for (i = 0; i < 3; i++) { - secp256k1_scalar_sqr(t, t); -} -secp256k1_scalar_mul(t, t, &x3); /* 111 */ -for (i = 0; i < 5; i++) { /* 0 */ - secp256k1_scalar_sqr(t, t); -} -secp256k1_scalar_mul(t, t, &u9); /* 1001 */ -for (i = 0; i < 6; i++) { /* 000 */ - secp256k1_scalar_sqr(t, t); -} -secp256k1_scalar_mul(t, t, &u5); /* 101 */ -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 < 5; i++) { /* 0 */ - secp256k1_scalar_sqr(t, t); -} -secp256k1_scalar_mul(t, t, &u9); /* 1001 */ -for (i = 0; i < 6; i++) { /* 00 */ - secp256k1_scalar_sqr(t, t); -} -secp256k1_scalar_mul(t, t, &u11); /* 1011 */ -for (i = 0; i < 4; i++) { - secp256k1_scalar_sqr(t, t); -} -secp256k1_scalar_mul(t, t, &u13); /* 1101 */ -for (i = 0; i < 5; i++) { - secp256k1_scalar_sqr(t, t); -} -secp256k1_scalar_mul(t, t, &x2); /* 11 */ -for (i = 0; i < 6; i++) { /* 00 */ - secp256k1_scalar_sqr(t, t); -} -secp256k1_scalar_mul(t, t, &u13); /* 1101 */ -for (i = 0; i < 10; i++) { /* 000000 */ - secp256k1_scalar_sqr(t, t); -} -secp256k1_scalar_mul(t, t, &u13); /* 1101 */ -for (i = 0; i < 4; i++) { - secp256k1_scalar_sqr(t, t); -} -secp256k1_scalar_mul(t, t, &u9); /* 1001 */ -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 */ -} - -SECP256K1_INLINE static int secp256k1_scalar_is_even(const secp256k1_scalar *a) { - return !(a->d[0] & 1); -} -#endif - -static void secp256k1_scalar_inverse_var(secp256k1_scalar *r, const secp256k1_scalar *x) { -#if defined(USE_SCALAR_INV_BUILTIN) - secp256k1_scalar_inverse(r, x); -#elif defined(USE_SCALAR_INV_NUM) - unsigned char b[32]; - secp256k1_num n, m; - secp256k1_scalar t = *x; - secp256k1_scalar_get_b32(b, &t); - 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); - /* Verify that the inverse was computed correctly, without GMP code. */ - secp256k1_scalar_mul(&t, &t, r); - CHECK(secp256k1_scalar_is_one(&t)); -#else -#error "Please select scalar inverse implementation" -#endif -} - -#ifdef USE_ENDOMORPHISM -#if defined(EXHAUSTIVE_TEST_ORDER) -/** - * Find k1 and k2 given k, such that k1 + k2 * lambda == k mod n; unlike in the - * full case we don't bother making k1 and k2 be small, we just want them to be - * nontrivial to get full test coverage for the exhaustive tests. We therefore - * (arbitrarily) set k2 = k + 5 and k1 = k - k2 * lambda. - */ -static void secp256k1_scalar_split_lambda(secp256k1_scalar *r1, secp256k1_scalar *r2, const secp256k1_scalar *a) { - *r2 = (*a + 5) % EXHAUSTIVE_TEST_ORDER; - *r1 = (*a + (EXHAUSTIVE_TEST_ORDER - *r2) * EXHAUSTIVE_TEST_LAMBDA) % EXHAUSTIVE_TEST_ORDER; -} -#else -/** - * 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(secp256k1_scalar *r1, secp256k1_scalar *r2, const secp256k1_scalar *a) { - secp256k1_scalar c1, c2; - static const secp256k1_scalar minus_lambda = SECP256K1_SCALAR_CONST( - 0xAC9C52B3UL, 0x3FA3CF1FUL, 0x5AD9E3FDUL, 0x77ED9BA4UL, - 0xA880B9FCUL, 0x8EC739C2UL, 0xE0CFC810UL, 0xB51283CFUL - ); - static const secp256k1_scalar minus_b1 = SECP256K1_SCALAR_CONST( - 0x00000000UL, 0x00000000UL, 0x00000000UL, 0x00000000UL, - 0xE4437ED6UL, 0x010E8828UL, 0x6F547FA9UL, 0x0ABFE4C3UL - ); - static const secp256k1_scalar minus_b2 = SECP256K1_SCALAR_CONST( - 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFEUL, - 0x8A280AC5UL, 0x0774346DUL, 0xD765CDA8UL, 0x3DB1562CUL - ); - static const secp256k1_scalar g1 = SECP256K1_SCALAR_CONST( - 0x00000000UL, 0x00000000UL, 0x00000000UL, 0x00003086UL, - 0xD221A7D4UL, 0x6BCDE86CUL, 0x90E49284UL, 0xEB153DABUL - ); - static const secp256k1_scalar g2 = SECP256K1_SCALAR_CONST( - 0x00000000UL, 0x00000000UL, 0x00000000UL, 0x0000E443UL, - 0x7ED6010EUL, 0x88286F54UL, 0x7FA90ABFUL, 0xE4C42212UL - ); - VERIFY_CHECK(r1 != a); - VERIFY_CHECK(r2 != a); - /* these _var calls are constant time since the shift amount is constant */ - 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 - -#endif /* SECP256K1_SCALAR_IMPL_H */ -#endif - From 56837e817483890243612313293ec76a809f2627 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 07:52:56 -1100 Subject: [PATCH 106/390] -xxx --- src/secp256k1/src/scalar_4x64_impl.h | 2 +- src/secp256k1/src/scalar_impl.h | 338 +++++++++++++++++++++++++++ 2 files changed, 339 insertions(+), 1 deletion(-) diff --git a/src/secp256k1/src/scalar_4x64_impl.h b/src/secp256k1/src/scalar_4x64_impl.h index a12c80626..b1b62ac1f 100644 --- a/src/secp256k1/src/scalar_4x64_impl.h +++ b/src/secp256k1/src/scalar_4x64_impl.h @@ -2001,6 +2001,6 @@ static void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2 #undef LE32 #endif /* SECP256K1_SCALAR_REPR_IMPL_H */ -xxx + #endif diff --git a/src/secp256k1/src/scalar_impl.h b/src/secp256k1/src/scalar_impl.h index dec541aed..d69a94880 100644 --- a/src/secp256k1/src/scalar_impl.h +++ b/src/secp256k1/src/scalar_impl.h @@ -1,3 +1,4 @@ +#ifndef ENABLE_MODULE_MUSIG /********************************************************************** * Copyright (c) 2014 Pieter Wuille * @@ -333,3 +334,340 @@ static void secp256k1_scalar_split_lambda(secp256k1_scalar *r1, secp256k1_scalar #endif /* SECP256K1_SCALAR_IMPL_H */ + +#else +/********************************************************************** + * 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 "group.h" +#include "scalar.h" + +#if defined HAVE_CONFIG_H +#include "libsecp256k1-config.h" +#endif + +#if defined(EXHAUSTIVE_TEST_ORDER) +#include "scalar_low_impl.h" +#elif 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 *r, const secp256k1_scalar *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 *r) { +#if defined(EXHAUSTIVE_TEST_ORDER) + static const unsigned char order[32] = { + 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,EXHAUSTIVE_TEST_ORDER + }; +#else + 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 + }; +#endif + secp256k1_num_set_bin(r, order, 32); +} +#endif + +static void secp256k1_scalar_inverse(secp256k1_scalar *r, const secp256k1_scalar *x) { +#if defined(EXHAUSTIVE_TEST_ORDER) + int i; + *r = 0; + for (i = 0; i < EXHAUSTIVE_TEST_ORDER; i++) + if ((i * *x) % EXHAUSTIVE_TEST_ORDER == 1) + *r = i; + /* If this VERIFY_CHECK triggers we were given a noninvertible scalar (and thus + * have a composite group order; fix it in exhaustive_tests.c). */ + VERIFY_CHECK(*r != 0); +} +#else +secp256k1_scalar *t; +int i; +/* First compute xN as x ^ (2^N - 1) for some values of N, + * and uM as x ^ M for some values of M. */ +secp256k1_scalar x2, x3, x6, x8, x14, x28, x56, x112, x126; +secp256k1_scalar u2, u5, u9, u11, u13; + +secp256k1_scalar_sqr(&u2, x); +secp256k1_scalar_mul(&x2, &u2, x); +secp256k1_scalar_mul(&u5, &u2, &x2); +secp256k1_scalar_mul(&x3, &u5, &u2); +secp256k1_scalar_mul(&u9, &x3, &u2); +secp256k1_scalar_mul(&u11, &u9, &u2); +secp256k1_scalar_mul(&u13, &u11, &u2); + +secp256k1_scalar_sqr(&x6, &u13); +secp256k1_scalar_sqr(&x6, &x6); +secp256k1_scalar_mul(&x6, &x6, &u11); + +secp256k1_scalar_sqr(&x8, &x6); +secp256k1_scalar_sqr(&x8, &x8); +secp256k1_scalar_mul(&x8, &x8, &x2); + +secp256k1_scalar_sqr(&x14, &x8); +for (i = 0; i < 5; i++) { + secp256k1_scalar_sqr(&x14, &x14); +} +secp256k1_scalar_mul(&x14, &x14, &x6); + +secp256k1_scalar_sqr(&x28, &x14); +for (i = 0; i < 13; i++) { + secp256k1_scalar_sqr(&x28, &x28); +} +secp256k1_scalar_mul(&x28, &x28, &x14); + +secp256k1_scalar_sqr(&x56, &x28); +for (i = 0; i < 27; i++) { + secp256k1_scalar_sqr(&x56, &x56); +} +secp256k1_scalar_mul(&x56, &x56, &x28); + +secp256k1_scalar_sqr(&x112, &x56); +for (i = 0; i < 55; i++) { + secp256k1_scalar_sqr(&x112, &x112); +} +secp256k1_scalar_mul(&x112, &x112, &x56); + +secp256k1_scalar_sqr(&x126, &x112); +for (i = 0; i < 13; i++) { + secp256k1_scalar_sqr(&x126, &x126); +} +secp256k1_scalar_mul(&x126, &x126, &x14); + +/* Then accumulate the final result (t starts at x126). */ +t = &x126; +for (i = 0; i < 3; i++) { + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u5); /* 101 */ +for (i = 0; i < 4; i++) { /* 0 */ + 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, &u5); /* 101 */ +for (i = 0; i < 5; i++) { /* 0 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u11); /* 1011 */ +for (i = 0; i < 4; i++) { + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u11); /* 1011 */ +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 < 6; i++) { /* 00 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u13); /* 1101 */ +for (i = 0; i < 4; i++) { /* 0 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u5); /* 101 */ +for (i = 0; i < 3; i++) { + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &x3); /* 111 */ +for (i = 0; i < 5; i++) { /* 0 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u9); /* 1001 */ +for (i = 0; i < 6; i++) { /* 000 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u5); /* 101 */ +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 < 5; i++) { /* 0 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u9); /* 1001 */ +for (i = 0; i < 6; i++) { /* 00 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u11); /* 1011 */ +for (i = 0; i < 4; i++) { + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u13); /* 1101 */ +for (i = 0; i < 5; i++) { + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &x2); /* 11 */ +for (i = 0; i < 6; i++) { /* 00 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u13); /* 1101 */ +for (i = 0; i < 10; i++) { /* 000000 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u13); /* 1101 */ +for (i = 0; i < 4; i++) { + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u9); /* 1001 */ +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 */ +} + +SECP256K1_INLINE static int secp256k1_scalar_is_even(const secp256k1_scalar *a) { + return !(a->d[0] & 1); +} +#endif + +static void secp256k1_scalar_inverse_var(secp256k1_scalar *r, const secp256k1_scalar *x) { +#if defined(USE_SCALAR_INV_BUILTIN) + secp256k1_scalar_inverse(r, x); +#elif defined(USE_SCALAR_INV_NUM) + unsigned char b[32]; + secp256k1_num n, m; + secp256k1_scalar t = *x; + secp256k1_scalar_get_b32(b, &t); + 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); + /* Verify that the inverse was computed correctly, without GMP code. */ + secp256k1_scalar_mul(&t, &t, r); + CHECK(secp256k1_scalar_is_one(&t)); +#else +#error "Please select scalar inverse implementation" +#endif +} + +#ifdef USE_ENDOMORPHISM +#if defined(EXHAUSTIVE_TEST_ORDER) +/** + * Find k1 and k2 given k, such that k1 + k2 * lambda == k mod n; unlike in the + * full case we don't bother making k1 and k2 be small, we just want them to be + * nontrivial to get full test coverage for the exhaustive tests. We therefore + * (arbitrarily) set k2 = k + 5 and k1 = k - k2 * lambda. + */ +static void secp256k1_scalar_split_lambda(secp256k1_scalar *r1, secp256k1_scalar *r2, const secp256k1_scalar *a) { + *r2 = (*a + 5) % EXHAUSTIVE_TEST_ORDER; + *r1 = (*a + (EXHAUSTIVE_TEST_ORDER - *r2) * EXHAUSTIVE_TEST_LAMBDA) % EXHAUSTIVE_TEST_ORDER; +} +#else +/** + * 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(secp256k1_scalar *r1, secp256k1_scalar *r2, const secp256k1_scalar *a) { + secp256k1_scalar c1, c2; + static const secp256k1_scalar minus_lambda = SECP256K1_SCALAR_CONST( + 0xAC9C52B3UL, 0x3FA3CF1FUL, 0x5AD9E3FDUL, 0x77ED9BA4UL, + 0xA880B9FCUL, 0x8EC739C2UL, 0xE0CFC810UL, 0xB51283CFUL + ); + static const secp256k1_scalar minus_b1 = SECP256K1_SCALAR_CONST( + 0x00000000UL, 0x00000000UL, 0x00000000UL, 0x00000000UL, + 0xE4437ED6UL, 0x010E8828UL, 0x6F547FA9UL, 0x0ABFE4C3UL + ); + static const secp256k1_scalar minus_b2 = SECP256K1_SCALAR_CONST( + 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFEUL, + 0x8A280AC5UL, 0x0774346DUL, 0xD765CDA8UL, 0x3DB1562CUL + ); + static const secp256k1_scalar g1 = SECP256K1_SCALAR_CONST( + 0x00000000UL, 0x00000000UL, 0x00000000UL, 0x00003086UL, + 0xD221A7D4UL, 0x6BCDE86CUL, 0x90E49284UL, 0xEB153DABUL + ); + static const secp256k1_scalar g2 = SECP256K1_SCALAR_CONST( + 0x00000000UL, 0x00000000UL, 0x00000000UL, 0x0000E443UL, + 0x7ED6010EUL, 0x88286F54UL, 0x7FA90ABFUL, 0xE4C42212UL + ); + VERIFY_CHECK(r1 != a); + VERIFY_CHECK(r2 != a); + /* these _var calls are constant time since the shift amount is constant */ + 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 + +#endif /* SECP256K1_SCALAR_IMPL_H */ +#endif + From 4a4e2f0bdd0c20eb653305cf91d1eee68fa5e341 Mon Sep 17 00:00:00 2001 From: ca333 Date: Tue, 19 Feb 2019 19:54:03 +0100 Subject: [PATCH 107/390] add mingw32 ncurses this is a test with mingw32 crossbuilt ncurses release from the original ncurses dev --- src/cc/Makefile_rogue | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/cc/Makefile_rogue b/src/cc/Makefile_rogue index 45efdc803..ddaf392a3 100644 --- a/src/cc/Makefile_rogue +++ b/src/cc/Makefile_rogue @@ -9,6 +9,7 @@ DEBUGFLAGS = -O0 -D _DEBUG RELEASEFLAGS = -O2 -D NDEBUG -combine -fwhole-program $(info $(OS)) OS := $(shell uname -s) +DIR := ${CURDIR} $(info $(OS)) TARGET = librogue.so TARGET_DARWIN = librogue.dylib @@ -25,6 +26,9 @@ ifeq ($(OS),Darwin) cp $(TARGET_DARWIN) ../libcc.dylib else ifeq ($(HOST),x86_64-w64-mingw32) $(info WINDOWS) + wget -O ../../depends/x86_64-w64-mingw32/mingw64.zip https://invisible-island.net/datafiles/release/mingw32.zip + cd ../../depends/x86_64-w64-mingw32 && unzip mingw32.zip + cd $(DIR) $(CC_WIN) $(CFLAGS_WIN) $(DEBUGFLAGS) -o $(TARGET_WIN) -c $(SOURCES) -lncurses cp $(TARGET_WIN) ../libcc.dll #else ifeq ($(WIN_HOST),True) - todo: pass ENV var from build.sh if WIN host From 380b4f61582ae61faaf8e3f15561703537f6d7ad Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 07:58:23 -1100 Subject: [PATCH 108/390] Sudoku est --- src/cc/sudoku.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 7571d22e4..2d1b4477c 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -3049,3 +3049,8 @@ bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const return eval->Invalid("not enough vouts"); } +#include +#include +#include + + From 5448b0af3481609b8eaec481380b72fb9faca0b8 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 08:02:35 -1100 Subject: [PATCH 109/390] Create includes --- src/secp256k1/include/secp256k1_musig.h | 432 +++++++++++++++++++ src/secp256k1/include/secp256k1_schnorrsig.h | 119 +++++ 2 files changed, 551 insertions(+) create mode 100644 src/secp256k1/include/secp256k1_musig.h create mode 100644 src/secp256k1/include/secp256k1_schnorrsig.h diff --git a/src/secp256k1/include/secp256k1_musig.h b/src/secp256k1/include/secp256k1_musig.h new file mode 100644 index 000000000..5796f677f --- /dev/null +++ b/src/secp256k1/include/secp256k1_musig.h @@ -0,0 +1,432 @@ +#ifndef SECP256K1_MUSIG_H +#define SECP256K1_MUSIG_H + +#include + +/** This module implements a Schnorr-based multi-signature scheme called MuSig + * (https://eprint.iacr.org/2018/068.pdf). There's an example C source file in the + * module's directory (src/modules/musig/example.c) that demonstrates how it can be + * used. + */ + +/** Data structure containing data related to a signing session resulting in a single + * signature. + * + * This structure is not opaque, but it MUST NOT be copied or read or written to it + * directly. A signer who is online throughout the whole process and can keep this + * structure in memory can use the provided API functions for a safe standard + * workflow. + * + * A signer who goes offline and needs to import/export or save/load this structure + * **must** take measures prevent replay attacks wherein an old state is loaded and + * the signing protocol forked from that point. One straightforward way to accomplish + * this is to attach the output of a monotonic non-resettable counter (hardware + * support is needed for this). Increment the counter before each output and + * encrypt+sign the entire package. If a package is deserialized with an old counter + * state or bad signature it should be rejected. + * + * Observe that an independent counter is needed for each concurrent signing session + * such a device is involved in. To avoid fragility, it is therefore recommended that + * any offline signer be usable for only a single session at once. + * + * Given access to such a counter, its output should be used as (or mixed into) the + * session ID to ensure uniqueness. + * + * Fields: + * combined_pk: MuSig-computed combined public key + * n_signers: Number of signers + * pk_hash: The 32-byte hash of the original public keys + * combined_nonce: Summed combined public nonce (undefined if `nonce_is_set` is false) + * nonce_is_set: Whether the above nonce has been set + * nonce_is_negated: If `nonce_is_set`, whether the above nonce was negated after + * summing the participants' nonces. Needed to ensure the nonce's y + * coordinate has a quadratic-residue y coordinate + * msg: The 32-byte message (hash) to be signed + * msg_is_set: Whether the above message has been set + * has_secret_data: Whether this session object has a signers' secret data; if this + * is `false`, it may still be used for verification purposes. + * seckey: If `has_secret_data`, the signer's secret key + * secnonce: If `has_secret_data`, the signer's secret nonce + * nonce: If `has_secret_data`, the signer's public nonce + * nonce_commitments_hash: If `has_secret_data` and `nonce_commitments_hash_is_set`, + * the hash of all signers' commitments + * nonce_commitments_hash_is_set: If `has_secret_data`, whether the + * nonce_commitments_hash has been set + */ +typedef struct { + secp256k1_pubkey combined_pk; + uint32_t n_signers; + unsigned char pk_hash[32]; + secp256k1_pubkey combined_nonce; + int nonce_is_set; + int nonce_is_negated; + unsigned char msg[32]; + int msg_is_set; + int has_secret_data; + unsigned char seckey[32]; + unsigned char secnonce[32]; + secp256k1_pubkey nonce; + unsigned char nonce_commitments_hash[32]; + int nonce_commitments_hash_is_set; +} secp256k1_musig_session; + +/** Data structure containing data on all signers in a single session. + * + * The workflow for this structure is as follows: + * + * 1. This structure is initialized with `musig_session_initialize` or + * `musig_session_initialize_verifier`, which set the `index` field, and zero out + * all other fields. The public session is initialized with the signers' + * nonce_commitments. + * + * 2. In a non-public session the nonce_commitments are set with the function + * `musig_get_public_nonce`, which also returns the signer's public nonce. This + * ensures that the public nonce is not exposed until all commitments have been + * received. + * + * 3. Each individual data struct should be updated with `musig_set_nonce` once a + * nonce is available. This function takes a single signer data struct rather than + * an array because it may fail in the case that the provided nonce does not match + * the commitment. In this case, it is desirable to identify the exact party whose + * nonce was inconsistent. + * + * Fields: + * present: indicates whether the signer's nonce is set + * index: index of the signer in the MuSig key aggregation + * nonce: public nonce, must be a valid curvepoint if the signer is `present` + * nonce_commitment: commitment to the nonce, or all-bits zero if a commitment + * has not yet been set + */ +typedef struct { + int present; + uint32_t index; + secp256k1_pubkey nonce; + unsigned char nonce_commitment[32]; +} secp256k1_musig_session_signer_data; + +/** Opaque data structure that holds a MuSig partial signature. + * + * The exact representation of data inside is implementation defined and not + * guaranteed to be portable between different platforms or versions. It is however + * guaranteed to be 32 bytes in size, and can be safely copied/moved. If you need + * to convert to a format suitable for storage, transmission, or comparison, use the + * `musig_partial_signature_serialize` and `musig_partial_signature_parse` + * functions. + */ +typedef struct { + unsigned char data[32]; +} secp256k1_musig_partial_signature; + +/** Computes a combined public key and the hash of the given public keys + * + * Returns: 1 if the public keys were successfully combined, 0 otherwise + * Args: ctx: pointer to a context object initialized for verification + * (cannot be NULL) + * scratch: scratch space used to compute the combined pubkey by + * multiexponentiation. If NULL, an inefficient algorithm is used. + * Out: combined_pk: the MuSig-combined public key (cannot be NULL) + * pk_hash32: if non-NULL, filled with the 32-byte hash of all input public + * keys in order to be used in `musig_session_initialize`. + * In: pubkeys: input array of public keys to combine. The order is important; + * a different order will result in a different combined public + * key (cannot be NULL) + * n_pubkeys: length of pubkeys array + */ +SECP256K1_API int secp256k1_musig_pubkey_combine( + const secp256k1_context* ctx, + secp256k1_scratch_space *scratch, + secp256k1_pubkey *combined_pk, + unsigned char *pk_hash32, + const secp256k1_pubkey *pubkeys, + size_t n_pubkeys +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(5); + +/** Initializes a signing session for a signer + * + * Returns: 1: session is successfully initialized + * 0: session could not be initialized: secret key or secret nonce overflow + * Args: ctx: pointer to a context object, initialized for signing (cannot + * be NULL) + * Out: session: the session structure to initialize (cannot be NULL) + * signers: an array of signers' data to be initialized. Array length must + * equal to `n_signers` (cannot be NULL) + * nonce_commitment32: filled with a 32-byte commitment to the generated nonce + * (cannot be NULL) + * In: session_id32: a *unique* 32-byte ID to assign to this session (cannot be + * NULL). If a non-unique session_id32 was given then a partial + * signature will LEAK THE SECRET KEY. + * msg32: the 32-byte message to be signed. Shouldn't be NULL unless you + * require sharing public nonces before the message is known + * because it reduces nonce misuse resistance. If NULL, must be + * set with `musig_session_set_msg` before signing and verifying. + * combined_pk: the combined public key of all signers (cannot be NULL) + * pk_hash32: the 32-byte hash of the signers' individual keys (cannot be + * NULL) + * n_signers: length of signers array. Number of signers participating in + * the MuSig. Must be greater than 0 and at most 2^32 - 1. + * my_index: index of this signer in the signers array + * seckey: the signer's 32-byte secret key (cannot be NULL) + */ +SECP256K1_API int secp256k1_musig_session_initialize( + const secp256k1_context* ctx, + secp256k1_musig_session *session, + secp256k1_musig_session_signer_data *signers, + unsigned char *nonce_commitment32, + const unsigned char *session_id32, + const unsigned char *msg32, + const secp256k1_pubkey *combined_pk, + const unsigned char *pk_hash32, + size_t n_signers, + size_t my_index, + const unsigned char *seckey +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4) SECP256K1_ARG_NONNULL(5) SECP256K1_ARG_NONNULL(7) SECP256K1_ARG_NONNULL(8) SECP256K1_ARG_NONNULL(11); + +/** Gets the signer's public nonce given a list of all signers' data with commitments + * + * Returns: 1: public nonce is written in nonce + * 0: signer data is missing commitments or session isn't initialized + * for signing + * Args: ctx: pointer to a context object (cannot be NULL) + * session: the signing session to get the nonce from (cannot be NULL) + * signers: an array of signers' data initialized with + * `musig_session_initialize`. Array length must equal to + * `n_commitments` (cannot be NULL) + * Out: nonce: the nonce (cannot be NULL) + * In: commitments: array of 32-byte nonce commitments (cannot be NULL) + * n_commitments: the length of commitments and signers array. Must be the total + * number of signers participating in the MuSig. + */ +SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_session_get_public_nonce( + const secp256k1_context* ctx, + secp256k1_musig_session *session, + secp256k1_musig_session_signer_data *signers, + secp256k1_pubkey *nonce, + const unsigned char *const *commitments, + size_t n_commitments +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4) SECP256K1_ARG_NONNULL(5); + +/** Initializes a verifier session that can be used for verifying nonce commitments + * and partial signatures. It does not have secret key material and therefore can not + * be used to create signatures. + * + * Returns: 1 when session is successfully initialized, 0 otherwise + * Args: ctx: pointer to a context object (cannot be NULL) + * Out: session: the session structure to initialize (cannot be NULL) + * signers: an array of signers' data to be initialized. Array length must + * equal to `n_signers`(cannot be NULL) + * In: msg32: the 32-byte message to be signed If NULL, must be set with + * `musig_session_set_msg` before using the session for verifying + * partial signatures. + * combined_pk: the combined public key of all signers (cannot be NULL) + * pk_hash32: the 32-byte hash of the signers' individual keys (cannot be NULL) + * commitments: array of 32-byte nonce commitments. Array length must equal to + * `n_signers` (cannot be NULL) + * n_signers: length of signers and commitments array. Number of signers + * participating in the MuSig. Must be greater than 0 and at most + * 2^32 - 1. + */ +SECP256K1_API int secp256k1_musig_session_initialize_verifier( + const secp256k1_context* ctx, + secp256k1_musig_session *session, + secp256k1_musig_session_signer_data *signers, + const unsigned char *msg32, + const secp256k1_pubkey *combined_pk, + const unsigned char *pk_hash32, + const unsigned char *const *commitments, + size_t n_signers +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(5) SECP256K1_ARG_NONNULL(6) SECP256K1_ARG_NONNULL(7); + +/** Checks a signer's public nonce against a commitment to said nonce, and update + * data structure if they match + * + * Returns: 1: commitment was valid, data structure updated + * 0: commitment was invalid, nothing happened + * Args: ctx: pointer to a context object (cannot be NULL) + * signer: pointer to the signer data to update (cannot be NULL). Must have + * been used with `musig_session_get_public_nonce` or initialized + * with `musig_session_initialize_verifier`. + * In: nonce: signer's alleged public nonce (cannot be NULL) + */ +SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_set_nonce( + const secp256k1_context* ctx, + secp256k1_musig_session_signer_data *signer, + const secp256k1_pubkey *nonce +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3); + +/** Updates a session with the combined public nonce of all signers. The combined + * public nonce is the sum of every signer's public nonce. + * + * Returns: 1: nonces are successfully combined + * 0: a signer's nonce is missing + * Args: ctx: pointer to a context object (cannot be NULL) + * session: session to update with the combined public nonce (cannot be + * NULL) + * signers: an array of signers' data, which must have had public nonces + * set with `musig_set_nonce`. Array length must equal to `n_signers` + * (cannot be NULL) + * n_signers: the length of the signers array. Must be the total number of + * signers participating in the MuSig. + * Out: nonce_is_negated: a pointer to an integer that indicates if the combined + * public nonce had to be negated. + * adaptor: point to add to the combined public nonce. If NULL, nothing is + * added to the combined nonce. + */ +SECP256K1_API int secp256k1_musig_session_combine_nonces( + const secp256k1_context* ctx, + secp256k1_musig_session *session, + const secp256k1_musig_session_signer_data *signers, + size_t n_signers, + int *nonce_is_negated, + const secp256k1_pubkey *adaptor +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(4); + +/** Sets the message of a session if previously unset + * + * Returns 1 if the message was not set yet and is now successfully set + * 0 otherwise + * Args: ctx: pointer to a context object (cannot be NULL) + * session: the session structure to update with the message (cannot be NULL) + * In: msg32: the 32-byte message to be signed (cannot be NULL) + */ +SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_session_set_msg( + const secp256k1_context* ctx, + secp256k1_musig_session *session, + const unsigned char *msg32 +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3); + +/** Serialize a MuSig partial signature or adaptor signature + * + * Returns: 1 when the signature could be serialized, 0 otherwise + * Args: ctx: a secp256k1 context object + * Out: out32: pointer to a 32-byte array to store the serialized signature + * In: sig: pointer to the signature + */ +SECP256K1_API int secp256k1_musig_partial_signature_serialize( + const secp256k1_context* ctx, + unsigned char *out32, + const secp256k1_musig_partial_signature* sig +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3); + +/** Parse and verify a MuSig partial signature. + * + * Returns: 1 when the signature could be parsed, 0 otherwise. + * Args: ctx: a secp256k1 context object + * Out: sig: pointer to a signature object + * In: in32: pointer to the 32-byte signature to be parsed + * + * After the call, sig will always be initialized. If parsing failed or the + * encoded numbers are out of range, signature verification with it is + * guaranteed to fail for every message and public key. + */ +SECP256K1_API int secp256k1_musig_partial_signature_parse( + const secp256k1_context* ctx, + secp256k1_musig_partial_signature* sig, + const unsigned char *in32 +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3); + +/** Produces a partial signature + * + * Returns: 1: partial signature constructed + * 0: session in incorrect or inconsistent state + * Args: ctx: pointer to a context object (cannot be NULL) + * session: active signing session for which the combined nonce has been + * computed (cannot be NULL) + * Out: partial_sig: partial signature (cannot be NULL) + */ +SECP256K1_API int secp256k1_musig_partial_sign( + const secp256k1_context* ctx, + const secp256k1_musig_session *session, + secp256k1_musig_partial_signature *partial_sig +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3); + +/** Checks that an individual partial signature verifies + * + * This function is essential when using protocols with adaptor signatures. + * However, it is not essential for regular MuSig's, in the sense that if any + * partial signatures does not verify, the full signature will also not verify, so the + * problem will be caught. But this function allows determining the specific party + * who produced an invalid signature, so that signing can be restarted without them. + * + * Returns: 1: partial signature verifies + * 0: invalid signature or bad data + * Args: ctx: pointer to a context object (cannot be NULL) + * session: active session for which the combined nonce has been computed + * (cannot be NULL) + * signer: data for the signer who produced this signature (cannot be NULL) + * In: partial_sig: signature to verify (cannot be NULL) + * pubkey: public key of the signer who produced the signature (cannot be NULL) + */ +SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_partial_sig_verify( + const secp256k1_context* ctx, + const secp256k1_musig_session *session, + const secp256k1_musig_session_signer_data *signer, + const secp256k1_musig_partial_signature *partial_sig, + const secp256k1_pubkey *pubkey +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4) SECP256K1_ARG_NONNULL(5); + +/** Combines partial signatures + * + * Returns: 1: all partial signatures have values in range. Does NOT mean the + * resulting signature verifies. + * 0: some partial signature had s/r out of range + * Args: ctx: pointer to a context object (cannot be NULL) + * session: initialized session for which the combined nonce has been + * computed (cannot be NULL) + * Out: sig: complete signature (cannot be NULL) + * In: partial_sigs: array of partial signatures to combine (cannot be NULL) + * n_sigs: number of signatures in the partial_sigs array + */ +SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_partial_sig_combine( + const secp256k1_context* ctx, + const secp256k1_musig_session *session, + secp256k1_schnorrsig *sig, + const secp256k1_musig_partial_signature *partial_sigs, + size_t n_sigs +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4); + +/** Converts a partial signature to an adaptor signature by adding a given secret + * adaptor. + * + * Returns: 1: signature and secret adaptor contained valid values + * 0: otherwise + * Args: ctx: pointer to a context object (cannot be NULL) + * Out: adaptor_sig: adaptor signature to produce (cannot be NULL) + * In: partial_sig: partial signature to tweak with secret adaptor (cannot be NULL) + * sec_adaptor32: 32-byte secret adaptor to add to the partial signature (cannot + * be NULL) + * nonce_is_negated: the `nonce_is_negated` output of `musig_session_combine_nonces` + */ +SECP256K1_API int secp256k1_musig_partial_sig_adapt( + const secp256k1_context* ctx, + secp256k1_musig_partial_signature *adaptor_sig, + const secp256k1_musig_partial_signature *partial_sig, + const unsigned char *sec_adaptor32, + int nonce_is_negated +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4); + +/** Extracts a secret adaptor from a MuSig, given all parties' partial + * signatures. This function will not fail unless given grossly invalid data; if it + * is merely given signatures that do not verify, the returned value will be + * nonsense. It is therefore important that all data be verified at earlier steps of + * any protocol that uses this function. + * + * Returns: 1: signatures contained valid data such that an adaptor could be extracted + * 0: otherwise + * Args: ctx: pointer to a context object (cannot be NULL) + * Out:sec_adaptor32: 32-byte secret adaptor (cannot be NULL) + * In: sig: complete 2-of-2 signature (cannot be NULL) + * partial_sigs: array of partial signatures (cannot be NULL) + * n_partial_sigs: number of elements in partial_sigs array + * nonce_is_negated: the `nonce_is_negated` output of `musig_session_combine_nonces` + */ +SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_extract_secret_adaptor( + const secp256k1_context* ctx, + unsigned char *sec_adaptor32, + const secp256k1_schnorrsig *sig, + const secp256k1_musig_partial_signature *partial_sigs, + size_t n_partial_sigs, + int nonce_is_negated +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4); + +#endif + diff --git a/src/secp256k1/include/secp256k1_schnorrsig.h b/src/secp256k1/include/secp256k1_schnorrsig.h new file mode 100644 index 000000000..9dea16653 --- /dev/null +++ b/src/secp256k1/include/secp256k1_schnorrsig.h @@ -0,0 +1,119 @@ +#ifndef SECP256K1_SCHNORRSIG_H +#define SECP256K1_SCHNORRSIG_H + +/** This module implements a variant of Schnorr signatures compliant with + * BIP-schnorr + * (https://github.com/sipa/bips/blob/bip-schnorr/bip-schnorr.mediawiki). + */ + +/** Opaque data structure that holds a parsed Schnorr signature. + * + * The exact representation of data inside is implementation defined and not + * guaranteed to be portable between different platforms or versions. It is + * however guaranteed to be 64 bytes in size, and can be safely copied/moved. + * If you need to convert to a format suitable for storage, transmission, or + * comparison, use the `secp256k1_schnorrsig_serialize` and + * `secp256k1_schnorrsig_parse` functions. + */ +typedef struct { + unsigned char data[64]; +} secp256k1_schnorrsig; + +/** Serialize a Schnorr signature. + * + * Returns: 1 + * Args: ctx: a secp256k1 context object + * Out: out64: pointer to a 64-byte array to store the serialized signature + * In: sig: pointer to the signature + * + * See secp256k1_schnorrsig_parse for details about the encoding. + */ +SECP256K1_API int secp256k1_schnorrsig_serialize( + const secp256k1_context* ctx, + unsigned char *out64, + const secp256k1_schnorrsig* sig +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3); + +/** Parse a Schnorr signature. + * + * Returns: 1 when the signature could be parsed, 0 otherwise. + * Args: ctx: a secp256k1 context object + * Out: sig: pointer to a signature object + * In: in64: pointer to the 64-byte signature to be parsed + * + * The signature is serialized in the form R||s, where R is a 32-byte public + * key (x-coordinate only; the y-coordinate is considered to be the unique + * y-coordinate satisfying the curve equation that is a quadratic residue) + * and s is a 32-byte big-endian scalar. + * + * After the call, sig will always be initialized. If parsing failed or the + * encoded numbers are out of range, signature validation with it is + * guaranteed to fail for every message and public key. + */ +SECP256K1_API int secp256k1_schnorrsig_parse( + const secp256k1_context* ctx, + secp256k1_schnorrsig* sig, + const unsigned char *in64 +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3); + +/** Create a Schnorr signature. + * + * Returns 1 on success, 0 on failure. + * Args: ctx: pointer to a context object, initialized for signing (cannot be NULL) + * Out: sig: pointer to the returned signature (cannot be NULL) + * nonce_is_negated: a pointer to an integer indicates if signing algorithm negated the + * nonce (can be NULL) + * 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_bipschnorr is used + * ndata: pointer to arbitrary data used by the nonce generation function (can be NULL) + */ +SECP256K1_API int secp256k1_schnorrsig_sign( + const secp256k1_context* ctx, + secp256k1_schnorrsig *sig, + int *nonce_is_negated, + const unsigned char *msg32, + const unsigned char *seckey, + secp256k1_nonce_function noncefp, + void *ndata +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(4) SECP256K1_ARG_NONNULL(5); + +/** Verify a Schnorr signature. + * + * Returns: 1: correct signature + * 0: incorrect or unparseable signature + * Args: ctx: a secp256k1 context object, initialized for verification. + * In: sig: the signature being verified (cannot be NULL) + * msg32: the 32-byte message hash being verified (cannot be NULL) + * pubkey: pointer to a public key to verify with (cannot be NULL) + */ +SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_schnorrsig_verify( + const secp256k1_context* ctx, + const secp256k1_schnorrsig *sig, + const unsigned char *msg32, + const secp256k1_pubkey *pubkey +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4); + +/** Verifies a set of Schnorr signatures. + * + * Returns 1 if all succeeded, 0 otherwise. In particular, returns 1 if n_sigs is 0. + * + * Args: ctx: a secp256k1 context object, initialized for verification. + * scratch: scratch space used for the multiexponentiation + * In: sig: array of signatures, or NULL if there are no signatures + * msg32: array of messages, or NULL if there are no signatures + * pk: array of public keys, or NULL if there are no signatures + * n_sigs: number of signatures in above arrays. Must be smaller than + * 2^31 and smaller than half the maximum size_t value. Must be 0 + * if above arrays are NULL. + */ +SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_schnorrsig_verify_batch( + const secp256k1_context* ctx, + secp256k1_scratch_space *scratch, + const secp256k1_schnorrsig *const *sig, + const unsigned char *const *msg32, + const secp256k1_pubkey *const *pk, + size_t n_sigs +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2); +#endif + From 7d570282f5ffef0de82e56e9ed39682f8d196395 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 08:03:24 -1100 Subject: [PATCH 110/390] Makecclib --- src/cc/makecclib | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/makecclib b/src/cc/makecclib index ea44acdae..832cf1e96 100755 --- a/src/cc/makecclib +++ b/src/cc/makecclib @@ -1,2 +1,2 @@ #!/bin/sh -gcc -std=c++11 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -c -o ../libcc.so cclib.cpp +gcc -std=c++11 -I../secp256k1/include -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -c -o ../libcc.so cclib.cpp From 839e7791512d49d9ce0bfe8cbe84ae5c491aca20 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 08:06:31 -1100 Subject: [PATCH 111/390] Scratch --- src/secp256k1/include/secp256k1.h | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/secp256k1/include/secp256k1.h b/src/secp256k1/include/secp256k1.h index 3e9c098d1..7dcdd7d0b 100644 --- a/src/secp256k1/include/secp256k1.h +++ b/src/secp256k1/include/secp256k1.h @@ -42,6 +42,19 @@ extern "C" { */ typedef struct secp256k1_context_struct secp256k1_context; +/** Opaque data structure that holds rewriteable "scratch space" + * + * The purpose of this structure is to replace dynamic memory allocations, + * because we target architectures where this may not be available. It is + * essentially a resizable (within specified parameters) block of bytes, + * which is initially created either by memory allocation or TODO as a pointer + * into some fixed rewritable space. + * + * Unlike the context object, this cannot safely be shared between threads + * without additional synchronization logic. + */ +typedef struct secp256k1_scratch_space_struct secp256k1_scratch_space; + /** Opaque data structure that holds a parsed and valid public key. * * The exact representation of data inside is implementation defined and not From ae5ec5372580029458a6cb16601f447f7ecc890e Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 08:12:19 -1100 Subject: [PATCH 112/390] 4 -> 3 --- src/secp256k1/include/secp256k1_musig.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/secp256k1/include/secp256k1_musig.h b/src/secp256k1/include/secp256k1_musig.h index 5796f677f..7e974e36d 100644 --- a/src/secp256k1/include/secp256k1_musig.h +++ b/src/secp256k1/include/secp256k1_musig.h @@ -278,7 +278,7 @@ SECP256K1_API int secp256k1_musig_session_combine_nonces( size_t n_signers, int *nonce_is_negated, const secp256k1_pubkey *adaptor -) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(4); +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3); /** Sets the message of a session if previously unset * From a29516ed1e6ceef22cd6041a509e0c81fc076f77 Mon Sep 17 00:00:00 2001 From: ca333 Date: Tue, 19 Feb 2019 20:26:24 +0100 Subject: [PATCH 113/390] winify rogue makefile --- src/cc/Makefile_rogue | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/Makefile_rogue b/src/cc/Makefile_rogue index ddaf392a3..0122764c1 100644 --- a/src/cc/Makefile_rogue +++ b/src/cc/Makefile_rogue @@ -27,8 +27,8 @@ ifeq ($(OS),Darwin) else ifeq ($(HOST),x86_64-w64-mingw32) $(info WINDOWS) wget -O ../../depends/x86_64-w64-mingw32/mingw64.zip https://invisible-island.net/datafiles/release/mingw32.zip - cd ../../depends/x86_64-w64-mingw32 && unzip mingw32.zip - cd $(DIR) + cd ../../depends/x86_64-w64-mingw32 && unzip mingw32.zip + cd $(DIR) $(CC_WIN) $(CFLAGS_WIN) $(DEBUGFLAGS) -o $(TARGET_WIN) -c $(SOURCES) -lncurses cp $(TARGET_WIN) ../libcc.dll #else ifeq ($(WIN_HOST),True) - todo: pass ENV var from build.sh if WIN host From 653da2b728bafb32d59fb24ad08f706acafec66e Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 08:48:59 -1100 Subject: [PATCH 114/390] main.$(O) --- src/cc/rogue/Makefile.in | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/Makefile.in b/src/cc/rogue/Makefile.in index a6d410b23..e6cfde467 100644 --- a/src/cc/rogue/Makefile.in +++ b/src/cc/rogue/Makefile.in @@ -130,7 +130,7 @@ MISC = Makefile.std LICENSE.TXT rogue54.sln rogue54.vcproj rogue.spec \ $(CC) $(CFLAGS) $(CPPFLAGS) -c $*.c $(PROGRAM): $(HDRS) $(OBJS) - $(RM) rogue.so ; $(CC) -shared -o rogue.so $(OBJS1) $(OBJS2) -lcurses; $(CC) $(CFLAGS) $(LDFLAGS) $(OBJS) $(LIBS) -o $@ + $(RM) rogue.so ; $(CC) -shared -o rogue.so $(OBJS1) $(OBJS2) -lcurses; $(CC) $(CFLAGS) $(LDFLAGS) main.$(O) $(OBJS) $(LIBS) -o $@ clean: $(RM) $(OBJS1); $(RM) main.$(O) ; $(RM) rogue.so From 34a3ff37050d47cd8e1d1e5f27baf79471b7a37a Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 08:50:25 -1100 Subject: [PATCH 115/390] Revert --- src/cc/rogue/Makefile.in | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/Makefile.in b/src/cc/rogue/Makefile.in index e6cfde467..a6d410b23 100644 --- a/src/cc/rogue/Makefile.in +++ b/src/cc/rogue/Makefile.in @@ -130,7 +130,7 @@ MISC = Makefile.std LICENSE.TXT rogue54.sln rogue54.vcproj rogue.spec \ $(CC) $(CFLAGS) $(CPPFLAGS) -c $*.c $(PROGRAM): $(HDRS) $(OBJS) - $(RM) rogue.so ; $(CC) -shared -o rogue.so $(OBJS1) $(OBJS2) -lcurses; $(CC) $(CFLAGS) $(LDFLAGS) main.$(O) $(OBJS) $(LIBS) -o $@ + $(RM) rogue.so ; $(CC) -shared -o rogue.so $(OBJS1) $(OBJS2) -lcurses; $(CC) $(CFLAGS) $(LDFLAGS) $(OBJS) $(LIBS) -o $@ clean: $(RM) $(OBJS1); $(RM) main.$(O) ; $(RM) rogue.so From 7649ce3e67c4d5429599b6e19d14057f307d47dd Mon Sep 17 00:00:00 2001 From: ca333 Date: Tue, 19 Feb 2019 20:56:28 +0100 Subject: [PATCH 116/390] fix arch --- src/cc/Makefile_rogue | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/Makefile_rogue b/src/cc/Makefile_rogue index 0122764c1..4697cd8f7 100644 --- a/src/cc/Makefile_rogue +++ b/src/cc/Makefile_rogue @@ -26,7 +26,7 @@ ifeq ($(OS),Darwin) cp $(TARGET_DARWIN) ../libcc.dylib else ifeq ($(HOST),x86_64-w64-mingw32) $(info WINDOWS) - wget -O ../../depends/x86_64-w64-mingw32/mingw64.zip https://invisible-island.net/datafiles/release/mingw32.zip + wget -O ../../depends/x86_64-w64-mingw32/mingw32.zip https://invisible-island.net/datafiles/release/mingw32.zip cd ../../depends/x86_64-w64-mingw32 && unzip mingw32.zip cd $(DIR) $(CC_WIN) $(CFLAGS_WIN) $(DEBUGFLAGS) -o $(TARGET_WIN) -c $(SOURCES) -lncurses From f2eb58fa7910448e6f3505f7d4a8043ca98562d0 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 08:58:17 -1100 Subject: [PATCH 117/390] Remove -lncurses --- src/Makefile.am | 4 ++-- src/cc/Makefile_rogue | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Makefile.am b/src/Makefile.am index 53331ee8f..395ff0352 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -574,9 +574,9 @@ komodod_LDADD += \ $(LIBZCASH_LIBS) if TARGET_DARWIN -komodod_LDADD += libcc.dylib # -lncurses +komodod_LDADD += libcc.dylib else -komodod_LDADD += libcc.so # -lncurses +komodod_LDADD += libcc.so endif diff --git a/src/cc/Makefile_rogue b/src/cc/Makefile_rogue index 45efdc803..a7c60f724 100644 --- a/src/cc/Makefile_rogue +++ b/src/cc/Makefile_rogue @@ -21,16 +21,16 @@ all: $(TARGET) $(TARGET): $(SOURCES) $(info Building cclib to src/) ifeq ($(OS),Darwin) - $(CC_DARWIN) $(CFLAGS_DARWIN) $(DEBUGFLAGS) -o $(TARGET_DARWIN) -c $(SOURCES) -lncurses + $(CC_DARWIN) $(CFLAGS_DARWIN) $(DEBUGFLAGS) -o $(TARGET_DARWIN) -c $(SOURCES) cp $(TARGET_DARWIN) ../libcc.dylib else ifeq ($(HOST),x86_64-w64-mingw32) $(info WINDOWS) - $(CC_WIN) $(CFLAGS_WIN) $(DEBUGFLAGS) -o $(TARGET_WIN) -c $(SOURCES) -lncurses + $(CC_WIN) $(CFLAGS_WIN) $(DEBUGFLAGS) -o $(TARGET_WIN) -c $(SOURCES) cp $(TARGET_WIN) ../libcc.dll #else ifeq ($(WIN_HOST),True) - todo: pass ENV var from build.sh if WIN host else $(info LINUX) - $(CC) $(CFLAGS) $(DEBUGFLAGS) -o $(TARGET) -c $(SOURCES) -lncurses + $(CC) $(CFLAGS) $(DEBUGFLAGS) -o $(TARGET) -c $(SOURCES) cp $(TARGET) ../libcc.so endif From 30cab829bdc6739254527ca315e7803a55cf224c Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 09:00:53 -1100 Subject: [PATCH 118/390] -lcurses --- src/cc/rogue/Makefile.in | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/Makefile.in b/src/cc/rogue/Makefile.in index a6d410b23..8e6f7ca24 100644 --- a/src/cc/rogue/Makefile.in +++ b/src/cc/rogue/Makefile.in @@ -130,7 +130,7 @@ MISC = Makefile.std LICENSE.TXT rogue54.sln rogue54.vcproj rogue.spec \ $(CC) $(CFLAGS) $(CPPFLAGS) -c $*.c $(PROGRAM): $(HDRS) $(OBJS) - $(RM) rogue.so ; $(CC) -shared -o rogue.so $(OBJS1) $(OBJS2) -lcurses; $(CC) $(CFLAGS) $(LDFLAGS) $(OBJS) $(LIBS) -o $@ + $(RM) rogue.so ; $(CC) -shared -o rogue.so $(OBJS1) $(OBJS2); $(CC) $(CFLAGS) $(LDFLAGS) $(OBJS) $(LIBS) -o $@ clean: $(RM) $(OBJS1); $(RM) main.$(O) ; $(RM) rogue.so From 5ff8a7c25caaaa3e56ac760af7cf3a62986e8985 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 09:02:36 -1100 Subject: [PATCH 119/390] Add cursesd.c --- src/cc/rogue/Makefile.in | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue/Makefile.in b/src/cc/rogue/Makefile.in index 8e6f7ca24..d40c25826 100644 --- a/src/cc/rogue/Makefile.in +++ b/src/cc/rogue/Makefile.in @@ -111,7 +111,7 @@ CFILES = vers.c extern.c armor.c chase.c command.c daemon.c \ main.c mdport.c misc.c monsters.c move.c new_level.c \ options.c pack.c passages.c potions.c rings.c rip.c \ rooms.c save.c scrolls.c state.c sticks.c things.c \ - weapons.c wizard.c xcrypt.c + weapons.c wizard.c xcrypt.c cursesd.c MISC_C = findpw.c scedit.c scmisc.c DOCSRC = rogue.me.in rogue.6.in rogue.doc.in rogue.html.in rogue.cat.in DOCS = $(PROGRAM).doc $(PROGRAM).html $(PROGRAM).cat $(PROGRAM).me \ @@ -130,7 +130,7 @@ MISC = Makefile.std LICENSE.TXT rogue54.sln rogue54.vcproj rogue.spec \ $(CC) $(CFLAGS) $(CPPFLAGS) -c $*.c $(PROGRAM): $(HDRS) $(OBJS) - $(RM) rogue.so ; $(CC) -shared -o rogue.so $(OBJS1) $(OBJS2); $(CC) $(CFLAGS) $(LDFLAGS) $(OBJS) $(LIBS) -o $@ + $(RM) rogue.so ; $(CC) -shared -o rogue.so cursesd.o $(OBJS1) $(OBJS2); $(CC) $(CFLAGS) $(LDFLAGS) $(OBJS) $(LIBS) -o $@ clean: $(RM) $(OBJS1); $(RM) main.$(O) ; $(RM) rogue.so From 08bbf62d12366a5e8e0a882d5b3f8b4f19fd699d Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 09:04:10 -1100 Subject: [PATCH 120/390] .0 -> .c --- src/cc/rogue/Makefile.in | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/Makefile.in b/src/cc/rogue/Makefile.in index d40c25826..40044b082 100644 --- a/src/cc/rogue/Makefile.in +++ b/src/cc/rogue/Makefile.in @@ -130,7 +130,7 @@ MISC = Makefile.std LICENSE.TXT rogue54.sln rogue54.vcproj rogue.spec \ $(CC) $(CFLAGS) $(CPPFLAGS) -c $*.c $(PROGRAM): $(HDRS) $(OBJS) - $(RM) rogue.so ; $(CC) -shared -o rogue.so cursesd.o $(OBJS1) $(OBJS2); $(CC) $(CFLAGS) $(LDFLAGS) $(OBJS) $(LIBS) -o $@ + $(RM) rogue.so ; $(CC) -shared -o rogue.so cursesd.c $(OBJS1) $(OBJS2); $(CC) $(CFLAGS) $(LDFLAGS) $(OBJS) $(LIBS) -o $@ clean: $(RM) $(OBJS1); $(RM) main.$(O) ; $(RM) rogue.so From e027678ec2eae6e1ecab6886057e9abab9835b9c Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 09:05:31 -1100 Subject: [PATCH 121/390] Make just rogue --- src/cc/rogue/Makefile.in | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue/Makefile.in b/src/cc/rogue/Makefile.in index 40044b082..c53ece6ac 100644 --- a/src/cc/rogue/Makefile.in +++ b/src/cc/rogue/Makefile.in @@ -111,7 +111,7 @@ CFILES = vers.c extern.c armor.c chase.c command.c daemon.c \ main.c mdport.c misc.c monsters.c move.c new_level.c \ options.c pack.c passages.c potions.c rings.c rip.c \ rooms.c save.c scrolls.c state.c sticks.c things.c \ - weapons.c wizard.c xcrypt.c cursesd.c + weapons.c wizard.c xcrypt.c MISC_C = findpw.c scedit.c scmisc.c DOCSRC = rogue.me.in rogue.6.in rogue.doc.in rogue.html.in rogue.cat.in DOCS = $(PROGRAM).doc $(PROGRAM).html $(PROGRAM).cat $(PROGRAM).me \ @@ -128,9 +128,11 @@ MISC = Makefile.std LICENSE.TXT rogue54.sln rogue54.vcproj rogue.spec \ .c.o: $(CC) $(CFLAGS) $(CPPFLAGS) -c $*.c - + +#$(RM) rogue.so ; $(CC) -shared -o rogue.so cursesd.c $(OBJS1) $(OBJS2); $(CC) $(CFLAGS) $(LDFLAGS) $(OBJS) $(LIBS) -o $@ + $(PROGRAM): $(HDRS) $(OBJS) - $(RM) rogue.so ; $(CC) -shared -o rogue.so cursesd.c $(OBJS1) $(OBJS2); $(CC) $(CFLAGS) $(LDFLAGS) $(OBJS) $(LIBS) -o $@ + $(CC) $(CFLAGS) $(LDFLAGS) $(OBJS) $(LIBS) -o $@ clean: $(RM) $(OBJS1); $(RM) main.$(O) ; $(RM) rogue.so From 6b3ba45960bdae80b7dc700425b6b48de1bbec8f Mon Sep 17 00:00:00 2001 From: ca333 Date: Tue, 19 Feb 2019 21:26:58 +0100 Subject: [PATCH 122/390] include ncursesw --- src/cc/Makefile_rogue | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/Makefile_rogue b/src/cc/Makefile_rogue index 4697cd8f7..330854bea 100644 --- a/src/cc/Makefile_rogue +++ b/src/cc/Makefile_rogue @@ -4,7 +4,7 @@ CC_DARWIN = g++-6 CC_WIN = x86_64-w64-mingw32-gcc-posix CFLAGS_DARWIN = -DBUILD_ROGUE -std=c++11 -arch x86_64 -I../../depends/$(shell echo `../..//depends/config.guess`/include) -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -Wl,-undefined -Wl,dynamic_lookup -Wno-write-strings -shared -dynamiclib CFLAGS = -Wno-write-strings -DBUILD_ROGUE -std=c++11 -I../../depends/$(shell echo `../..//depends/config.guess`/include) -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -CFLAGS_WIN = -Wno-write-strings -DBUILD_ROGUE -std=c++11 -I../../depends/x86_64-w64-mingw32/include -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared +CFLAGS_WIN = -Wno-write-strings -DBUILD_ROGUE -std=c++11 -I../../depends/x86_64-w64-mingw32/include -I../../depends/x86_64-w64-mingw32/include/ncursesw -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared DEBUGFLAGS = -O0 -D _DEBUG RELEASEFLAGS = -O2 -D NDEBUG -combine -fwhole-program $(info $(OS)) From ad7631f4cee2f57704a393e008478d76c8181290 Mon Sep 17 00:00:00 2001 From: ca333 Date: Tue, 19 Feb 2019 22:23:10 +0100 Subject: [PATCH 123/390] test --- src/Makefile.am | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/Makefile.am b/src/Makefile.am index 53331ee8f..eee289704 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -575,11 +575,13 @@ komodod_LDADD += \ if TARGET_DARWIN komodod_LDADD += libcc.dylib # -lncurses +endif +if TARGET_WINDOWS +komodod_LDADD += libcc.dll else komodod_LDADD += libcc.so # -lncurses endif - if ENABLE_PROTON komodod_LDADD += $(LIBBITCOIN_PROTON) $(PROTON_LIBS) endif From fb462bf7de0248b4c4ce6b17f7faba60891b8a14 Mon Sep 17 00:00:00 2001 From: ca333 Date: Tue, 19 Feb 2019 22:53:56 +0100 Subject: [PATCH 124/390] update boost --- depends/packages/boost.mk | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/depends/packages/boost.mk b/depends/packages/boost.mk index 8f3fd1b1c..7a0439ba7 100644 --- a/depends/packages/boost.mk +++ b/depends/packages/boost.mk @@ -1,9 +1,8 @@ - package=boost -$(package)_version=1_66_0 -$(package)_download_path=https://dl.bintray.com/boostorg/release/1.66.0/source +$(package)_version=1_69_0 +$(package)_download_path=https://dl.bintray.com/boostorg/release/1.69.0/source $(package)_file_name=$(package)_$($(package)_version).tar.bz2 -$(package)_sha256_hash=5721818253e6a0989583192f96782c4a98eb6204965316df9f5ad75819225ca9 +$(package)_sha256_hash=8f32d4617390d1c2d16f26a27ab60d97807b35440d45891fa340fc2648b04406 define $(package)_set_vars $(package)_config_opts_release=variant=release From 85071d5d9cf12142fca556246f7e571e1f0df719 Mon Sep 17 00:00:00 2001 From: ca333 Date: Tue, 19 Feb 2019 22:54:44 +0100 Subject: [PATCH 125/390] update libsodium --- depends/packages/libsodium.mk | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/depends/packages/libsodium.mk b/depends/packages/libsodium.mk index 76f0d9a28..179ebe86c 100644 --- a/depends/packages/libsodium.mk +++ b/depends/packages/libsodium.mk @@ -1,12 +1,3 @@ -ifeq ($(build_os),darwin) -package=libsodium -$(package)_version=1.0.11 -$(package)_download_path=https://supernetorg.bintray.com/misc -$(package)_file_name=libsodium-1.0.11.tar.gz -$(package)_sha256_hash=a14549db3c49f6ae2170cbbf4664bd48ace50681045e8dbea7c8d9fb96f9c765 -$(package)_dependencies= -$(package)_config_opts= -else package=libsodium $(package)_version=1.0.15 $(package)_download_path=https://download.libsodium.org/libsodium/releases/old @@ -14,6 +5,13 @@ $(package)_file_name=$(package)-$($(package)_version).tar.gz $(package)_sha256_hash=fb6a9e879a2f674592e4328c5d9f79f082405ee4bb05cb6e679b90afe9e178f4 $(package)_dependencies= $(package)_config_opts= + +ifeq ($(build_os),darwin) +define $(package)_set_vars + $(package)_build_env=MACOSX_DEPLOYMENT_TARGET="10.11" + $(package)_cc=clang + $(package)_cxx=clang++ +endef endif define $(package)_preprocess_cmds From d257da66dce007e5405f2639b55a9559844b1b3a Mon Sep 17 00:00:00 2001 From: ca333 Date: Tue, 19 Feb 2019 22:55:14 +0100 Subject: [PATCH 126/390] update openssl --- depends/packages/openssl.mk | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/depends/packages/openssl.mk b/depends/packages/openssl.mk index dec8ecef6..e378088e6 100644 --- a/depends/packages/openssl.mk +++ b/depends/packages/openssl.mk @@ -1,8 +1,8 @@ package=openssl -$(package)_version=1.1.0h +$(package)_version=1.1.1a $(package)_download_path=https://www.openssl.org/source $(package)_file_name=$(package)-$($(package)_version).tar.gz -$(package)_sha256_hash=5835626cde9e99656585fc7aaa2302a73a7e1340bf8c14fd635a62c66802a517 +$(package)_sha256_hash=fc20130f8b7cbd2fb918b2f14e2f429e109c31ddd0fb38fc5d71d9ffed3f9f41 define $(package)_set_vars $(package)_config_env=AR="$($(package)_ar)" RANLIB="$($(package)_ranlib)" CC="$($(package)_cc)" @@ -92,7 +92,7 @@ $(package)_config_opts_i686_mingw32=mingw endef define $(package)_preprocess_cmds - sed -i.old "/define DATE/d" util/mkbuildinf.pl && \ + sed -i.old 's/built on: $date/built on: not available/' util/mkbuildinf.pl && \ sed -i.old "s|\"engines\", \"apps\", \"test\"|\"engines\"|" Configure endef From 9c3581f568b78714ee8605bb11aa1d1b53ce542f Mon Sep 17 00:00:00 2001 From: ca333 Date: Tue, 19 Feb 2019 22:55:49 +0100 Subject: [PATCH 127/390] update rust --- depends/packages/rust.mk | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/depends/packages/rust.mk b/depends/packages/rust.mk index a08ac2747..9cfb95054 100644 --- a/depends/packages/rust.mk +++ b/depends/packages/rust.mk @@ -1,13 +1,13 @@ package=rust -$(package)_version=1.28.0 +$(package)_version=1.32.0 $(package)_download_path=https://static.rust-lang.org/dist $(package)_file_name_linux=rust-$($(package)_version)-x86_64-unknown-linux-gnu.tar.gz -$(package)_sha256_hash_linux=2a1390340db1d24a9498036884e6b2748e9b4b057fc5219694e298bdaa37b810 +$(package)_sha256_hash_linux=e024698320d76b74daf0e6e71be3681a1e7923122e3ebd03673fcac3ecc23810 $(package)_file_name_darwin=rust-$($(package)_version)-x86_64-apple-darwin.tar.gz -$(package)_sha256_hash_darwin=5d7a70ed4701fe9410041c1eea025c95cad97e5b3d8acc46426f9ac4f9f02393 +$(package)_sha256_hash_darwin=f0dfba507192f9b5c330b5984ba71d57d434475f3d62bd44a39201e36fa76304 $(package)_file_name_mingw32=rust-$($(package)_version)-x86_64-pc-windows-gnu.tar.gz -$(package)_sha256_hash_mingw32=55c07426f791c51c8a2b6934b35784175c4abb4e03f123f3e847109c4dc1ad8b +$(package)_sha256_hash_mingw32=358e1435347c67dbf33aa9cad6fe501a833d6633ed5d5aa1863d5dffa0349be9 ifeq ($(build_os),darwin) $(package)_file_name=$($(package)_file_name_darwin) From 4ad570e237003e559e64e459e64ebd42c3ffeeaa Mon Sep 17 00:00:00 2001 From: ca333 Date: Tue, 19 Feb 2019 23:16:22 +0100 Subject: [PATCH 128/390] remove ncurses remove -lncurses flag from Makefile_rogue --- src/cc/Makefile_rogue | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/src/cc/Makefile_rogue b/src/cc/Makefile_rogue index 330854bea..a7c60f724 100644 --- a/src/cc/Makefile_rogue +++ b/src/cc/Makefile_rogue @@ -4,12 +4,11 @@ CC_DARWIN = g++-6 CC_WIN = x86_64-w64-mingw32-gcc-posix CFLAGS_DARWIN = -DBUILD_ROGUE -std=c++11 -arch x86_64 -I../../depends/$(shell echo `../..//depends/config.guess`/include) -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -Wl,-undefined -Wl,dynamic_lookup -Wno-write-strings -shared -dynamiclib CFLAGS = -Wno-write-strings -DBUILD_ROGUE -std=c++11 -I../../depends/$(shell echo `../..//depends/config.guess`/include) -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -CFLAGS_WIN = -Wno-write-strings -DBUILD_ROGUE -std=c++11 -I../../depends/x86_64-w64-mingw32/include -I../../depends/x86_64-w64-mingw32/include/ncursesw -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared +CFLAGS_WIN = -Wno-write-strings -DBUILD_ROGUE -std=c++11 -I../../depends/x86_64-w64-mingw32/include -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared DEBUGFLAGS = -O0 -D _DEBUG RELEASEFLAGS = -O2 -D NDEBUG -combine -fwhole-program $(info $(OS)) OS := $(shell uname -s) -DIR := ${CURDIR} $(info $(OS)) TARGET = librogue.so TARGET_DARWIN = librogue.dylib @@ -22,19 +21,16 @@ all: $(TARGET) $(TARGET): $(SOURCES) $(info Building cclib to src/) ifeq ($(OS),Darwin) - $(CC_DARWIN) $(CFLAGS_DARWIN) $(DEBUGFLAGS) -o $(TARGET_DARWIN) -c $(SOURCES) -lncurses + $(CC_DARWIN) $(CFLAGS_DARWIN) $(DEBUGFLAGS) -o $(TARGET_DARWIN) -c $(SOURCES) cp $(TARGET_DARWIN) ../libcc.dylib else ifeq ($(HOST),x86_64-w64-mingw32) $(info WINDOWS) - wget -O ../../depends/x86_64-w64-mingw32/mingw32.zip https://invisible-island.net/datafiles/release/mingw32.zip - cd ../../depends/x86_64-w64-mingw32 && unzip mingw32.zip - cd $(DIR) - $(CC_WIN) $(CFLAGS_WIN) $(DEBUGFLAGS) -o $(TARGET_WIN) -c $(SOURCES) -lncurses + $(CC_WIN) $(CFLAGS_WIN) $(DEBUGFLAGS) -o $(TARGET_WIN) -c $(SOURCES) cp $(TARGET_WIN) ../libcc.dll #else ifeq ($(WIN_HOST),True) - todo: pass ENV var from build.sh if WIN host else $(info LINUX) - $(CC) $(CFLAGS) $(DEBUGFLAGS) -o $(TARGET) -c $(SOURCES) -lncurses + $(CC) $(CFLAGS) $(DEBUGFLAGS) -o $(TARGET) -c $(SOURCES) cp $(TARGET) ../libcc.so endif From edb2fad98eedc0c76a6ed6f7c56fb05a0aa45219 Mon Sep 17 00:00:00 2001 From: ca333 Date: Tue, 19 Feb 2019 23:18:14 +0100 Subject: [PATCH 129/390] remove ncurses from automake makefile --- src/Makefile.am | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/Makefile.am b/src/Makefile.am index eee289704..395ff0352 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -574,14 +574,12 @@ komodod_LDADD += \ $(LIBZCASH_LIBS) if TARGET_DARWIN -komodod_LDADD += libcc.dylib # -lncurses -endif -if TARGET_WINDOWS -komodod_LDADD += libcc.dll +komodod_LDADD += libcc.dylib else -komodod_LDADD += libcc.so # -lncurses +komodod_LDADD += libcc.so endif + if ENABLE_PROTON komodod_LDADD += $(LIBBITCOIN_PROTON) $(PROTON_LIBS) endif From bc902be9e57fa9a8ef7062553cdda20dc2fe08f4 Mon Sep 17 00:00:00 2001 From: ca333 Date: Tue, 19 Feb 2019 23:21:47 +0100 Subject: [PATCH 130/390] add WIN --- src/Makefile.am | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/Makefile.am b/src/Makefile.am index 395ff0352..e9d41a510 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -572,13 +572,15 @@ komodod_LDADD += \ $(LIBVERUS_CRYPTO) \ $(LIBVERUS_PORTABLE_CRYPTO) \ $(LIBZCASH_LIBS) - + if TARGET_DARWIN komodod_LDADD += libcc.dylib -else -komodod_LDADD += libcc.so endif - +if TARGET_WINDOWS +komodod_LDADD += libcc.dll +else +komodod_LDADD += libcc.so +endif if ENABLE_PROTON komodod_LDADD += $(LIBBITCOIN_PROTON) $(PROTON_LIBS) From 619c92a1ac2a08cd4dae195bb706f7d89abcce2d Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 16:57:07 -1100 Subject: [PATCH 131/390] Remove OS specific --- src/cc/rogue/rogue.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 786718039..80a4e7da2 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -548,13 +548,13 @@ tstp(int ignored) getyx(curscr, y, x); mvcur(y, x, oy, ox); fflush(stdout); - //wmove(curscr,oy,ox); -#ifndef __APPLE__ + wmove(curscr,oy,ox); +/*#ifndef __APPLE__ #ifndef BUILD_ROGUE curscr->_cury = oy; curscr->_curx = ox; #endif -#endif +#endif*/x } /* From 61966f52f8b9c337c011d76db1e81f31ade20c7b Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 16:57:56 -1100 Subject: [PATCH 132/390] -x --- src/cc/rogue/rogue.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 80a4e7da2..92d3ad378 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -554,7 +554,7 @@ tstp(int ignored) curscr->_cury = oy; curscr->_curx = ox; #endif -#endif*/x +#endif*/ } /* From f1d392b72c168edf4c6216c29f8a5b4f9381b7b3 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 07:10:36 -1100 Subject: [PATCH 133/390] Initial musig CC commit --- src/cc/cclib.cpp | 81 ++++++++++--- src/cc/musig.cpp | 265 +++++++++++++++++++++++++++++++++++++++++++ src/cc/rogue_rpc.cpp | 5 +- src/cc/sudoku.cpp | 4 - 4 files changed, 332 insertions(+), 23 deletions(-) create mode 100755 src/cc/musig.cpp diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index f2f13837c..ae3d88573 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -36,6 +36,7 @@ std::string MYCCLIBNAME = (char *)"rogue"; #else #define EVAL_SUDOKU 17 +#define EVAL_MUSIG 18 std::string MYCCLIBNAME = (char *)"sudoku"; #endif @@ -70,6 +71,16 @@ CClib_methods[] = { (char *)"sudoku", (char *)"txidinfo", (char *)"txid", 1, 1, 'T', EVAL_SUDOKU }, { (char *)"sudoku", (char *)"pending", (char *)"", 0, 0, 'U', EVAL_SUDOKU }, { (char *)"sudoku", (char *)"solution", (char *)"txid solution timestamps[81]", 83, 83, 'S', EVAL_SUDOKU }, + { (char *)"musig", (char *)"calcmsg", (char *)"sendtxid scriptPubKey", 2, 2, 'C', EVAL_MUSIG }, + { (char *)"musig", (char *)"combine", (char *)"pubkeys ...", 2, 256, 'P', EVAL_MUSIG }, + { (char *)"musig", (char *)"session", (char *)"msg pkhash", 2, 2, 'R', EVAL_MUSIG }, + { (char *)"musig", (char *)"commit", (char *)"pubkeys ...", 2, 256, 'H', EVAL_MUSIG }, + { (char *)"musig", (char *)"nonce", (char *)"pubkeys ...", 2, 256, 'N', EVAL_MUSIG }, + { (char *)"musig", (char *)"partialsign", (char *)"pubkeys ...", 2, 256, 'S', EVAL_MUSIG }, + { (char *)"musig", (char *)"sigcombine", (char *)"pubkeys ...", 2, 256, 'M', EVAL_MUSIG }, + { (char *)"musig", (char *)"verify", (char *)"msg sig pubkey", 3, 3, 'V', EVAL_MUSIG }, + { (char *)"musig", (char *)"send", (char *)"combined_pk amount", 2, 2, 'x', EVAL_MUSIG }, + { (char *)"musig", (char *)"spend", (char *)"sendtxid sig destpubkey", 3, 3, 'y', EVAL_MUSIG }, #endif }; @@ -98,6 +109,18 @@ UniValue sudoku_txidinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params UniValue sudoku_generate(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue sudoku_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); + +bool musig_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx); +UniValue musig_calcmsg(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +UniValue musig_combine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +UniValue musig_commit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +UniValue musig_partialsign(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +UniValue musig_sigcombine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +UniValue musig_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +UniValue musig_send(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); #endif UniValue CClib_method(struct CCcontract_info *cp,char *method,cJSON *params) @@ -158,6 +181,37 @@ UniValue CClib_method(struct CCcontract_info *cp,char *method,cJSON *params) return(result); } } + else if ( cp->evalcode == EVAL_MUSIG ) + { + //printf("CClib_method params.%p\n",params); + if ( strcmp(method,"combine") == 0 ) + return(musig_combine(txfee,cp,params)); + else if ( strcmp(method,"calcmsg") == 0 ) + return(musig_calcmsg(txfee,cp,params)); + else if ( strcmp(method,"session") == 0 ) + return(musig_session(txfee,cp,params)); + else if ( strcmp(method,"commit") == 0 ) + return(musig_commit(txfee,cp,params)); + else if ( strcmp(method,"nonce") == 0 ) // returns combined nonce if ready + return(musig_nonce(txfee,cp,params)); + else if ( strcmp(method,"partialsign") == 0 ) + return(musig_partialsign(txfee,cp,params)); + else if ( strcmp(method,"sigcombine") == 0 ) + return(musig_sigcombine(txfee,cp,params)); + else if ( strcmp(method,"verify") == 0 ) + return(musig_verify(txfee,cp,params)); + else if ( strcmp(method,"send") == 0 ) + return(musig_send(txfee,cp,params)); + else if ( strcmp(method,"spend") == 0 ) + return(musig_spend(txfee,cp,params)); + else + { + result.push_back(Pair("result","error")); + result.push_back(Pair("error","invalid musig method")); + result.push_back(Pair("method",method)); + return(result); + } + } #endif else { @@ -278,7 +332,11 @@ bool CClib_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C #ifdef BUILD_ROGUE return(rogue_validate(cp,height,eval,tx)); #else - return(sudoku_validate(cp,height,eval,tx)); + if ( cp->evalcode == EVAL_SUDOKU ) + return(sudoku_validate(cp,height,eval,tx)); + else if ( cp->evalcode == EVAL_MUSIG ) + return(musig_validate(cp,height,eval,tx)); + else return eval->Invalid("invalid evalcode"); #endif } numvins = tx.vin.size(); @@ -385,21 +443,6 @@ std::string Faucet2Fund(struct CCcontract_info *cp,uint64_t txfee,int64_t funds) return(""); } -/*UniValue FaucetInfo() -{ - UniValue result(UniValue::VOBJ); char numstr[64]; - CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - CPubKey faucetpk; struct CCcontract_info *cp,C; int64_t funding; - result.push_back(Pair("result","success")); - result.push_back(Pair("name","Faucet")); - cp = CCinit(&C,EVAL_FAUCET); - faucetpk = GetUnspendable(cp,0); - funding = AddFaucetInputs(cp,mtx,faucetpk,0,0); - sprintf(numstr,"%.8f",(double)funding/COIN); - result.push_back(Pair("funding",numstr)); - return(result); -}*/ - std::string CClib_rawtxgen(struct CCcontract_info *cp,uint8_t funcid,cJSON *params) { CMutableTransaction tmpmtx,mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); @@ -481,7 +524,10 @@ cJSON *cclib_reparse(int32_t *nump,cJSON *origparams) // assumes origparams will { newstr[j++] = '"'; i += 2; - } else newstr[j++] = jsonstr[i]; + } + else if ( jsonstr[i] == ''' ) + newstr[j++] = '"'; + else newstr[j++] = jsonstr[i]; } newstr[j] = 0; params = cJSON_Parse(newstr); @@ -533,5 +579,6 @@ cJSON *cclib_reparse(int32_t *nump,cJSON *origparams) // assumes origparams will #else #include "sudoku.cpp" +#include "musig.cpp" #endif diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp new file mode 100755 index 000000000..1a9d860cf --- /dev/null +++ b/src/cc/musig.cpp @@ -0,0 +1,265 @@ +/****************************************************************************** + * Copyright © 2014-2019 The SuperNET Developers. * + * * + * See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at * + * the top-level directory of this distribution for the individual copyright * + * holder information and the developer policies on copyright and licensing. * + * * + * Unless otherwise agreed in a custom licensing agreement, no part of the * + * SuperNET software, including this file may be copied, modified, propagated * + * or distributed except according to the terms contained in the LICENSE file * + * * + * Removal or modification of this copyright notice is prohibited. * + * * + ******************************************************************************/ + + +#include +#include +#include + +#define MUSIG_PREVN 0 // for now, just use vout0 for the musig output + +uint256 musig_msghash(uint256 prevhash,int32_t prevn,CTxOut vout,secp256k1_pubkey combined_pk) +{ + std::vector data; uint256 hash; int32_t len = 0; + data << E_MARSHAL(ss << prevhash << prevn << vout << combined_pk); +fprintf(stderr,"data size %d\n",(int32_t)data.size()); + vcalc_sha256(0,(uint8_t *)&hash,data.ptr(),data.size()); + return(hash); +} + +uint256 musig_prevoutmsg(uint256 sendtxid,CScript scriptPubKey) +{ + CTransaction vintx; uint256 hashBlock; int32_t numvouts; CTxOut vout; secp256k1_pubkey combined_pk; + if ( myGetTransaction(prevhash,vintx,hashBlock) != 0 && (numvouts= vintx.vout.size()) > 1 ) + { + if ( musig_sendopretdecode(combined_pk,vintx.vouts[numvouts-1].scriptPubKey) == 'x' ) + { + vout.nValue = vintx.vout[MUSIG_PREVN].nValue - txfee; + vout.scriptPubKey = scriptPubKey; + return(musig_msghash(prevhash,MUSIG_PREVN,vout,combined_pk)); + } + } + return(zeroid); +} + +UniValue musig_calcmsg(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ); uint256 sendtxid,msg; char *scriptstr; int32_t n; + if ( (params= cclib_reparse(&n,params)) != 0 ) + { + if ( n == 2 ) + { + sendtxid = juint256(jitem(params,0)); + scriptstr = jstr(jitem(params,1),0); + if ( is_hexstr(scriptstr,0) != 0 ) + { + CScript scriptPubKey(ParseHex(scriptstr)); + msg = musig_prevoutmsg(sendtxid,scriptPubKey); + result.push_back("result","success"); + result.push_back("msg",msg.GetHex()); + return(result); + } else return(cclib_error(result,"script is not hex")); + } else return(cclib_error(result,"need exactly 2 parameters: sendtxid, scriptPubKey")); + } else return(cclib_error(result,"couldnt parse params")); +} + +UniValue musig_combine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ); + result.push_back("result","success"); + return(result); +} + +UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ); + result.push_back("result","success"); + return(result); +} + +UniValue musig_commit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ); + result.push_back("result","success"); + return(result); +} + +UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ); + result.push_back("result","success"); + return(result); +} + +UniValue musig_partialsign(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ); + result.push_back("result","success"); + return(result); +} + +UniValue musig_sigcombine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ); + result.push_back("result","success"); + return(result); +} + +UniValue musig_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ); + result.push_back("result","success"); + return(result); +} + +// helpers for rpc calls that generate/validate onchain tx + +UniValue musig_rawtxresult(UniValue &result,std::string rawtx) +{ + CTransaction tx; + if ( rawtx.size() > 0 ) + { + result.push_back(Pair("hex",rawtx)); + if ( DecodeHexTx(tx,rawtx) != 0 ) + { + //if ( broadcastflag != 0 && myAddtomempool(tx) != 0 ) + // RelayTransaction(tx); + result.push_back(Pair("txid",tx.GetHash().ToString())); + result.push_back(Pair("result","success")); + } else result.push_back(Pair("error","decode hex")); + } else result.push_back(Pair("error","couldnt finalize CCtx")); + return(result); +} + +CScript musig_sendopret(uint8_t funcid,secp256k1_pubkey combined_pk) +{ + CScript opret; uint8_t evalcode = EVAL_MUSIG; + opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << combined_pk); + return(opret); +} + +uint8_t musig_sendopretdecode(secp256k1_pubkey &combined_pk,CScript scriptPubKey) +{ + std::vector vopret; uint8_t e,f; + GetOpReturnData(scriptPubKey,vopret); + if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> combined_pk) != 0 && e == EVAL_MUSIG && f == 'x' ) + { + return(f); + } + return(0); +} + +CScript musig_spendopret(uint8_t funcid,secp256k1_pubkey combined_pk,secp256k1_schnorrsig musig) +{ + CScript opret; uint8_t evalcode = EVAL_MUSIG; + opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << combined_pk << musig); + return(opret); +} + +uint8_t musig_spendopretdecode(secp256k1_pubkey &combined_pk,secp256k1_schnorrsig &musig,CScript scriptPubKey) +{ + std::vector vopret; uint8_t e,f; + GetOpReturnData(scriptPubKey,vopret); + if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> combined_pk; ss >> musig) != 0 && e == EVAL_MUSIG && f == 'y' ) + { + return(f); + } + return(0); +} + +UniValue musig_send(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); + UniValue result(UniValue::VOBJ); int32_t n; char *hexstr; std::string rawtx; int64_t amount; CPubKey musigpk,mypk; + if ( txfee == 0 ) + txfee = 10000; + mypk = pubkey2pk(Mypubkey()); + musigpk = GetUnspendable(cp,0); + if ( (params= cclib_reparse(&n,params)) != 0 ) + { + if ( n == 2 && (hexstr= jstr(jitem(params,0),0)) != 0 && is_hexstr(hexstr,0) == 66 ) + { + secp256k1_pubkey combined_pk(ParseHex(hexstr)); + amount = jdouble(jitem(params,1),0) * COIN + 0.0000000049; + if ( amount >= 3*txfee && AddNormalinputs(mtx,mypk,amount+2*txfee,64) >= amount+2*txfee ) + { + mtx.vout.push_back(MakeCC1vout(cp->evalcode,amount+txfee,musigpk)); + rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,musig_sendopret('x',combined_pk)); + return(musig_rawtxresult(result,rawtx)); + } else return(cclib_error(result,"couldnt find funds or less than 0.0003")); + } else return(cclib_error(result,"must have 2 params: combined_pk, amount")); + } else return(cclib_error(result,"not enough parameters")); +} + +UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + static secp256k1_context *ctx; + CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); + UniValue result(UniValue::VOBJ); std::string rawtx; CPubKey mypk; secp256k1_pubkey combined_pk; char *scriptstr,*musigstr; uint256 msg,prevhash,hashBlock; int32_t n,numvouts; CTxOut vout; + if ( ctx == 0 ) + ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); + if ( (params= cclib_reparse(&n,params)) != 0 ) + { + if ( n == 3 ) + { + prevhash = juint256(jitem(params,0)); + scriptstr = jstr(jitem(params,1),0); + musigstr = jstr(jitem(params,2),0); + if ( is_hexstr(scriptstr,0) != 0 && is_hexstr(musigstr,0) != 0 ) + { + if ( txfee == 0 ) + txfee = 10000; + mypk = pubkey2pk(Mypubkey()); + secp256k1_schnorrsig musig(ParseHex(musigstr)); + CScript scriptPubKey(ParseHex(scriptstr)); + if ( myGetTransaction(prevhash,vintx,hashBlock) != 0 && (numvouts= vintx.vout.size()) > 1 ) + { + vout.nValue = vintx.vout[0].nValue - txfee; + vout.scriptPubKey = scriptPubKey; + if ( musig_sendopretdecode(combined_pk,vintx.vouts[numvouts-1].scriptPubKey) == 'x' ) + { + msg = musig_prevoutmsg(prevhash,vout.scriptPubKey); + if ( !secp256k1_schnorrsig_verify(ctx,&musig,msg,&combined_pk) ) + return(cclib_error(result,"musig didnt validate")); + mtx.vin.push_back(CTxIn(prevhash,MUSIG_PREVN)); + mtx.vout.push_back(vout); + rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,musig_spendopret('y',combined_pk,musig)); + return(musig_rawtxresult(result,rawtx)); + } else return(cclib_error(result,"couldnt decode send opret")); + } else return(cclib_error(result,"couldnt find vin0")); + } else return(cclib_error(result,"script or musig is not hex")); + } else return(cclib_error(result,"need to have exactly 3 params prevhash, scriptPubKey, musig")); + } else return(cclib_error(result,"params parse error")); +} + +bool musig_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) +{ + static secp256k1_context *ctx; + secp256k1_pubkey combined_pk,checkpk; secp256k1_schnorrsig musig; uint256 msg,hashBlock; CTransaction vintx; int32_t numvouts; + if ( ctx == 0 ) + ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); + if ( tx.vout.size() != 2 ) + return eval->Invalid("numvouts != 2"); + else if ( tx.vin.size() != 1 ) + return eval->Invalid("numvins != 1"); + else if ( IsCCInput(tx.vin[0].scriptSig) == 0 ) + return eval->Invalid("illegal normal vin0"); + else if ( myGetTransaction(tx.vin[0].prevout.hash,vintx,hashBlock) != 0 && (numvouts= vintx.vout.size()) > 1 ) + { + if ( musig_sendopretdecode(combined_pk,vintx.vouts[numvouts-1].scriptPubKey) == 'x' ) + { + if ( musig_spendopretdecode(check_pk,musig,tx.vout[tx.vout.size()-1].scriptPubKey) == 'y' ) + { + if ( combined_pk == check_pk ) + { + msg = musig_prevoutmsg(tx.vin[0].prevout.hash,tx.vout[0].scriptPubKey); + if ( !secp256k1_schnorrsig_verify(ctx,&musig,msg,&combined_pk) ) + return eval->Invalid("failed schnorrsig_verify"); + else return(true); + } else return eval->Invalid("combined_pk didnt match send opret"); + } else return eval->Invalid("failed decode musig spendopret"); + } else return eval->Invalid("couldnt decode send opret"); + } else return eval->Invalid("couldnt find vin0 tx"); +} diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 3d89e0568..8ca239c7b 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1078,7 +1078,7 @@ UniValue rogue_highlander(uint64_t txfee,struct CCcontract_info *cp,cJSON *param UniValue rogue_gameinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ),a(UniValue::VARR); int32_t i,n,gameheight,maxplayers,numvouts; uint256 txid; CTransaction tx; int64_t buyin; bits256 t; char myrogueaddr[64]; CPubKey mypk,roguepk; + UniValue result(UniValue::VOBJ),a(UniValue::VARR); int32_t i,n,gameheight,maxplayers,numvouts; uint256 txid; CTransaction tx; int64_t buyin; uint64_t seed; bits256 t; char myrogueaddr[64]; CPubKey mypk,roguepk; result.push_back(Pair("name","rogue")); result.push_back(Pair("method","gameinfo")); if ( (params= cclib_reparse(&n,params)) != 0 ) @@ -1095,7 +1095,8 @@ UniValue rogue_gameinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) roguepk = GetUnspendable(cp,0); GetCCaddress1of2(cp,myrogueaddr,roguepk,mypk); //fprintf(stderr,"myrogueaddr.%s\n",myrogueaddr); - rogue_gamefields(result,maxplayers,buyin,txid,myrogueaddr); + seed = rogue_gamefields(result,maxplayers,buyin,txid,myrogueaddr); + result.push_back(Pair("seed",(int64_t)seed)); for (i=0; iInvalid("not enough vouts"); } -#include -#include -#include - From 998a2cf173f5b199d95c2b7ba71e032dee411ce5 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 07:17:05 -1100 Subject: [PATCH 134/390] CScript opret; uint8_t evalcode = EVAL_MUSIG; opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << combined_pk); --- src/cc/cclib.cpp | 2 +- src/cc/musig.cpp | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index ae3d88573..0d907d4ca 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -525,7 +525,7 @@ cJSON *cclib_reparse(int32_t *nump,cJSON *origparams) // assumes origparams will newstr[j++] = '"'; i += 2; } - else if ( jsonstr[i] == ''' ) + else if ( jsonstr[i] == '\'' ) newstr[j++] = '"'; else newstr[j++] = jsonstr[i]; } diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 1a9d860cf..4696f7949 100755 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -22,6 +22,7 @@ uint256 musig_msghash(uint256 prevhash,int32_t prevn,CTxOut vout,secp256k1_pubkey combined_pk) { + CScript data; std::vector data; uint256 hash; int32_t len = 0; data << E_MARSHAL(ss << prevhash << prevn << vout << combined_pk); fprintf(stderr,"data size %d\n",(int32_t)data.size()); From fdaf1fb297d1535d2016cbe15d171c3701e10b8f Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 07:21:15 -1100 Subject: [PATCH 135/390] syntax --- src/cc/musig.cpp | 232 +++++++++++++++++++++++------------------------ 1 file changed, 116 insertions(+), 116 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 4696f7949..12da40f1d 100755 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -19,120 +19,7 @@ #include #define MUSIG_PREVN 0 // for now, just use vout0 for the musig output - -uint256 musig_msghash(uint256 prevhash,int32_t prevn,CTxOut vout,secp256k1_pubkey combined_pk) -{ - CScript data; - std::vector data; uint256 hash; int32_t len = 0; - data << E_MARSHAL(ss << prevhash << prevn << vout << combined_pk); -fprintf(stderr,"data size %d\n",(int32_t)data.size()); - vcalc_sha256(0,(uint8_t *)&hash,data.ptr(),data.size()); - return(hash); -} - -uint256 musig_prevoutmsg(uint256 sendtxid,CScript scriptPubKey) -{ - CTransaction vintx; uint256 hashBlock; int32_t numvouts; CTxOut vout; secp256k1_pubkey combined_pk; - if ( myGetTransaction(prevhash,vintx,hashBlock) != 0 && (numvouts= vintx.vout.size()) > 1 ) - { - if ( musig_sendopretdecode(combined_pk,vintx.vouts[numvouts-1].scriptPubKey) == 'x' ) - { - vout.nValue = vintx.vout[MUSIG_PREVN].nValue - txfee; - vout.scriptPubKey = scriptPubKey; - return(musig_msghash(prevhash,MUSIG_PREVN,vout,combined_pk)); - } - } - return(zeroid); -} - -UniValue musig_calcmsg(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) -{ - UniValue result(UniValue::VOBJ); uint256 sendtxid,msg; char *scriptstr; int32_t n; - if ( (params= cclib_reparse(&n,params)) != 0 ) - { - if ( n == 2 ) - { - sendtxid = juint256(jitem(params,0)); - scriptstr = jstr(jitem(params,1),0); - if ( is_hexstr(scriptstr,0) != 0 ) - { - CScript scriptPubKey(ParseHex(scriptstr)); - msg = musig_prevoutmsg(sendtxid,scriptPubKey); - result.push_back("result","success"); - result.push_back("msg",msg.GetHex()); - return(result); - } else return(cclib_error(result,"script is not hex")); - } else return(cclib_error(result,"need exactly 2 parameters: sendtxid, scriptPubKey")); - } else return(cclib_error(result,"couldnt parse params")); -} - -UniValue musig_combine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) -{ - UniValue result(UniValue::VOBJ); - result.push_back("result","success"); - return(result); -} - -UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) -{ - UniValue result(UniValue::VOBJ); - result.push_back("result","success"); - return(result); -} - -UniValue musig_commit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) -{ - UniValue result(UniValue::VOBJ); - result.push_back("result","success"); - return(result); -} - -UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) -{ - UniValue result(UniValue::VOBJ); - result.push_back("result","success"); - return(result); -} - -UniValue musig_partialsign(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) -{ - UniValue result(UniValue::VOBJ); - result.push_back("result","success"); - return(result); -} - -UniValue musig_sigcombine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) -{ - UniValue result(UniValue::VOBJ); - result.push_back("result","success"); - return(result); -} - -UniValue musig_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) -{ - UniValue result(UniValue::VOBJ); - result.push_back("result","success"); - return(result); -} - -// helpers for rpc calls that generate/validate onchain tx - -UniValue musig_rawtxresult(UniValue &result,std::string rawtx) -{ - CTransaction tx; - if ( rawtx.size() > 0 ) - { - result.push_back(Pair("hex",rawtx)); - if ( DecodeHexTx(tx,rawtx) != 0 ) - { - //if ( broadcastflag != 0 && myAddtomempool(tx) != 0 ) - // RelayTransaction(tx); - result.push_back(Pair("txid",tx.GetHash().ToString())); - result.push_back(Pair("result","success")); - } else result.push_back(Pair("error","decode hex")); - } else result.push_back(Pair("error","couldnt finalize CCtx")); - return(result); -} +#define MUSIG_TXFEE 10000 CScript musig_sendopret(uint8_t funcid,secp256k1_pubkey combined_pk) { @@ -170,12 +57,125 @@ uint8_t musig_spendopretdecode(secp256k1_pubkey &combined_pk,secp256k1_schnorrsi return(0); } +uint256 musig_msghash(uint256 prevhash,int32_t prevn,CTxOut vout,secp256k1_pubkey combined_pk) +{ + CScript data; uint256 hash; int32_t len = 0; + data << E_MARSHAL(ss << prevhash << prevn << vout << combined_pk); +fprintf(stderr,"data size %d\n",(int32_t)data.size()); + vcalc_sha256(0,(uint8_t *)&hash,data.data(),data.size()); + return(hash); +} + +uint256 musig_prevoutmsg(uint256 sendtxid,CScript scriptPubKey) +{ + CTransaction vintx; uint256 hashBlock; int32_t numvouts; CTxOut vout; secp256k1_pubkey combined_pk; + if ( myGetTransaction(sendtxid,vintx,hashBlock) != 0 && (numvouts= vintx.vout.size()) > 1 ) + { + if ( musig_sendopretdecode(combined_pk,vintx.vout[numvouts-1].scriptPubKey) == 'x' ) + { + vout.nValue = vintx.vout[MUSIG_PREVN].nValue - MUSIG_TXFEE; + vout.scriptPubKey = scriptPubKey; + return(musig_msghash(sendtxid,MUSIG_PREVN,vout,combined_pk)); + } + } + return(zeroid); +} + +UniValue musig_calcmsg(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ); uint256 sendtxid,msg; char *scriptstr; int32_t n; + if ( (params= cclib_reparse(&n,params)) != 0 ) + { + if ( n == 2 ) + { + sendtxid = juint256(jitem(params,0)); + scriptstr = jstr(jitem(params,1),0); + if ( is_hexstr(scriptstr,0) != 0 ) + { + CScript scriptPubKey(ParseHex(scriptstr)); + msg = musig_prevoutmsg(sendtxid,scriptPubKey); + result.push_back(Pair("result","success")); + result.push_back(Pair("msg",msg.GetHex())); + return(result); + } else return(cclib_error(result,"script is not hex")); + } else return(cclib_error(result,"need exactly 2 parameters: sendtxid, scriptPubKey")); + } else return(cclib_error(result,"couldnt parse params")); +} + +UniValue musig_combine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ); + result.push_back(Pair("result","success")); + return(result); +} + +UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ); + result.push_back(Pair("result","success")); + return(result); +} + +UniValue musig_commit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ); + result.push_back(Pair("result","success")); + return(result); +} + +UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ); + result.push_back(Pair("result","success")); + return(result); +} + +UniValue musig_partialsign(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ); + result.push_back(Pair("result","success")); + return(result); +} + +UniValue musig_sigcombine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ); + result.push_back(Pair("result","success")); + return(result); +} + +UniValue musig_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ); + result.push_back(Pair("result","success")); + return(result); +} + +// helpers for rpc calls that generate/validate onchain tx + +UniValue musig_rawtxresult(UniValue &result,std::string rawtx) +{ + CTransaction tx; + if ( rawtx.size() > 0 ) + { + result.push_back(Pair("hex",rawtx)); + if ( DecodeHexTx(tx,rawtx) != 0 ) + { + //if ( broadcastflag != 0 && myAddtomempool(tx) != 0 ) + // RelayTransaction(tx); + result.push_back(Pair("txid",tx.GetHash().ToString())); + result.push_back(Pair("result","success")); + } else result.push_back(Pair("error","decode hex")); + } else result.push_back(Pair("error","couldnt finalize CCtx")); + return(result); +} + UniValue musig_send(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); UniValue result(UniValue::VOBJ); int32_t n; char *hexstr; std::string rawtx; int64_t amount; CPubKey musigpk,mypk; if ( txfee == 0 ) - txfee = 10000; + txfee = MUSIG_TXFEE; mypk = pubkey2pk(Mypubkey()); musigpk = GetUnspendable(cp,0); if ( (params= cclib_reparse(&n,params)) != 0 ) @@ -211,7 +211,7 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) if ( is_hexstr(scriptstr,0) != 0 && is_hexstr(musigstr,0) != 0 ) { if ( txfee == 0 ) - txfee = 10000; + txfee = MUSIG_TXFEE; mypk = pubkey2pk(Mypubkey()); secp256k1_schnorrsig musig(ParseHex(musigstr)); CScript scriptPubKey(ParseHex(scriptstr)); From a2d6ae5e145cff32f35981f71229022785b272a3 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 07:28:27 -1100 Subject: [PATCH 136/390] Msg -> msg[32] --- src/cc/musig.cpp | 34 ++++++++++++++++++---------------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 12da40f1d..6d2a1f583 100755 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -57,16 +57,15 @@ uint8_t musig_spendopretdecode(secp256k1_pubkey &combined_pk,secp256k1_schnorrsi return(0); } -uint256 musig_msghash(uint256 prevhash,int32_t prevn,CTxOut vout,secp256k1_pubkey combined_pk) +void musig_msghash(uint8_t *msg,uint256 prevhash,int32_t prevn,CTxOut vout,secp256k1_pubkey combined_pk) { CScript data; uint256 hash; int32_t len = 0; data << E_MARSHAL(ss << prevhash << prevn << vout << combined_pk); fprintf(stderr,"data size %d\n",(int32_t)data.size()); - vcalc_sha256(0,(uint8_t *)&hash,data.data(),data.size()); - return(hash); + vcalc_sha256(0,msg,data.data(),data.size()); } -uint256 musig_prevoutmsg(uint256 sendtxid,CScript scriptPubKey) +int32_t musig_prevoutmsg(uint8_t *msg,uint256 sendtxid,CScript scriptPubKey) { CTransaction vintx; uint256 hashBlock; int32_t numvouts; CTxOut vout; secp256k1_pubkey combined_pk; if ( myGetTransaction(sendtxid,vintx,hashBlock) != 0 && (numvouts= vintx.vout.size()) > 1 ) @@ -75,7 +74,7 @@ uint256 musig_prevoutmsg(uint256 sendtxid,CScript scriptPubKey) { vout.nValue = vintx.vout[MUSIG_PREVN].nValue - MUSIG_TXFEE; vout.scriptPubKey = scriptPubKey; - return(musig_msghash(sendtxid,MUSIG_PREVN,vout,combined_pk)); + return(musig_msghash(msg,sendtxid,MUSIG_PREVN,vout,combined_pk)); } } return(zeroid); @@ -83,7 +82,7 @@ uint256 musig_prevoutmsg(uint256 sendtxid,CScript scriptPubKey) UniValue musig_calcmsg(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); uint256 sendtxid,msg; char *scriptstr; int32_t n; + UniValue result(UniValue::VOBJ); uint256 sendtxid; int32_t i; uint8_t msg[32]; char *scriptstr,str[65]; int32_t n; if ( (params= cclib_reparse(&n,params)) != 0 ) { if ( n == 2 ) @@ -93,9 +92,12 @@ UniValue musig_calcmsg(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) if ( is_hexstr(scriptstr,0) != 0 ) { CScript scriptPubKey(ParseHex(scriptstr)); - msg = musig_prevoutmsg(sendtxid,scriptPubKey); + musig_prevoutmsg(msg,sendtxid,scriptPubKey); result.push_back(Pair("result","success")); - result.push_back(Pair("msg",msg.GetHex())); + for (i=0; i<32; i++) + sprintf(&str[i<<1],"%02x",msg[i]); + str[64] = 0; + result.push_back(Pair("msg",str)); return(result); } else return(cclib_error(result,"script is not hex")); } else return(cclib_error(result,"need exactly 2 parameters: sendtxid, scriptPubKey")); @@ -198,7 +200,7 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { static secp256k1_context *ctx; CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); std::string rawtx; CPubKey mypk; secp256k1_pubkey combined_pk; char *scriptstr,*musigstr; uint256 msg,prevhash,hashBlock; int32_t n,numvouts; CTxOut vout; + UniValue result(UniValue::VOBJ); std::string rawtx; CPubKey mypk; secp256k1_pubkey combined_pk; char *scriptstr,*musigstr; uint8_t msg[32]; CTransaction vintx; uint256 prevhash,hashBlock; int32_t n,numvouts; CTxOut vout; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); if ( (params= cclib_reparse(&n,params)) != 0 ) @@ -219,9 +221,9 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { vout.nValue = vintx.vout[0].nValue - txfee; vout.scriptPubKey = scriptPubKey; - if ( musig_sendopretdecode(combined_pk,vintx.vouts[numvouts-1].scriptPubKey) == 'x' ) + if ( musig_sendopretdecode(combined_pk,vintx.vout[numvouts-1].scriptPubKey) == 'x' ) { - msg = musig_prevoutmsg(prevhash,vout.scriptPubKey); + musig_prevoutmsg(msg,prevhash,vout.scriptPubKey); if ( !secp256k1_schnorrsig_verify(ctx,&musig,msg,&combined_pk) ) return(cclib_error(result,"musig didnt validate")); mtx.vin.push_back(CTxIn(prevhash,MUSIG_PREVN)); @@ -238,7 +240,7 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) bool musig_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { static secp256k1_context *ctx; - secp256k1_pubkey combined_pk,checkpk; secp256k1_schnorrsig musig; uint256 msg,hashBlock; CTransaction vintx; int32_t numvouts; + secp256k1_pubkey combined_pk,checkpk; secp256k1_schnorrsig musig; uint256 hashBlock; CTransaction vintx; int32_t numvouts; uint8_t msg[32]; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); if ( tx.vout.size() != 2 ) @@ -249,13 +251,13 @@ bool musig_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C return eval->Invalid("illegal normal vin0"); else if ( myGetTransaction(tx.vin[0].prevout.hash,vintx,hashBlock) != 0 && (numvouts= vintx.vout.size()) > 1 ) { - if ( musig_sendopretdecode(combined_pk,vintx.vouts[numvouts-1].scriptPubKey) == 'x' ) + if ( musig_sendopretdecode(combined_pk,vintx.vout[numvouts-1].scriptPubKey) == 'x' ) { - if ( musig_spendopretdecode(check_pk,musig,tx.vout[tx.vout.size()-1].scriptPubKey) == 'y' ) + if ( musig_spendopretdecode(checkpk,musig,tx.vout[tx.vout.size()-1].scriptPubKey) == 'y' ) { - if ( combined_pk == check_pk ) + if ( combined_pk == checkpk ) { - msg = musig_prevoutmsg(tx.vin[0].prevout.hash,tx.vout[0].scriptPubKey); + musig_prevoutmsg(msg,tx.vin[0].prevout.hash,tx.vout[0].scriptPubKey); if ( !secp256k1_schnorrsig_verify(ctx,&musig,msg,&combined_pk) ) return eval->Invalid("failed schnorrsig_verify"); else return(true); From 30edb30e4aca089bbe7fe59246ae1b0aeff35485 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 07:47:39 -1100 Subject: [PATCH 137/390] Serialize pk -> combined_pk --- src/cc/musig.cpp | 76 ++++++++++++++++++++++++++---------------------- 1 file changed, 42 insertions(+), 34 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 6d2a1f583..561851640 100755 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -21,63 +21,65 @@ #define MUSIG_PREVN 0 // for now, just use vout0 for the musig output #define MUSIG_TXFEE 10000 -CScript musig_sendopret(uint8_t funcid,secp256k1_pubkey combined_pk) +CScript musig_sendopret(uint8_t funcid,CPubKey pk) { CScript opret; uint8_t evalcode = EVAL_MUSIG; - opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << combined_pk); + opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << pk); return(opret); } -uint8_t musig_sendopretdecode(secp256k1_pubkey &combined_pk,CScript scriptPubKey) +uint8_t musig_sendopretdecode(CPubKey &pk,CScript scriptPubKey) { std::vector vopret; uint8_t e,f; GetOpReturnData(scriptPubKey,vopret); - if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> combined_pk) != 0 && e == EVAL_MUSIG && f == 'x' ) + if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> pk) != 0 && e == EVAL_MUSIG && f == 'x' ) { return(f); } return(0); } -CScript musig_spendopret(uint8_t funcid,secp256k1_pubkey combined_pk,secp256k1_schnorrsig musig) +CScript musig_spendopret(uint8_t funcid,CPubKey pk,secp256k1_schnorrsig musig) { CScript opret; uint8_t evalcode = EVAL_MUSIG; - opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << combined_pk << musig); + opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << pk << musig); return(opret); } -uint8_t musig_spendopretdecode(secp256k1_pubkey &combined_pk,secp256k1_schnorrsig &musig,CScript scriptPubKey) +uint8_t musig_spendopretdecode(CPubKey &pk,secp256k1_schnorrsig &musig,CScript scriptPubKey) { std::vector vopret; uint8_t e,f; GetOpReturnData(scriptPubKey,vopret); - if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> combined_pk; ss >> musig) != 0 && e == EVAL_MUSIG && f == 'y' ) + if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> pk; ss >> musig) != 0 && e == EVAL_MUSIG && f == 'y' ) { return(f); } return(0); } -void musig_msghash(uint8_t *msg,uint256 prevhash,int32_t prevn,CTxOut vout,secp256k1_pubkey combined_pk) +int32_t musig_msghash(uint8_t *msg,uint256 prevhash,int32_t prevn,CTxOut vout,CPubKey pk) { CScript data; uint256 hash; int32_t len = 0; - data << E_MARSHAL(ss << prevhash << prevn << vout << combined_pk); + data << E_MARSHAL(ss << prevhash << prevn << vout << pk); fprintf(stderr,"data size %d\n",(int32_t)data.size()); - vcalc_sha256(0,msg,data.data(),data.size()); + vcalc_sha256(0,msg,data.begin(),data.size()); + return(0); } int32_t musig_prevoutmsg(uint8_t *msg,uint256 sendtxid,CScript scriptPubKey) { - CTransaction vintx; uint256 hashBlock; int32_t numvouts; CTxOut vout; secp256k1_pubkey combined_pk; + CTransaction vintx; uint256 hashBlock; int32_t numvouts; CTxOut vout; CPubKey pk; + memset(msg,0,32); if ( myGetTransaction(sendtxid,vintx,hashBlock) != 0 && (numvouts= vintx.vout.size()) > 1 ) { - if ( musig_sendopretdecode(combined_pk,vintx.vout[numvouts-1].scriptPubKey) == 'x' ) + if ( musig_sendopretdecode(pk,vintx.vout[numvouts-1].scriptPubKey) == 'x' ) { vout.nValue = vintx.vout[MUSIG_PREVN].nValue - MUSIG_TXFEE; vout.scriptPubKey = scriptPubKey; - return(musig_msghash(msg,sendtxid,MUSIG_PREVN,vout,combined_pk)); + return(musig_msghash(msg,sendtxid,MUSIG_PREVN,vout,pk)); } } - return(zeroid); + return(-1); } UniValue musig_calcmsg(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) @@ -184,15 +186,15 @@ UniValue musig_send(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { if ( n == 2 && (hexstr= jstr(jitem(params,0),0)) != 0 && is_hexstr(hexstr,0) == 66 ) { - secp256k1_pubkey combined_pk(ParseHex(hexstr)); + CPubKey pk(ParseHex(hexstr)); amount = jdouble(jitem(params,1),0) * COIN + 0.0000000049; if ( amount >= 3*txfee && AddNormalinputs(mtx,mypk,amount+2*txfee,64) >= amount+2*txfee ) { mtx.vout.push_back(MakeCC1vout(cp->evalcode,amount+txfee,musigpk)); - rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,musig_sendopret('x',combined_pk)); + rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,musig_sendopret('x',pk)); return(musig_rawtxresult(result,rawtx)); } else return(cclib_error(result,"couldnt find funds or less than 0.0003")); - } else return(cclib_error(result,"must have 2 params: combined_pk, amount")); + } else return(cclib_error(result,"must have 2 params: pk, amount")); } else return(cclib_error(result,"not enough parameters")); } @@ -200,7 +202,7 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { static secp256k1_context *ctx; CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); std::string rawtx; CPubKey mypk; secp256k1_pubkey combined_pk; char *scriptstr,*musigstr; uint8_t msg[32]; CTransaction vintx; uint256 prevhash,hashBlock; int32_t n,numvouts; CTxOut vout; + UniValue result(UniValue::VOBJ); std::string rawtx; CPubKey mypk,pk; secp256k1_pubkey combined_pk; char *scriptstr,*musigstr; uint8_t msg[32]; CTransaction vintx; uint256 prevhash,hashBlock; int32_t n,numvouts; CTxOut vout; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); if ( (params= cclib_reparse(&n,params)) != 0 ) @@ -221,15 +223,18 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { vout.nValue = vintx.vout[0].nValue - txfee; vout.scriptPubKey = scriptPubKey; - if ( musig_sendopretdecode(combined_pk,vintx.vout[numvouts-1].scriptPubKey) == 'x' ) + if ( musig_sendopretdecode(pk,vintx.vout[numvouts-1].scriptPubKey) == 'x' ) { - musig_prevoutmsg(msg,prevhash,vout.scriptPubKey); - if ( !secp256k1_schnorrsig_verify(ctx,&musig,msg,&combined_pk) ) - return(cclib_error(result,"musig didnt validate")); - mtx.vin.push_back(CTxIn(prevhash,MUSIG_PREVN)); - mtx.vout.push_back(vout); - rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,musig_spendopret('y',combined_pk,musig)); - return(musig_rawtxresult(result,rawtx)); + if ( secp256k1_ec_pubkey_parse(ctx,&combined_pk,pk.begin(),33) > 0 ) + { + musig_prevoutmsg(msg,prevhash,vout.scriptPubKey); + if ( !secp256k1_schnorrsig_verify(ctx,&musig,msg,&combined_pk) ) + return(cclib_error(result,"musig didnt validate")); + mtx.vin.push_back(CTxIn(prevhash,MUSIG_PREVN)); + mtx.vout.push_back(vout); + rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,musig_spendopret('y',pk,musig)); + return(musig_rawtxresult(result,rawtx)); + } else return(cclib_error(result,"couldnt parse pk")); } else return(cclib_error(result,"couldnt decode send opret")); } else return(cclib_error(result,"couldnt find vin0")); } else return(cclib_error(result,"script or musig is not hex")); @@ -240,7 +245,7 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) bool musig_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { static secp256k1_context *ctx; - secp256k1_pubkey combined_pk,checkpk; secp256k1_schnorrsig musig; uint256 hashBlock; CTransaction vintx; int32_t numvouts; uint8_t msg[32]; + secp256k1_pubkey combined_pk; CPubKey pk,checkpk; secp256k1_schnorrsig musig; uint256 hashBlock; CTransaction vintx; int32_t numvouts; uint8_t msg[32]; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); if ( tx.vout.size() != 2 ) @@ -251,16 +256,19 @@ bool musig_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C return eval->Invalid("illegal normal vin0"); else if ( myGetTransaction(tx.vin[0].prevout.hash,vintx,hashBlock) != 0 && (numvouts= vintx.vout.size()) > 1 ) { - if ( musig_sendopretdecode(combined_pk,vintx.vout[numvouts-1].scriptPubKey) == 'x' ) + if ( musig_sendopretdecode(pk,vintx.vout[numvouts-1].scriptPubKey) == 'x' ) { if ( musig_spendopretdecode(checkpk,musig,tx.vout[tx.vout.size()-1].scriptPubKey) == 'y' ) { - if ( combined_pk == checkpk ) + if ( pk == checkpk ) { - musig_prevoutmsg(msg,tx.vin[0].prevout.hash,tx.vout[0].scriptPubKey); - if ( !secp256k1_schnorrsig_verify(ctx,&musig,msg,&combined_pk) ) - return eval->Invalid("failed schnorrsig_verify"); - else return(true); + if ( secp256k1_ec_pubkey_parse(ctx,&combined_pk,pk.begin(),33) > 0 ) + { + musig_prevoutmsg(msg,tx.vin[0].prevout.hash,tx.vout[0].scriptPubKey); + if ( !secp256k1_schnorrsig_verify(ctx,&musig,msg,&combined_pk) ) + return eval->Invalid("failed schnorrsig_verify"); + else return(true); + } else return eval->Invalid("couldnt parse pk"); } else return eval->Invalid("combined_pk didnt match send opret"); } else return eval->Invalid("failed decode musig spendopret"); } else return eval->Invalid("couldnt decode send opret"); From 8de3c71baa8ab11903439d50f8e0191a326ce112 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 07:56:45 -1100 Subject: [PATCH 138/390] musig64 --- src/cc/musig.cpp | 30 ++++++++++++++++-------------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 561851640..64d7528b6 100755 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -39,18 +39,18 @@ uint8_t musig_sendopretdecode(CPubKey &pk,CScript scriptPubKey) return(0); } -CScript musig_spendopret(uint8_t funcid,CPubKey pk,secp256k1_schnorrsig musig) +CScript musig_spendopret(uint8_t funcid,CPubKey pk,std::vector musig64) { CScript opret; uint8_t evalcode = EVAL_MUSIG; - opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << pk << musig); + opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << pk << musig64); return(opret); } -uint8_t musig_spendopretdecode(CPubKey &pk,secp256k1_schnorrsig &musig,CScript scriptPubKey) +uint8_t musig_spendopretdecode(CPubKey &pk,std::vector &musig64,CScript scriptPubKey) { std::vector vopret; uint8_t e,f; GetOpReturnData(scriptPubKey,vopret); - if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> pk; ss >> musig) != 0 && e == EVAL_MUSIG && f == 'y' ) + if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> pk; ss >> musig64) != 0 && e == EVAL_MUSIG && f == 'y' ) { return(f); } @@ -62,7 +62,7 @@ int32_t musig_msghash(uint8_t *msg,uint256 prevhash,int32_t prevn,CTxOut vout,CP CScript data; uint256 hash; int32_t len = 0; data << E_MARSHAL(ss << prevhash << prevn << vout << pk); fprintf(stderr,"data size %d\n",(int32_t)data.size()); - vcalc_sha256(0,msg,data.begin(),data.size()); + vcalc_sha256(0,msg,data.begin(),(int32_t)data.size()); return(0); } @@ -212,12 +212,12 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) prevhash = juint256(jitem(params,0)); scriptstr = jstr(jitem(params,1),0); musigstr = jstr(jitem(params,2),0); - if ( is_hexstr(scriptstr,0) != 0 && is_hexstr(musigstr,0) != 0 ) + if ( is_hexstr(scriptstr,0) != 0 && is_hexstr(musigstr,0) != 128 ) { if ( txfee == 0 ) txfee = MUSIG_TXFEE; mypk = pubkey2pk(Mypubkey()); - secp256k1_schnorrsig musig(ParseHex(musigstr)); + std::vector musig64(ParseHex(musigstr)); CScript scriptPubKey(ParseHex(scriptstr)); if ( myGetTransaction(prevhash,vintx,hashBlock) != 0 && (numvouts= vintx.vout.size()) > 1 ) { @@ -225,16 +225,17 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) vout.scriptPubKey = scriptPubKey; if ( musig_sendopretdecode(pk,vintx.vout[numvouts-1].scriptPubKey) == 'x' ) { - if ( secp256k1_ec_pubkey_parse(ctx,&combined_pk,pk.begin(),33) > 0 ) + if ( secp256k1_schnorrsig_parse(ctx,&musig,&musig64[0]) > 0 && + secp256k1_ec_pubkey_parse(ctx,&combined_pk,pk.begin(),33) > 0 ) { musig_prevoutmsg(msg,prevhash,vout.scriptPubKey); if ( !secp256k1_schnorrsig_verify(ctx,&musig,msg,&combined_pk) ) return(cclib_error(result,"musig didnt validate")); mtx.vin.push_back(CTxIn(prevhash,MUSIG_PREVN)); mtx.vout.push_back(vout); - rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,musig_spendopret('y',pk,musig)); + rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,musig_spendopret('y',pk,musig64)); return(musig_rawtxresult(result,rawtx)); - } else return(cclib_error(result,"couldnt parse pk")); + } else return(cclib_error(result,"couldnt parse pk or musig")); } else return(cclib_error(result,"couldnt decode send opret")); } else return(cclib_error(result,"couldnt find vin0")); } else return(cclib_error(result,"script or musig is not hex")); @@ -245,7 +246,7 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) bool musig_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { static secp256k1_context *ctx; - secp256k1_pubkey combined_pk; CPubKey pk,checkpk; secp256k1_schnorrsig musig; uint256 hashBlock; CTransaction vintx; int32_t numvouts; uint8_t msg[32]; + secp256k1_pubkey combined_pk; CPubKey pk,checkpk; secp256k1_schnorrsig musig; uint256 hashBlock; CTransaction vintx; int32_t numvouts; std::vector musig64; uint8_t msg[32]; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); if ( tx.vout.size() != 2 ) @@ -258,17 +259,18 @@ bool musig_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C { if ( musig_sendopretdecode(pk,vintx.vout[numvouts-1].scriptPubKey) == 'x' ) { - if ( musig_spendopretdecode(checkpk,musig,tx.vout[tx.vout.size()-1].scriptPubKey) == 'y' ) + if ( musig_spendopretdecode(checkpk,musig64,tx.vout[tx.vout.size()-1].scriptPubKey) == 'y' ) { if ( pk == checkpk ) { - if ( secp256k1_ec_pubkey_parse(ctx,&combined_pk,pk.begin(),33) > 0 ) + if ( secp256k1_schnorrsig_parse(ctx,&musig,&musig64[0]) > 0 && + secp256k1_ec_pubkey_parse(ctx,&combined_pk,pk.begin(),33) > 0 ) { musig_prevoutmsg(msg,tx.vin[0].prevout.hash,tx.vout[0].scriptPubKey); if ( !secp256k1_schnorrsig_verify(ctx,&musig,msg,&combined_pk) ) return eval->Invalid("failed schnorrsig_verify"); else return(true); - } else return eval->Invalid("couldnt parse pk"); + } else return eval->Invalid("couldnt parse pk or musig"); } else return eval->Invalid("combined_pk didnt match send opret"); } else return eval->Invalid("failed decode musig spendopret"); } else return eval->Invalid("couldnt decode send opret"); From 6ed384ff471be6653e0084f7b8fcf0e524e6611e Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 08:07:05 -1100 Subject: [PATCH 139/390] Fixes --- src/cc/musig.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 64d7528b6..c12866865 100755 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -62,7 +62,8 @@ int32_t musig_msghash(uint8_t *msg,uint256 prevhash,int32_t prevn,CTxOut vout,CP CScript data; uint256 hash; int32_t len = 0; data << E_MARSHAL(ss << prevhash << prevn << vout << pk); fprintf(stderr,"data size %d\n",(int32_t)data.size()); - vcalc_sha256(0,msg,data.begin(),(int32_t)data.size()); + hash = Hash(data.begin(),data.end()); + memcpy(msg,&hash,sizeof(hash)); return(0); } @@ -202,7 +203,7 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { static secp256k1_context *ctx; CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); std::string rawtx; CPubKey mypk,pk; secp256k1_pubkey combined_pk; char *scriptstr,*musigstr; uint8_t msg[32]; CTransaction vintx; uint256 prevhash,hashBlock; int32_t n,numvouts; CTxOut vout; + UniValue result(UniValue::VOBJ); std::string rawtx; CPubKey mypk,pk; secp256k1_pubkey combined_pk; char *scriptstr,*musigstr; uint8_t msg[32]; CTransaction vintx; uint256 prevhash,hashBlock; int32_t n,numvouts; CTxOut vout; secp256k1_schnorrsig musig; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); if ( (params= cclib_reparse(&n,params)) != 0 ) From fb69ddb0c66c37f949b3e007720162344c7e4b8b Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 08:12:36 -1100 Subject: [PATCH 140/390] Add modules --- src/secp256k1/Makefile.am | 5 ----- src/secp256k1/src/secp256k1.c | 6 ++++++ 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/secp256k1/Makefile.am b/src/secp256k1/Makefile.am index 676415834..089d3ee8e 100644 --- a/src/secp256k1/Makefile.am +++ b/src/secp256k1/Makefile.am @@ -174,11 +174,6 @@ if ENABLE_MODULE_ECDH include src/modules/ecdh/Makefile.am.include endif -#if ENABLE_MODULE_MUSIG -include src/modules/schnorrsig/Makefile.am.include -include src/modules/musig/Makefile.am.include -#endif - if ENABLE_MODULE_RECOVERY include src/modules/recovery/Makefile.am.include endif diff --git a/src/secp256k1/src/secp256k1.c b/src/secp256k1/src/secp256k1.c index b89a7c04a..2cf57856b 100644 --- a/src/secp256k1/src/secp256k1.c +++ b/src/secp256k1/src/secp256k1.c @@ -580,6 +580,12 @@ int secp256k1_ec_pubkey_combine(const secp256k1_context* ctx, secp256k1_pubkey * # include "modules/ecdh/main_impl.h" #endif +#ifdef ENABLE_MODULE_MUSIG +#include "modules/schnorrsig/main_impl.h" +#include "modules/musig/main_impl.h" +#endif + + #ifdef ENABLE_MODULE_RECOVERY # include "modules/recovery/main_impl.h" #endif From 88d08c07fa1ebce2f59216f2719014e198a41d2d Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 08:17:34 -1100 Subject: [PATCH 141/390] secp256k1_nonce_function_bipschnorr --- src/secp256k1/src/secp256k1.c | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/src/secp256k1/src/secp256k1.c b/src/secp256k1/src/secp256k1.c index 2cf57856b..fbff4b3aa 100644 --- a/src/secp256k1/src/secp256k1.c +++ b/src/secp256k1/src/secp256k1.c @@ -340,6 +340,27 @@ static int nonce_function_rfc6979(unsigned char *nonce32, const unsigned char *m return 1; } +/* This nonce function is described in BIP-schnorr + * (https://github.com/sipa/bips/blob/bip-schnorr/bip-schnorr.mediawiki) */ +static int secp256k1_nonce_function_bipschnorr(unsigned char *nonce32, const unsigned char *msg32, const unsigned char *key32, const unsigned char *algo16, void *data, unsigned int counter) { + secp256k1_sha256 sha; + (void) data; + (void) counter; + VERIFY_CHECK(counter == 0); + + /* Hash x||msg as per the spec */ + secp256k1_sha256_initialize(&sha); + secp256k1_sha256_write(&sha, key32, 32); + secp256k1_sha256_write(&sha, msg32, 32); + /* Hash in algorithm, which is not in the spec, but may be critical to + * users depending on it to avoid nonce reuse across algorithms. */ + if (algo16 != NULL) { + secp256k1_sha256_write(&sha, algo16, 16); + } + secp256k1_sha256_finalize(&sha, nonce32); + return 1; +} + const secp256k1_nonce_function secp256k1_nonce_function_rfc6979 = nonce_function_rfc6979; const secp256k1_nonce_function secp256k1_nonce_function_default = nonce_function_rfc6979; From 6adebc5e7bf3a82cfbaf8b0b35e06df8a4cbaf6b Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 08:19:37 -1100 Subject: [PATCH 142/390] Test --- src/secp256k1/src/modules/schnorrsig/main_impl.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/secp256k1/src/modules/schnorrsig/main_impl.h b/src/secp256k1/src/modules/schnorrsig/main_impl.h index b366236d8..6ccec1523 100644 --- a/src/secp256k1/src/modules/schnorrsig/main_impl.h +++ b/src/secp256k1/src/modules/schnorrsig/main_impl.h @@ -10,7 +10,7 @@ #include "include/secp256k1.h" #include "include/secp256k1_schnorrsig.h" #include "hash.h" - +hello int secp256k1_schnorrsig_serialize(const secp256k1_context* ctx, unsigned char *out64, const secp256k1_schnorrsig* sig) { (void) ctx; VERIFY_CHECK(ctx != NULL); From 0a433f453bd4098de592b12219f545655aa04c06 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 08:20:59 -1100 Subject: [PATCH 143/390] ENABLE_MODULE_MUSIG --- src/secp256k1/src/modules/schnorrsig/main_impl.h | 2 +- src/secp256k1/src/secp256k1.c | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/secp256k1/src/modules/schnorrsig/main_impl.h b/src/secp256k1/src/modules/schnorrsig/main_impl.h index 6ccec1523..b366236d8 100644 --- a/src/secp256k1/src/modules/schnorrsig/main_impl.h +++ b/src/secp256k1/src/modules/schnorrsig/main_impl.h @@ -10,7 +10,7 @@ #include "include/secp256k1.h" #include "include/secp256k1_schnorrsig.h" #include "hash.h" -hello + int secp256k1_schnorrsig_serialize(const secp256k1_context* ctx, unsigned char *out64, const secp256k1_schnorrsig* sig) { (void) ctx; VERIFY_CHECK(ctx != NULL); diff --git a/src/secp256k1/src/secp256k1.c b/src/secp256k1/src/secp256k1.c index fbff4b3aa..1f04af395 100644 --- a/src/secp256k1/src/secp256k1.c +++ b/src/secp256k1/src/secp256k1.c @@ -4,6 +4,7 @@ * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ +#define ENABLE_MODULE_MUSIG #include "include/secp256k1.h" #include "util.h" From 965abd3d526caa3f87188cb62836b29a9f798115 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 08:23:06 -1100 Subject: [PATCH 144/390] Force include --- src/secp256k1/src/secp256k1.c | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/secp256k1/src/secp256k1.c b/src/secp256k1/src/secp256k1.c index 1f04af395..4c24c1084 100644 --- a/src/secp256k1/src/secp256k1.c +++ b/src/secp256k1/src/secp256k1.c @@ -4,7 +4,6 @@ * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ -#define ENABLE_MODULE_MUSIG #include "include/secp256k1.h" #include "util.h" @@ -602,10 +601,10 @@ int secp256k1_ec_pubkey_combine(const secp256k1_context* ctx, secp256k1_pubkey * # include "modules/ecdh/main_impl.h" #endif -#ifdef ENABLE_MODULE_MUSIG +//#ifdef ENABLE_MODULE_MUSIG #include "modules/schnorrsig/main_impl.h" #include "modules/musig/main_impl.h" -#endif +//#endif #ifdef ENABLE_MODULE_RECOVERY From 5944b3e64fce54a06a5dbbe971fac12c617645cd Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 08:25:10 -1100 Subject: [PATCH 145/390] Test --- src/secp256k1/src/secp256k1.c | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/secp256k1/src/secp256k1.c b/src/secp256k1/src/secp256k1.c index 4c24c1084..1c7b75bc5 100644 --- a/src/secp256k1/src/secp256k1.c +++ b/src/secp256k1/src/secp256k1.c @@ -601,10 +601,8 @@ int secp256k1_ec_pubkey_combine(const secp256k1_context* ctx, secp256k1_pubkey * # include "modules/ecdh/main_impl.h" #endif -//#ifdef ENABLE_MODULE_MUSIG #include "modules/schnorrsig/main_impl.h" #include "modules/musig/main_impl.h" -//#endif #ifdef ENABLE_MODULE_RECOVERY From 8de28666e0e18373444888d390be2ded4ea2795e Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 08:34:19 -1100 Subject: [PATCH 146/390] $(LIBSECP256K1) --- src/Makefile.am | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Makefile.am b/src/Makefile.am index 395ff0352..22668c91f 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -574,9 +574,9 @@ komodod_LDADD += \ $(LIBZCASH_LIBS) if TARGET_DARWIN -komodod_LDADD += libcc.dylib +komodod_LDADD += libcc.dylib $(LIBSECP256K1) else -komodod_LDADD += libcc.so +komodod_LDADD += libcc.so $(LIBSECP256K1) endif From 9ca5858eebdca923517dd5e786c6d63034dd2bcf Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 08:41:10 -1100 Subject: [PATCH 147/390] Include secp --- src/cc/cclib.cpp | 1 + src/cc/makecclib | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 0d907d4ca..f02d63dbd 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -579,6 +579,7 @@ cJSON *cclib_reparse(int32_t *nump,cJSON *origparams) // assumes origparams will #else #include "sudoku.cpp" +#include "../secp256k1/src/secp256k1.c" #include "musig.cpp" #endif diff --git a/src/cc/makecclib b/src/cc/makecclib index 832cf1e96..871569325 100755 --- a/src/cc/makecclib +++ b/src/cc/makecclib @@ -1,2 +1,2 @@ #!/bin/sh -gcc -std=c++11 -I../secp256k1/include -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -c -o ../libcc.so cclib.cpp +gcc -std=c++11 -I../secp256k1/include -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -c -o ../libcc.so cclib.cpp ../secp256k1/libsecp256k1.la From 38e67bca763fed2b6d2b618d5089019ac1b145fd Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 08:45:05 -1100 Subject: [PATCH 148/390] ../include --- src/cc/makecclib | 2 +- src/secp256k1/src/secp256k1.c | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/makecclib b/src/cc/makecclib index 871569325..f4d2bd01b 100755 --- a/src/cc/makecclib +++ b/src/cc/makecclib @@ -1,2 +1,2 @@ #!/bin/sh -gcc -std=c++11 -I../secp256k1/include -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -c -o ../libcc.so cclib.cpp ../secp256k1/libsecp256k1.la +gcc -std=c++11 -I../secp256k1/include -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -c -o ../libcc.so cclib.cpp diff --git a/src/secp256k1/src/secp256k1.c b/src/secp256k1/src/secp256k1.c index 1c7b75bc5..657893d0d 100644 --- a/src/secp256k1/src/secp256k1.c +++ b/src/secp256k1/src/secp256k1.c @@ -4,7 +4,7 @@ * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ -#include "include/secp256k1.h" +#include "../include/secp256k1.h" #include "util.h" #include "num_impl.h" From b82b61d772c9b321ff662b49a888d8464051a8fb Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 08:50:03 -1100 Subject: [PATCH 149/390] -DSECP256K1_BUILD --- src/cc/cclib.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index f02d63dbd..3cfb1a185 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -579,6 +579,7 @@ cJSON *cclib_reparse(int32_t *nump,cJSON *origparams) // assumes origparams will #else #include "sudoku.cpp" +#define SECP256K1_BUILD #include "../secp256k1/src/secp256k1.c" #include "musig.cpp" #endif From 8ce89adfe711d8972d72c48b4cd8442cd65ca349 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 08:55:49 -1100 Subject: [PATCH 150/390] Basic-config --- src/cc/cclib.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 3cfb1a185..88fa9b554 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -579,7 +579,7 @@ cJSON *cclib_reparse(int32_t *nump,cJSON *origparams) // assumes origparams will #else #include "sudoku.cpp" -#define SECP256K1_BUILD +#include "../secp256k1/src/basic-config.h" #include "../secp256k1/src/secp256k1.c" #include "musig.cpp" #endif From d745071b2abc938668eaea61517a00fcb35c332a Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 08:59:00 -1100 Subject: [PATCH 151/390] USE_BASIC_CONFIG --- src/cc/cclib.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 88fa9b554..1fc8c45a7 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -579,6 +579,7 @@ cJSON *cclib_reparse(int32_t *nump,cJSON *origparams) // assumes origparams will #else #include "sudoku.cpp" +#define USE_BASIC_CONFIG #include "../secp256k1/src/basic-config.h" #include "../secp256k1/src/secp256k1.c" #include "musig.cpp" From 5d7ffa476033156a598430775e57e6992e839e66 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 09:01:29 -1100 Subject: [PATCH 152/390] ../../.. --- src/secp256k1/src/modules/musig/main_impl.h | 4 ++-- src/secp256k1/src/modules/schnorrsig/main_impl.h | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/secp256k1/src/modules/musig/main_impl.h b/src/secp256k1/src/modules/musig/main_impl.h index dece823d6..8bd2f1831 100644 --- a/src/secp256k1/src/modules/musig/main_impl.h +++ b/src/secp256k1/src/modules/musig/main_impl.h @@ -8,8 +8,8 @@ #ifndef _SECP256K1_MODULE_MUSIG_MAIN_ #define _SECP256K1_MODULE_MUSIG_MAIN_ -#include "include/secp256k1.h" -#include "include/secp256k1_musig.h" +#include "../../../include/secp256k1.h" +#include "../../../include/secp256k1_musig.h" #include "hash.h" /* Computes ell = SHA256(pk[0], ..., pk[np-1]) */ diff --git a/src/secp256k1/src/modules/schnorrsig/main_impl.h b/src/secp256k1/src/modules/schnorrsig/main_impl.h index b366236d8..f2b418159 100644 --- a/src/secp256k1/src/modules/schnorrsig/main_impl.h +++ b/src/secp256k1/src/modules/schnorrsig/main_impl.h @@ -7,8 +7,8 @@ #ifndef _SECP256K1_MODULE_SCHNORRSIG_MAIN_ #define _SECP256K1_MODULE_SCHNORRSIG_MAIN_ -#include "include/secp256k1.h" -#include "include/secp256k1_schnorrsig.h" +#include "../../../include/secp256k1.h" +#include "../../../include/secp256k1_schnorrsig.h" #include "hash.h" int secp256k1_schnorrsig_serialize(const secp256k1_context* ctx, unsigned char *out64, const secp256k1_schnorrsig* sig) { From 96c6f295339ddb1f9f5f92b55e41fa4b33ec4ea4 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 09:06:09 -1100 Subject: [PATCH 153/390] Define funds --- src/secp256k1/src/modules/schnorrsig/main_impl.h | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/secp256k1/src/modules/schnorrsig/main_impl.h b/src/secp256k1/src/modules/schnorrsig/main_impl.h index f2b418159..9a08e81d8 100644 --- a/src/secp256k1/src/modules/schnorrsig/main_impl.h +++ b/src/secp256k1/src/modules/schnorrsig/main_impl.h @@ -11,6 +11,9 @@ #include "../../../include/secp256k1_schnorrsig.h" #include "hash.h" +static void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx); +static int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n); + int secp256k1_schnorrsig_serialize(const secp256k1_context* ctx, unsigned char *out64, const secp256k1_schnorrsig* sig) { (void) ctx; VERIFY_CHECK(ctx != NULL); From 23a530ae4ebb7dc2f23c06aeecce591a9fc2c117 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 09:09:43 -1100 Subject: [PATCH 154/390] static int secp256k1_musig_pubkey_combine_callback(secp256k1_scalar *sc, secp256k1_ge *pt, size_t idx, void *data) --- src/secp256k1/src/modules/schnorrsig/main_impl.h | 1 + 1 file changed, 1 insertion(+) diff --git a/src/secp256k1/src/modules/schnorrsig/main_impl.h b/src/secp256k1/src/modules/schnorrsig/main_impl.h index 9a08e81d8..00f241020 100644 --- a/src/secp256k1/src/modules/schnorrsig/main_impl.h +++ b/src/secp256k1/src/modules/schnorrsig/main_impl.h @@ -13,6 +13,7 @@ static void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx); static int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n); +typedef int (secp256k1_ecmult_multi_callback)(secp256k1_scalar *sc, secp256k1_ge *pt, size_t idx, void *data); int secp256k1_schnorrsig_serialize(const secp256k1_context* ctx, unsigned char *out64, const secp256k1_schnorrsig* sig) { (void) ctx; From c1264e8ddb42fae26bb3c128ae204391416706e2 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 09:12:08 -1100 Subject: [PATCH 155/390] Reorder --- src/secp256k1/src/modules/schnorrsig/main_impl.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/secp256k1/src/modules/schnorrsig/main_impl.h b/src/secp256k1/src/modules/schnorrsig/main_impl.h index 00f241020..2eb939f55 100644 --- a/src/secp256k1/src/modules/schnorrsig/main_impl.h +++ b/src/secp256k1/src/modules/schnorrsig/main_impl.h @@ -11,9 +11,9 @@ #include "../../../include/secp256k1_schnorrsig.h" #include "hash.h" +typedef int (secp256k1_ecmult_multi_callback)(secp256k1_scalar *sc, secp256k1_ge *pt, size_t idx, void *data); static void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx); static int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n); -typedef int (secp256k1_ecmult_multi_callback)(secp256k1_scalar *sc, secp256k1_ge *pt, size_t idx, void *data); int secp256k1_schnorrsig_serialize(const secp256k1_context* ctx, unsigned char *out64, const secp256k1_schnorrsig* sig) { (void) ctx; From dfb71e518242d8ea2bef87a9cb2647e5915c1542 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 09:14:59 -1100 Subject: [PATCH 156/390] e tes --- src/cc/cclib.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 1fc8c45a7..33b76ff91 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -579,9 +579,9 @@ cJSON *cclib_reparse(int32_t *nump,cJSON *origparams) // assumes origparams will #else #include "sudoku.cpp" -#define USE_BASIC_CONFIG -#include "../secp256k1/src/basic-config.h" -#include "../secp256k1/src/secp256k1.c" +//#define USE_BASIC_CONFIG +//#include "../secp256k1/src/basic-config.h" +//#include "../secp256k1/src/secp256k1.c" #include "musig.cpp" #endif From e4494dc1207d38a16a26166c760c417b8bab1197 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 09:16:35 -1100 Subject: [PATCH 157/390] Test --- src/cc/musig.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index c12866865..34561d820 100755 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -14,9 +14,9 @@ ******************************************************************************/ -#include -#include -#include +#include "../secp256k1/include/secp256k1.h" +#include "../secp256k1/include/secp256k1_schnorrsig.h" +#include "../secp256k1/include/secp256k1_musig.h" #define MUSIG_PREVN 0 // for now, just use vout0 for the musig output #define MUSIG_TXFEE 10000 From 60122c9eeca2a91331eae3ed8dd50c8369552fbe Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 09:23:32 -1100 Subject: [PATCH 158/390] (const uint8_t *) --- src/cc/musig.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 34561d820..800102e13 100755 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -226,11 +226,11 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) vout.scriptPubKey = scriptPubKey; if ( musig_sendopretdecode(pk,vintx.vout[numvouts-1].scriptPubKey) == 'x' ) { - if ( secp256k1_schnorrsig_parse(ctx,&musig,&musig64[0]) > 0 && + if ( secp256k1_schnorrsig_parse((const secp256k1_context *)ctx,&musig,(const uint8_t *)&musig64[0]) > 0 && secp256k1_ec_pubkey_parse(ctx,&combined_pk,pk.begin(),33) > 0 ) { musig_prevoutmsg(msg,prevhash,vout.scriptPubKey); - if ( !secp256k1_schnorrsig_verify(ctx,&musig,msg,&combined_pk) ) + if ( !secp256k1_schnorrsig_verify((const secp256k1_context *)ctx,&musig,(const uint8_t *)msg,(const secp256k1_pubkey *)&combined_pk) ) return(cclib_error(result,"musig didnt validate")); mtx.vin.push_back(CTxIn(prevhash,MUSIG_PREVN)); mtx.vout.push_back(vout); @@ -264,11 +264,11 @@ bool musig_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C { if ( pk == checkpk ) { - if ( secp256k1_schnorrsig_parse(ctx,&musig,&musig64[0]) > 0 && + if ( secp256k1_schnorrsig_parse((const secp256k1_context *)ctx,&musig,(const uint8_t *)&musig64[0]) > 0 && secp256k1_ec_pubkey_parse(ctx,&combined_pk,pk.begin(),33) > 0 ) { musig_prevoutmsg(msg,tx.vin[0].prevout.hash,tx.vout[0].scriptPubKey); - if ( !secp256k1_schnorrsig_verify(ctx,&musig,msg,&combined_pk) ) + if ( !secp256k1_schnorrsig_verify((const secp256k1_context *)ctx,&musig,(const uint8_t *)msg,(const secp256k1_pubkey *)&combined_pk) ) return eval->Invalid("failed schnorrsig_verify"); else return(true); } else return eval->Invalid("couldnt parse pk or musig"); From 6cdecbe7f78ddf29eeab4368f150dbeb7a302e7b Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 09:30:27 -1100 Subject: [PATCH 159/390] Pull in schnorr --- src/komodo_gateway.h | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/komodo_gateway.h b/src/komodo_gateway.h index 02ab67407..35952bebf 100644 --- a/src/komodo_gateway.h +++ b/src/komodo_gateway.h @@ -16,6 +16,17 @@ // paxdeposit equivalent in reverse makes opreturn and KMD does the same in reverse #include "komodo_defs.h" +#include "secp256k1/include/secp256k1.h" +#include "secp256k1/include/secp256k1_schnorrsig.h" +#include "secp256k1/include/secp256k1_musig.h" + +void dummy_linker_tricker() +{ + secp256k1_context *ctx = 0; std::vector musig64; CPubKey pk; secp256k1_schnorrsig musig; secp256k1_pubkey combined_pk; + if ( secp256k1_schnorrsig_parse((const secp256k1_context *)ctx,&musig,(const uint8_t *)&musig64[0]) > 0 && secp256k1_ec_pubkey_parse(ctx,&combined_pk,pk.begin(),33) > 0 ) + return(1); +} + int32_t MarmaraValidateCoinbase(int32_t height,CTransaction tx); int32_t pax_fiatstatus(uint64_t *available,uint64_t *deposited,uint64_t *issued,uint64_t *withdrawn,uint64_t *approved,uint64_t *redeemed,char *base) From bb07e87c4a993b12b0fc43c91b0bf677f15e185b Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 09:31:44 -1100 Subject: [PATCH 160/390] Int32 --- src/komodo_gateway.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo_gateway.h b/src/komodo_gateway.h index 35952bebf..5dd9907c9 100644 --- a/src/komodo_gateway.h +++ b/src/komodo_gateway.h @@ -20,7 +20,7 @@ #include "secp256k1/include/secp256k1_schnorrsig.h" #include "secp256k1/include/secp256k1_musig.h" -void dummy_linker_tricker() +int32_t dummy_linker_tricker() { secp256k1_context *ctx = 0; std::vector musig64; CPubKey pk; secp256k1_schnorrsig musig; secp256k1_pubkey combined_pk; if ( secp256k1_schnorrsig_parse((const secp256k1_context *)ctx,&musig,(const uint8_t *)&musig64[0]) > 0 && secp256k1_ec_pubkey_parse(ctx,&combined_pk,pk.begin(),33) > 0 ) From befefc81c9e22b9f1a191ee3d5012dcf26113254 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 09:34:07 -1100 Subject: [PATCH 161/390] Test --- src/komodo_gateway.h | 4 ++-- src/secp256k1/src/modules/schnorrsig/main_impl.h | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/komodo_gateway.h b/src/komodo_gateway.h index 5dd9907c9..68e648b14 100644 --- a/src/komodo_gateway.h +++ b/src/komodo_gateway.h @@ -16,7 +16,7 @@ // paxdeposit equivalent in reverse makes opreturn and KMD does the same in reverse #include "komodo_defs.h" -#include "secp256k1/include/secp256k1.h" +/*#include "secp256k1/include/secp256k1.h" #include "secp256k1/include/secp256k1_schnorrsig.h" #include "secp256k1/include/secp256k1_musig.h" @@ -25,7 +25,7 @@ int32_t dummy_linker_tricker() secp256k1_context *ctx = 0; std::vector musig64; CPubKey pk; secp256k1_schnorrsig musig; secp256k1_pubkey combined_pk; if ( secp256k1_schnorrsig_parse((const secp256k1_context *)ctx,&musig,(const uint8_t *)&musig64[0]) > 0 && secp256k1_ec_pubkey_parse(ctx,&combined_pk,pk.begin(),33) > 0 ) return(1); -} +}*/ int32_t MarmaraValidateCoinbase(int32_t height,CTransaction tx); diff --git a/src/secp256k1/src/modules/schnorrsig/main_impl.h b/src/secp256k1/src/modules/schnorrsig/main_impl.h index 2eb939f55..925c49d2a 100644 --- a/src/secp256k1/src/modules/schnorrsig/main_impl.h +++ b/src/secp256k1/src/modules/schnorrsig/main_impl.h @@ -25,6 +25,7 @@ int secp256k1_schnorrsig_serialize(const secp256k1_context* ctx, unsigned char * } int secp256k1_schnorrsig_parse(const secp256k1_context* ctx, secp256k1_schnorrsig* sig, const unsigned char *in64) { + parse is here (void) ctx; VERIFY_CHECK(ctx != NULL); ARG_CHECK(sig != NULL); From 0fe4fdd07cbac8b174db05227f398315be1690ef Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 09:43:00 -1100 Subject: [PATCH 162/390] Disable for now --- src/cc/cclib.cpp | 2 +- src/secp256k1/src/modules/schnorrsig/main_impl.h | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 33b76ff91..75dd13fa2 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -582,6 +582,6 @@ cJSON *cclib_reparse(int32_t *nump,cJSON *origparams) // assumes origparams will //#define USE_BASIC_CONFIG //#include "../secp256k1/src/basic-config.h" //#include "../secp256k1/src/secp256k1.c" -#include "musig.cpp" +//#include "musig.cpp" #endif diff --git a/src/secp256k1/src/modules/schnorrsig/main_impl.h b/src/secp256k1/src/modules/schnorrsig/main_impl.h index 925c49d2a..2eb939f55 100644 --- a/src/secp256k1/src/modules/schnorrsig/main_impl.h +++ b/src/secp256k1/src/modules/schnorrsig/main_impl.h @@ -25,7 +25,6 @@ int secp256k1_schnorrsig_serialize(const secp256k1_context* ctx, unsigned char * } int secp256k1_schnorrsig_parse(const secp256k1_context* ctx, secp256k1_schnorrsig* sig, const unsigned char *in64) { - parse is here (void) ctx; VERIFY_CHECK(ctx != NULL); ARG_CHECK(sig != NULL); From 33c9f37abe0da91e990047e3204c0f989cb713af Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 09:45:12 -1100 Subject: [PATCH 163/390] Enable --- src/cc/cclib.cpp | 2 +- src/secp256k1/src/modules/schnorrsig/main_impl.h | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 75dd13fa2..33b76ff91 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -582,6 +582,6 @@ cJSON *cclib_reparse(int32_t *nump,cJSON *origparams) // assumes origparams will //#define USE_BASIC_CONFIG //#include "../secp256k1/src/basic-config.h" //#include "../secp256k1/src/secp256k1.c" -//#include "musig.cpp" +#include "musig.cpp" #endif diff --git a/src/secp256k1/src/modules/schnorrsig/main_impl.h b/src/secp256k1/src/modules/schnorrsig/main_impl.h index 2eb939f55..a99897d2c 100644 --- a/src/secp256k1/src/modules/schnorrsig/main_impl.h +++ b/src/secp256k1/src/modules/schnorrsig/main_impl.h @@ -11,9 +11,9 @@ #include "../../../include/secp256k1_schnorrsig.h" #include "hash.h" -typedef int (secp256k1_ecmult_multi_callback)(secp256k1_scalar *sc, secp256k1_ge *pt, size_t idx, void *data); -static void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx); -static int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n); +//typedef int (secp256k1_ecmult_multi_callback)(secp256k1_scalar *sc, secp256k1_ge *pt, size_t idx, void *data); +//static void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx); +//static int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n); int secp256k1_schnorrsig_serialize(const secp256k1_context* ctx, unsigned char *out64, const secp256k1_schnorrsig* sig) { (void) ctx; From 3c802c4a0219207903151d7ca483665a749d37a3 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 09:53:09 -1100 Subject: [PATCH 164/390] -// --- src/secp256k1/src/modules/schnorrsig/main_impl.h | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/secp256k1/src/modules/schnorrsig/main_impl.h b/src/secp256k1/src/modules/schnorrsig/main_impl.h index a99897d2c..f2b418159 100644 --- a/src/secp256k1/src/modules/schnorrsig/main_impl.h +++ b/src/secp256k1/src/modules/schnorrsig/main_impl.h @@ -11,10 +11,6 @@ #include "../../../include/secp256k1_schnorrsig.h" #include "hash.h" -//typedef int (secp256k1_ecmult_multi_callback)(secp256k1_scalar *sc, secp256k1_ge *pt, size_t idx, void *data); -//static void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx); -//static int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n); - int secp256k1_schnorrsig_serialize(const secp256k1_context* ctx, unsigned char *out64, const secp256k1_schnorrsig* sig) { (void) ctx; VERIFY_CHECK(ctx != NULL); From ea3e9ee36a7fb89f48aecc824ce18050de53848c Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 10:01:21 -1100 Subject: [PATCH 165/390] Parse --- src/komodo_gateway.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/komodo_gateway.h b/src/komodo_gateway.h index 68e648b14..5dd9907c9 100644 --- a/src/komodo_gateway.h +++ b/src/komodo_gateway.h @@ -16,7 +16,7 @@ // paxdeposit equivalent in reverse makes opreturn and KMD does the same in reverse #include "komodo_defs.h" -/*#include "secp256k1/include/secp256k1.h" +#include "secp256k1/include/secp256k1.h" #include "secp256k1/include/secp256k1_schnorrsig.h" #include "secp256k1/include/secp256k1_musig.h" @@ -25,7 +25,7 @@ int32_t dummy_linker_tricker() secp256k1_context *ctx = 0; std::vector musig64; CPubKey pk; secp256k1_schnorrsig musig; secp256k1_pubkey combined_pk; if ( secp256k1_schnorrsig_parse((const secp256k1_context *)ctx,&musig,(const uint8_t *)&musig64[0]) > 0 && secp256k1_ec_pubkey_parse(ctx,&combined_pk,pk.begin(),33) > 0 ) return(1); -}*/ +} int32_t MarmaraValidateCoinbase(int32_t height,CTransaction tx); From 5280af8c12010d7cc7929651fc7d92337d4a2368 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 10:13:16 -1100 Subject: [PATCH 166/390] Revert --- src/komodo_gateway.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/komodo_gateway.h b/src/komodo_gateway.h index 5dd9907c9..68e648b14 100644 --- a/src/komodo_gateway.h +++ b/src/komodo_gateway.h @@ -16,7 +16,7 @@ // paxdeposit equivalent in reverse makes opreturn and KMD does the same in reverse #include "komodo_defs.h" -#include "secp256k1/include/secp256k1.h" +/*#include "secp256k1/include/secp256k1.h" #include "secp256k1/include/secp256k1_schnorrsig.h" #include "secp256k1/include/secp256k1_musig.h" @@ -25,7 +25,7 @@ int32_t dummy_linker_tricker() secp256k1_context *ctx = 0; std::vector musig64; CPubKey pk; secp256k1_schnorrsig musig; secp256k1_pubkey combined_pk; if ( secp256k1_schnorrsig_parse((const secp256k1_context *)ctx,&musig,(const uint8_t *)&musig64[0]) > 0 && secp256k1_ec_pubkey_parse(ctx,&combined_pk,pk.begin(),33) > 0 ) return(1); -} +}*/ int32_t MarmaraValidateCoinbase(int32_t height,CTransaction tx); From 0594b52df25a3b8096ac18e99ed02f283c8d320a Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 20:33:13 -1100 Subject: [PATCH 167/390] Big buffer --- .gitignore | 10 ++++++++++ src/cc/rogue/init.c | 1 + src/cc/rogue/io.c | 12 ++++++++++++ src/cc/rogue/rip.c | 2 +- src/cc/rogue/rogue.c | 2 +- 5 files changed, 25 insertions(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index ebaa71f4d..2f97780ab 100644 --- a/.gitignore +++ b/.gitignore @@ -132,3 +132,13 @@ src/cc/rogue/rogue src/cc/rogue/rogue.so src/cc/rogue/test.zip + +src/rogue.530623577502174316.0 + +src/rogue.530623577502174316.pack + +src/rogue.530623577502174316.player + +src/checkfile + +src/log diff --git a/src/cc/rogue/init.c b/src/cc/rogue/init.c index ffc0b3707..b11cfa80c 100644 --- a/src/cc/rogue/init.c +++ b/src/cc/rogue/init.c @@ -34,6 +34,7 @@ void restore_player(struct rogue_state *rs) int32_t i,total = 0; THING *obj; //rs->P.gold = purse; max_hp = rs->P.hitpoints; + //pstats.s_hpt = max_hp; pstats.s_str = rs->P.strength & 0xffff; if ( (max_stats.s_str= (rs->P.strength >> 16) & 0xffff) == 0 ) max_stats.s_str = 16; diff --git a/src/cc/rogue/io.c b/src/cc/rogue/io.c index 9842ba353..994f112e2 100644 --- a/src/cc/rogue/io.c +++ b/src/cc/rogue/io.c @@ -160,6 +160,18 @@ readchar(struct rogue_state *rs) if ( rs->ind < rs->numkeys ) { c = rs->keystrokes[rs->ind++]; + if ( 0 ) + { + static FILE *fp; static int32_t counter; + if ( fp == 0 ) + fp = fopen("log","wb"); + if ( fp != 0 ) + { + fprintf(fp,"%d: (%c) hp.%d\n",counter,c,pstats.s_hpt); + fflush(fp); + counter++; + } + } while ( c == 'Q' && rs->ind < rs->numkeys ) { //fprintf(stderr,"Got 'Q' next (%c)\n",rs->keystrokes[rs->ind]); sleep(2); diff --git a/src/cc/rogue/rip.c b/src/cc/rogue/rip.c index 65be2e8fa..1866f0b48 100644 --- a/src/cc/rogue/rip.c +++ b/src/cc/rogue/rip.c @@ -238,7 +238,7 @@ death(struct rogue_state *rs,char monst) //struct tm *localtime(const time_t *); if ( rs->guiflag == 0 ) { - fprintf(stderr,"death during replay\n"); + fprintf(stderr,"death during replay by (%c)\n",monst); //sleep(3); rs->replaydone = (uint32_t)time(NULL); return; } diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 92d3ad378..2f4545585 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -607,7 +607,7 @@ playit(struct rogue_state *rs) } else { - if ( rs->needflush != 0 && rs->num > 1024 ) + if ( rs->needflush != 0 && rs->num > 8000 ) { if ( flushkeystrokes(rs) == 0 ) rs->needflush = 0; From 23caa3477367a08556128a329ffd1ba602591fef Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 21:33:25 -1100 Subject: [PATCH 168/390] Allow zombies --- .gitignore | 2 + src/cc/rogue/main.c | 514 +++++++++++++++++++++++++++++++++++++++++++ src/cc/rogue/rogue.c | 71 +----- src/cc/rogue/rogue.h | 4 +- src/cc/rogue/state.c | 2 +- src/cc/rogue_rpc.cpp | 2 +- 6 files changed, 526 insertions(+), 69 deletions(-) diff --git a/.gitignore b/.gitignore index 2f97780ab..0d0846e31 100644 --- a/.gitignore +++ b/.gitignore @@ -142,3 +142,5 @@ src/rogue.530623577502174316.player src/checkfile src/log + +src/foo.zip diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index c0fa36752..1131e3429 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -20,10 +20,17 @@ #include #include #include +#include +#include + +char USERPASS[8192]; +char Gametxidstr[67]; #define SMALLVAL 0.000000000000001 #define SATOSHIDEN ((uint64_t)100000000L) #define dstr(x) ((double)(x) / SATOSHIDEN) +#define KOMODO_ASSETCHAIN_MAXLEN 65 +#define ASSETCHAINS_SYMBOL "ROGUE" #ifndef _BITS256 #define _BITS256 @@ -31,6 +38,15 @@ union _bits256 { uint8_t bytes[32]; uint16_t ushorts[16]; uint32_t uints[8]; uin typedef union _bits256 bits256; #endif +double OS_milliseconds() +{ + struct timeval tv; double millis; + gettimeofday(&tv,NULL); + millis = ((double)tv.tv_sec * 1000. + (double)tv.tv_usec / 1000.); + //printf("tv_sec.%ld usec.%d %f\n",tv.tv_sec,tv.tv_usec,millis); + return(millis); +} + int32_t _unhex(char c) { if ( c >= '0' && c <= '9' ) @@ -167,6 +183,23 @@ char *clonestr(char *str) strcpy(clone,str); return(clone); } + +char *parse_conf_line(char *line,char *field) +{ + line += strlen(field); + for (; *line!='='&&*line!=0; line++) + break; + if ( *line == 0 ) + return(0); + if ( *line == '=' ) + line++; + while ( line[strlen(line)-1] == '\r' || line[strlen(line)-1] == '\n' || line[strlen(line)-1] == ' ' ) + line[strlen(line)-1] = 0; + //printf("LINE.(%s)\n",line); + _stripwhite(line,0); + return(clonestr(line)); +} + int32_t safecopy(char *dest,char *src,long len) { int32_t i = -1; @@ -246,6 +279,487 @@ uint8_t *OS_fileptr(long *allocsizep,char *fname) return((uint8_t *)retptr); } +struct MemoryStruct { char *memory; size_t size; }; +struct return_string { char *ptr; size_t len; }; + +// return data from the server +#define CURL_GLOBAL_ALL (CURL_GLOBAL_SSL|CURL_GLOBAL_WIN32) +#define CURL_GLOBAL_SSL (1<<0) +#define CURL_GLOBAL_WIN32 (1<<1) + + +/************************************************************************ + * + * Initialize the string handler so that it is thread safe + * + ************************************************************************/ + +void init_string(struct return_string *s) +{ + s->len = 0; + s->ptr = (char *)calloc(1,s->len+1); + if ( s->ptr == NULL ) + { + fprintf(stderr,"init_string malloc() failed\n"); + exit(-1); + } + s->ptr[0] = '\0'; +} + +/************************************************************************ + * + * Use the "writer" to accumulate text until done + * + ************************************************************************/ + +size_t accumulatebytes(void *ptr,size_t size,size_t nmemb,struct return_string *s) +{ + size_t new_len = s->len + size*nmemb; + s->ptr = (char *)realloc(s->ptr,new_len+1); + if ( s->ptr == NULL ) + { + fprintf(stderr, "accumulate realloc() failed\n"); + exit(-1); + } + memcpy(s->ptr+s->len,ptr,size*nmemb); + s->ptr[new_len] = '\0'; + s->len = new_len; + return(size * nmemb); +} + +/************************************************************************ + * + * return the current system time in milliseconds + * + ************************************************************************/ + +#define EXTRACT_BITCOIND_RESULT // if defined, ensures error is null and returns the "result" field +#ifdef EXTRACT_BITCOIND_RESULT + +/************************************************************************ + * + * perform post processing of the results + * + ************************************************************************/ + +char *post_process_bitcoind_RPC(char *debugstr,char *command,char *rpcstr,char *params) +{ + long i,j,len; char *retstr = 0; cJSON *json,*result,*error; + //printf("<<<<<<<<<<< bitcoind_RPC: %s post_process_bitcoind_RPC.%s.[%s]\n",debugstr,command,rpcstr); + if ( command == 0 || rpcstr == 0 || rpcstr[0] == 0 ) + { + if ( strcmp(command,"signrawtransaction") != 0 ) + printf("<<<<<<<<<<< bitcoind_RPC: %s post_process_bitcoind_RPC.%s.[%s]\n",debugstr,command,rpcstr); + return(rpcstr); + } + json = cJSON_Parse(rpcstr); + if ( json == 0 ) + { + printf("<<<<<<<<<<< bitcoind_RPC: %s post_process_bitcoind_RPC.%s can't parse.(%s) params.(%s)\n",debugstr,command,rpcstr,params); + free(rpcstr); + return(0); + } + result = cJSON_GetObjectItem(json,"result"); + error = cJSON_GetObjectItem(json,"error"); + if ( error != 0 && result != 0 ) + { + if ( (error->type&0xff) == cJSON_NULL && (result->type&0xff) != cJSON_NULL ) + { + retstr = cJSON_Print(result); + len = strlen(retstr); + if ( retstr[0] == '"' && retstr[len-1] == '"' ) + { + for (i=1,j=0; itype&0xff) != cJSON_NULL || (result->type&0xff) != cJSON_NULL ) + { + if ( strcmp(command,"signrawtransaction") != 0 ) + printf("<<<<<<<<<<< bitcoind_RPC: %s post_process_bitcoind_RPC (%s) error.%s\n",debugstr,command,rpcstr); + } + free(rpcstr); + } else retstr = rpcstr; + free_json(json); + //fprintf(stderr,"<<<<<<<<<<< bitcoind_RPC: postprocess returns.(%s)\n",retstr); + return(retstr); +} +#endif + +/************************************************************************ + * + * perform the query + * + ************************************************************************/ + +char *bitcoind_RPC(char **retstrp,char *debugstr,char *url,char *userpass,char *command,char *params) +{ + static int didinit,count,count2; static double elapsedsum,elapsedsum2; + struct curl_slist *headers = NULL; struct return_string s; CURLcode res; CURL *curl_handle; + char *bracket0,*bracket1,*databuf = 0; long len; int32_t specialcase,numretries; double starttime; + if ( didinit == 0 ) + { + didinit = 1; + curl_global_init(CURL_GLOBAL_ALL); //init the curl session + } + numretries = 0; + if ( debugstr != 0 && strcmp(debugstr,"BTCD") == 0 && command != 0 && strcmp(command,"SuperNET") == 0 ) + specialcase = 1; + else specialcase = 0; + if ( url[0] == 0 ) + strcpy(url,"http://127.0.0.1:7876/nxt"); + if ( specialcase != 0 && 0 ) + printf("<<<<<<<<<<< bitcoind_RPC: debug.(%s) url.(%s) command.(%s) params.(%s)\n",debugstr,url,command,params); +try_again: + if ( retstrp != 0 ) + *retstrp = 0; + starttime = OS_milliseconds(); + curl_handle = curl_easy_init(); + init_string(&s); + headers = curl_slist_append(0,"Expect:"); + + curl_easy_setopt(curl_handle,CURLOPT_USERAGENT,"mozilla/4.0");//"Mozilla/4.0 (compatible; )"); + curl_easy_setopt(curl_handle,CURLOPT_HTTPHEADER, headers); + curl_easy_setopt(curl_handle,CURLOPT_URL, url); + curl_easy_setopt(curl_handle,CURLOPT_WRITEFUNCTION, (void *)accumulatebytes); // send all data to this function + curl_easy_setopt(curl_handle,CURLOPT_WRITEDATA, &s); // we pass our 's' struct to the callback + curl_easy_setopt(curl_handle,CURLOPT_NOSIGNAL, 1L); // supposed to fix "Alarm clock" and long jump crash + curl_easy_setopt(curl_handle,CURLOPT_NOPROGRESS, 1L); // no progress callback + if ( strncmp(url,"https",5) == 0 ) + { + curl_easy_setopt(curl_handle,CURLOPT_SSL_VERIFYPEER,0); + curl_easy_setopt(curl_handle,CURLOPT_SSL_VERIFYHOST,0); + } + if ( userpass != 0 ) + curl_easy_setopt(curl_handle,CURLOPT_USERPWD, userpass); + databuf = 0; + if ( params != 0 ) + { + if ( command != 0 && specialcase == 0 ) + { + len = strlen(params); + if ( len > 0 && params[0] == '[' && params[len-1] == ']' ) { + bracket0 = bracket1 = (char *)""; + } + else + { + bracket0 = (char *)"["; + bracket1 = (char *)"]"; + } + + databuf = (char *)malloc(256 + strlen(command) + strlen(params)); + sprintf(databuf,"{\"id\":\"jl777\",\"method\":\"%s\",\"params\":%s%s%s}",command,bracket0,params,bracket1); + //printf("url.(%s) userpass.(%s) databuf.(%s)\n",url,userpass,databuf); + // + } //else if ( specialcase != 0 ) fprintf(stderr,"databuf.(%s)\n",params); + curl_easy_setopt(curl_handle,CURLOPT_POST,1L); + if ( databuf != 0 ) + curl_easy_setopt(curl_handle,CURLOPT_POSTFIELDS,databuf); + else curl_easy_setopt(curl_handle,CURLOPT_POSTFIELDS,params); + } + //laststart = milliseconds(); + res = curl_easy_perform(curl_handle); + curl_slist_free_all(headers); + curl_easy_cleanup(curl_handle); + if ( databuf != 0 ) // clean up temporary buffer + { + free(databuf); + databuf = 0; + } + if ( res != CURLE_OK ) + { + numretries++; + if ( specialcase != 0 ) + { + printf("<<<<<<<<<<< bitcoind_RPC.(%s): BTCD.%s timeout params.(%s) s.ptr.(%s) err.%d\n",url,command,params,s.ptr,res); + free(s.ptr); + return(0); + } + else if ( numretries >= 1 ) + { + //printf("Maximum number of retries exceeded!\n"); + free(s.ptr); + return(0); + } + if ( (rand() % 1000) == 0 ) + printf( "curl_easy_perform() failed: %s %s.(%s %s), retries: %d\n",curl_easy_strerror(res),debugstr,url,command,numretries); + free(s.ptr); + sleep((1< (%s)\n",params,s.ptr); + count2++; + elapsedsum2 += (OS_milliseconds() - starttime); + if ( (count2 % 10000) == 0) + printf("%d: ave %9.6f | elapsed %.3f millis | NXT calls.(%s) cmd.(%s)\n",count2,elapsedsum2/count2,(double)(OS_milliseconds() - starttime),url,command); + return(s.ptr); + } + } + printf("bitcoind_RPC: impossible case\n"); + free(s.ptr); + return(0); +} + +static size_t WriteMemoryCallback(void *ptr,size_t size,size_t nmemb,void *data) +{ + size_t realsize = (size * nmemb); + struct MemoryStruct *mem = (struct MemoryStruct *)data; + mem->memory = (char *)((ptr != 0) ? realloc(mem->memory,mem->size + realsize + 1) : malloc(mem->size + realsize + 1)); + if ( mem->memory != 0 ) + { + if ( ptr != 0 ) + memcpy(&(mem->memory[mem->size]),ptr,realsize); + mem->size += realsize; + mem->memory[mem->size] = 0; + } + //printf("got %d bytes\n",(int32_t)(size*nmemb)); + return(realsize); +} + +char *curl_post(CURL **cHandlep,char *url,char *userpass,char *postfields,char *hdr0,char *hdr1,char *hdr2,char *hdr3) +{ + struct MemoryStruct chunk; CURL *cHandle; long code; struct curl_slist *headers = 0; + if ( (cHandle= *cHandlep) == NULL ) + *cHandlep = cHandle = curl_easy_init(); + else curl_easy_reset(cHandle); + //#ifdef DEBUG + //curl_easy_setopt(cHandle,CURLOPT_VERBOSE, 1); + //#endif + curl_easy_setopt(cHandle,CURLOPT_USERAGENT,"mozilla/4.0");//"Mozilla/4.0 (compatible; )"); + curl_easy_setopt(cHandle,CURLOPT_SSL_VERIFYPEER,0); + //curl_easy_setopt(cHandle,CURLOPT_SSLVERSION,1); + curl_easy_setopt(cHandle,CURLOPT_URL,url); + curl_easy_setopt(cHandle,CURLOPT_CONNECTTIMEOUT,10); + if ( userpass != 0 && userpass[0] != 0 ) + curl_easy_setopt(cHandle,CURLOPT_USERPWD,userpass); + if ( postfields != 0 && postfields[0] != 0 ) + { + curl_easy_setopt(cHandle,CURLOPT_POST,1); + curl_easy_setopt(cHandle,CURLOPT_POSTFIELDS,postfields); + } + if ( hdr0 != NULL && hdr0[0] != 0 ) + { + //printf("HDR0.(%s) HDR1.(%s) HDR2.(%s) HDR3.(%s)\n",hdr0!=0?hdr0:"",hdr1!=0?hdr1:"",hdr2!=0?hdr2:"",hdr3!=0?hdr3:""); + headers = curl_slist_append(headers,hdr0); + if ( hdr1 != 0 && hdr1[0] != 0 ) + headers = curl_slist_append(headers,hdr1); + if ( hdr2 != 0 && hdr2[0] != 0 ) + headers = curl_slist_append(headers,hdr2); + if ( hdr3 != 0 && hdr3[0] != 0 ) + headers = curl_slist_append(headers,hdr3); + } //headers = curl_slist_append(0,"Expect:"); + if ( headers != 0 ) + curl_easy_setopt(cHandle,CURLOPT_HTTPHEADER,headers); + //res = curl_easy_perform(cHandle); + memset(&chunk,0,sizeof(chunk)); + curl_easy_setopt(cHandle,CURLOPT_WRITEFUNCTION,WriteMemoryCallback); + curl_easy_setopt(cHandle,CURLOPT_WRITEDATA,(void *)&chunk); + curl_easy_perform(cHandle); + curl_easy_getinfo(cHandle,CURLINFO_RESPONSE_CODE,&code); + if ( headers != 0 ) + curl_slist_free_all(headers); + if ( code != 200 ) + printf("(%s) server responded with code %ld (%s)\n",url,code,chunk.memory); + return(chunk.memory); +} + +#ifdef autoextract +uint16_t _komodo_userpass(char *username,char *password,FILE *fp) +{ + char *rpcuser,*rpcpassword,*str,line[8192]; uint16_t port = 0; + rpcuser = rpcpassword = 0; + username[0] = password[0] = 0; + while ( fgets(line,sizeof(line),fp) != 0 ) + { + if ( line[0] == '#' ) + continue; + //printf("line.(%s) %p %p\n",line,strstr(line,(char *)"rpcuser"),strstr(line,(char *)"rpcpassword")); + if ( (str= strstr(line,(char *)"rpcuser")) != 0 ) + rpcuser = parse_conf_line(str,(char *)"rpcuser"); + else if ( (str= strstr(line,(char *)"rpcpassword")) != 0 ) + rpcpassword = parse_conf_line(str,(char *)"rpcpassword"); + else if ( (str= strstr(line,(char *)"rpcport")) != 0 ) + { + port = atoi(parse_conf_line(str,(char *)"rpcport")); + //fprintf(stderr,"rpcport.%u in file\n",port); + } + } + if ( rpcuser != 0 && rpcpassword != 0 ) + { + strcpy(username,rpcuser); + strcpy(password,rpcpassword); + } + //printf("rpcuser.(%s) rpcpassword.(%s) KMDUSERPASS.(%s) %u\n",rpcuser,rpcpassword,KMDUSERPASS,port); + if ( rpcuser != 0 ) + free(rpcuser); + if ( rpcpassword != 0 ) + free(rpcpassword); + return(port); +} + +void komodo_statefname(char *fname,char *symbol,char *str) +{ + int32_t n,len; + sprintf(fname,"%s",getDataDir()); + if ( (n= (int32_t)strlen(ASSETCHAINS_SYMBOL)) != 0 ) + { + len = (int32_t)strlen(fname); + if ( strcmp(ASSETCHAINS_SYMBOL,&fname[len - n]) == 0 ) + fname[len - n] = 0; + else + { + printf("unexpected fname.(%s) vs %s [%s] n.%d len.%d (%s)\n",fname,symbol,ASSETCHAINS_SYMBOL,n,len,&fname[len - n]); + return; + } + } + else + { +#ifdef _WIN32 + strcat(fname,"\\"); +#else + strcat(fname,"/"); +#endif + } + if ( symbol != 0 && symbol[0] != 0 && strcmp("KMD",symbol) != 0 ) + { + strcat(fname,symbol); + //printf("statefname.(%s) -> (%s)\n",symbol,fname); +#ifdef _WIN32 + strcat(fname,"\\"); +#else + strcat(fname,"/"); +#endif + } + strcat(fname,str); + //printf("test.(%s) -> [%s] statename.(%s) %s\n",test,ASSETCHAINS_SYMBOL,symbol,fname); +} + +uint16_t komodo_userpass(char *userpass,char *symbol) +{ + FILE *fp; uint16_t port = 0; char fname[512],username[512],password[512],confname[KOMODO_ASSETCHAIN_MAXLEN]; + userpass[0] = 0; + if ( strcmp("KMD",symbol) == 0 ) + { +#ifdef __APPLE__ + sprintf(confname,"Komodo.conf"); +#else + sprintf(confname,"komodo.conf"); +#endif + } + else sprintf(confname,"%s.conf",symbol); + komodo_statefname(fname,symbol,confname); + if ( (fp= fopen(fname,"rb")) != 0 ) + { + port = _komodo_userpass(username,password,fp); + sprintf(userpass,"%s:%s",username,password); + if ( strcmp(symbol,ASSETCHAINS_SYMBOL) == 0 ) + strcpy(USERPASS,userpass); + fclose(fp); + } + return(port); +} +#endif + +#define is_cJSON_True(json) ((json) != 0 && ((json)->type & 0xff) == cJSON_True) + +char *komodo_issuemethod(char *userpass,char *method,char *params,uint16_t port) +{ + //static void *cHandle; + char url[512],*retstr=0,*retstr2=0,postdata[8192]; + if ( params == 0 || params[0] == 0 ) + params = (char *)"[]"; + if ( strlen(params) < sizeof(postdata)-128 ) + { + sprintf(url,(char *)"http://127.0.0.1:%u",port); + sprintf(postdata,"{\"method\":\"%s\",\"params\":%s}",method,params); + //printf("[%s] (%s) postdata.(%s) params.(%s) USERPASS.(%s)\n",ASSETCHAINS_SYMBOL,url,postdata,params,KMDUSERPASS); + retstr2 = bitcoind_RPC(&retstr,(char *)"debug",url,userpass,method,params); + //retstr = curl_post(&cHandle,url,USERPASS,postdata,0,0,0,0); + } + return(retstr2); +} + +#include "rogue.h" + +void rogue_progress(struct rogue_state *rs,uint64_t seed,char *keystrokes,int32_t num) +{ + char cmd[16384],hexstr[16384]; int32_t i; + if ( rs->guiflag != 0 && Gametxidstr[0] != 0 ) + { + for (i=0; i> keystrokes.log",Gametxidstr,hexstr); + if ( system(cmd) != 0 ) + fprintf(stderr,"error issuing (%s)\n",cmd); + } +} + +int32_t rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) +{ + char cmd[32768]; int32_t i,n,retval=-1; char *filestr,*pname,*statusstr,*datastr,fname[128]; long allocsize; cJSON *retjson,*array,*item; + if ( rs->guiflag == 0 ) + return(-1); + if ( gametxidstr == 0 || *gametxidstr == 0 ) + return(retval); + sprintf(fname,"%s.gameinfo",gametxidstr); + sprintf(cmd,"./komodo-cli -ac_name=ROGUE cclib gameinfo 17 \\\"[%%22%s%%22]\\\" > %s",gametxidstr,fname); + if ( system(cmd) != 0 ) + fprintf(stderr,"error issuing (%s)\n",cmd); + else + { + filestr = (char *)OS_fileptr(&allocsize,fname); + if ( (retjson= cJSON_Parse(filestr)) != 0 ) + { + if ( (array= jarray(&n,retjson,"players")) != 0 ) + { + for (i=0; iP,(int32_t)strlen(datastr)/2,datastr); + fprintf(stderr,"set pname[%s] %s\n",pname==0?"":pname,jprint(item,0)); + rs->restoring = 1; + } + } + } + } + } + free_json(retjson); + } + free(filestr); + } + return(retval); +} + int main(int argc, char **argv, char **envp) { uint64_t seed; FILE *fp = 0; diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 2f4545585..7e5a53fe5 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -26,7 +26,6 @@ */ struct rogue_state globalR; void garbage_collect(); -char Gametxidstr[67]; void purge_obj_guess(struct obj_info *array,int32_t n) { @@ -152,71 +151,11 @@ int32_t flushkeystrokes(struct rogue_state *rs) } #else -uint8_t *OS_fileptr(long *allocsizep,char *fname); -#define is_cJSON_True(json) ((json) != 0 && ((json)->type & 0xff) == cJSON_True) - -int32_t rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) -{ - char cmd[32768]; int32_t i,n,retval=-1; char *filestr,*pname,*statusstr,*datastr,fname[128]; long allocsize; cJSON *retjson,*array,*item; - if ( gametxidstr == 0 || *gametxidstr == 0 ) - return(retval); - sprintf(fname,"%s.gameinfo",gametxidstr); - sprintf(cmd,"./komodo-cli -ac_name=ROGUE cclib gameinfo 17 \\\"[%%22%s%%22]\\\" > %s",gametxidstr,fname); - if ( system(cmd) != 0 ) - fprintf(stderr,"error issuing (%s)\n",cmd); - else - { - filestr = (char *)OS_fileptr(&allocsize,fname); - if ( (retjson= cJSON_Parse(filestr)) != 0 ) - { - if ( (array= jarray(&n,retjson,"players")) != 0 ) - { - for (i=0; iP,(int32_t)strlen(datastr)/2,datastr); - fprintf(stderr,"set pname[%s] %s\n",pname==0?"":pname,jprint(item,0)); - rs->restoring = 1; - } - } - } - } - } - free_json(retjson); - } - free(filestr); - } - return(retval); -} - -void rogue_progress(uint64_t seed,char *keystrokes,int32_t num) -{ - char cmd[16384],hexstr[16384]; int32_t i; - if ( Gametxidstr[0] != 0 ) - { - for (i=0; i> keystrokes.log",Gametxidstr,hexstr); - if ( system(cmd) != 0 ) - fprintf(stderr,"error issuing (%s)\n",cmd); - } -} - int32_t flushkeystrokes(struct rogue_state *rs) { if ( rs->num > 0 ) { - rogue_progress(rs->seed,rs->buffered,rs->num); + rogue_progress(rs,rs->seed,rs->buffered,rs->num); memset(rs->buffered,0,sizeof(rs->buffered)); rs->counter++; rs->num = 0; @@ -230,10 +169,10 @@ void rogue_bailout(struct rogue_state *rs) flushkeystrokes(rs); //sleep(5); return; - fprintf(stderr,"bailing out\n"); + /*fprintf(stderr,"bailing out\n"); sprintf(cmd,"./komodo-cli -ac_name=ROGUE cclib bailout 17 \\\"[%%22%s%%22]\\\" >> bailout.log",Gametxidstr); if ( system(cmd) != 0 ) - fprintf(stderr,"error issuing (%s)\n",cmd); + fprintf(stderr,"error issuing (%s)\n",cmd);*/ } int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t num,struct rogue_player *player,int32_t sleepmillis) @@ -356,6 +295,8 @@ int rogue(int argc, char **argv, char **envp) { char *env; int lowtime; struct rogue_state *rs = &globalR; memset(rs,0,sizeof(*rs)); + rs->guiflag = 1; + rs->sleeptime = 1; // non-zero to allow refresh() if ( argc == 3 && strlen(argv[2]) == 64 ) { rs->seed = atol(argv[1]); @@ -366,8 +307,6 @@ int rogue(int argc, char **argv, char **envp) return(-1); } } else rs->seed = 777; - rs->guiflag = 1; - rs->sleeptime = 1; // non-zero to allow refresh() md_init(); #ifdef MASTER diff --git a/src/cc/rogue/rogue.h b/src/cc/rogue/rogue.h index f687b170c..802dd5f64 100644 --- a/src/cc/rogue/rogue.h +++ b/src/cc/rogue/rogue.h @@ -370,7 +370,7 @@ struct rogue_state uint8_t playerdata[10000]; }; extern struct rogue_state globalR; - +extern char Gametxidstr[67]; int rogue(int argc, char **argv, char **envp); void rogueiterate(struct rogue_state *rs); @@ -380,6 +380,8 @@ int32_t rogue_restorepack(struct rogue_state *rs); void restore_player(struct rogue_state *rs); int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t num,struct rogue_player *player,int32_t sleepmillis); void rogue_bailout(struct rogue_state *rs); +void rogue_progress(struct rogue_state *rs,uint64_t seed,char *keystrokes,int32_t num); +int32_t rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr); #define ROGUE_MAXTOTAL (pstats.s_str*2) diff --git a/src/cc/rogue/state.c b/src/cc/rogue/state.c index 589f77422..7a0e2e4c6 100644 --- a/src/cc/rogue/state.c +++ b/src/cc/rogue/state.c @@ -1432,7 +1432,7 @@ rs_write_object(struct rogue_state *rs,FILE *savef, THING *o) if ( o->_o._o_packch != 0 ) { item = &rs->P.roguepack[rs->P.packsize]; - if ( pstats.s_hpt <= 0 ) + if ( 0 && pstats.s_hpt <= 0 ) { //fprintf(stderr,"KILLED\n"); rs->P.gold = -1; diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 8ca239c7b..2d34d27c8 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1005,7 +1005,7 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param newdata[i] = player[i]; ((uint8_t *)&P)[i] = player[i]; } - if ( P.gold <= 0 || P.hitpoints <= 0 || (P.strength&0xffff) <= 0 || P.level <= 0 || P.experience <= 0 || P.dungeonlevel <= 0 ) + if ( 0 && (P.gold <= 0 || P.hitpoints <= 0 || (P.strength&0xffff) <= 0 || P.level <= 0 || P.experience <= 0 || P.dungeonlevel <= 0) ) { fprintf(stderr,"zero value character was killed -> no playerdata\n"); newdata.resize(0); From a08a6f3be4a9dce2379a8a1b0057e4ed05a8fa21 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 21:35:14 -1100 Subject: [PATCH 169/390] -lcurl --- src/cc/rogue/Makefile.in | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue/Makefile.in b/src/cc/rogue/Makefile.in index c53ece6ac..2669a2025 100644 --- a/src/cc/rogue/Makefile.in +++ b/src/cc/rogue/Makefile.in @@ -28,8 +28,8 @@ CC = @CC@ #CFLAGS=-O2 CFLAGS= @CFLAGS@ -fPIC -#LIBS=-lcurses -LIBS = @LIBS@ +LIBS=-lcurses -lcurl +#LIBS = @LIBS@ #RM=rm -f RM = rm -f From 0514250ce31de0ebe26e23e09c39b2af036baa6e Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 22:07:25 -1100 Subject: [PATCH 170/390] Attempt curl. Will be broken until debugged --- .gitignore | 8 ++ src/cc/rogue/config.h | 270 ------------------------------------------ src/cc/rogue/main.c | 77 ++++++++---- 3 files changed, 65 insertions(+), 290 deletions(-) delete mode 100644 src/cc/rogue/config.h diff --git a/.gitignore b/.gitignore index 0d0846e31..030c9dc5a 100644 --- a/.gitignore +++ b/.gitignore @@ -144,3 +144,11 @@ src/checkfile src/log src/foo.zip + +src/cc/rogue/config.h + +src/cc/rogue/config.h + +src/ROGUE.conf + +src/rogue.scr diff --git a/src/cc/rogue/config.h b/src/cc/rogue/config.h deleted file mode 100644 index 558ae3ba1..000000000 --- a/src/cc/rogue/config.h +++ /dev/null @@ -1,270 +0,0 @@ -/* config.h. Generated from config.h.in by configure. */ -/* config.h.in. Generated from configure.ac by autoheader. */ - -/* Define if scorefile is top scores, not top players */ -#define ALLSCORES 1 - -/* Define if checktime feature should be enabled */ -/* #undef CHECKTIME */ - -/* Define to group owner of setgid executable */ -/* #undef GROUPOWNER */ - -/* Define to 1 if you have the `alarm' function. */ -#define HAVE_ALARM 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_ARPA_INET_H 1 - -/* Define to 1 if libcurses is requested */ -#define HAVE_CURSES_H 1 - -/* Define to 1 if you don't have `vprintf' but do have `_doprnt.' */ -/* #undef HAVE_DOPRNT */ - -/* Define to 1 if you have the `erasechar' function. */ -#define HAVE_ERASECHAR 1 - -/* Define if ncurses has ESCDELAY variable */ -#define HAVE_ESCDELAY 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_FCNTL_H 1 - -/* Define to 1 if you have the `fork' function. */ -#define HAVE_FORK 1 - -/* Define to 1 if you have the `getgid' function. */ -#define HAVE_GETGID 1 - -/* Define to 1 if you have the `getloadavg' function. */ -#define HAVE_GETLOADAVG 1 - -/* Define to 1 if you have the `getpass' function. */ -#define HAVE_GETPASS 1 - -/* Define to 1 if you have the `getpwuid' function. */ -#define HAVE_GETPWUID 1 - -/* Define to 1 if you have the `getuid' function. */ -#define HAVE_GETUID 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_INTTYPES_H 1 - -/* Define to 1 if you have the `killchar' function. */ -#define HAVE_KILLCHAR 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_LIMITS_H 1 - -/* Define to 1 if you have the `loadav' function. */ -/* #undef HAVE_LOADAV */ - -/* Define to 1 if `lstat' has the bug that it succeeds when given the - zero-length file name argument. */ -/* #undef HAVE_LSTAT_EMPTY_STRING_BUG */ - -/* Define to 1 if you have the header file. */ -#define HAVE_MEMORY_H 1 - -/* Define to 1 if you have the `memset' function. */ -#define HAVE_MEMSET 1 - -/* Define to 1 if libncurses is requested */ -/* #undef HAVE_NCURSES_H */ - -/* Define to 1 if you have the header file. */ -/* #undef HAVE_NCURSES_TERM_H */ - -/* Define to 1 if you have the `nlist' function. */ -/* #undef HAVE_NLIST */ - -/* Define to 1 if you have the header file. */ -#define HAVE_NLIST_H 1 - -/* Define to 1 if you have the header file. */ -/* #undef HAVE_PROCESS_H */ - -/* Define to 1 if you have the header file. */ -#define HAVE_PWD_H 1 - -/* Define to 1 if you have the `setenv' function. */ -#define HAVE_SETENV 1 - -/* Define to 1 if you have the `setgid' function. */ -#define HAVE_SETGID 1 - -/* Define to 1 if you have the `setregid' function. */ -#define HAVE_SETREGID 1 - -/* Define to 1 if you have the `setresgid' function. */ -/* #undef HAVE_SETRESGID */ - -/* Define to 1 if you have the `setresuid' function. */ -/* #undef HAVE_SETRESUID */ - -/* Define to 1 if you have the `setreuid' function. */ -#define HAVE_SETREUID 1 - -/* Define to 1 if you have the `setuid' function. */ -#define HAVE_SETUID 1 - -/* Define to 1 if you have the `spawnl' function. */ -/* #undef HAVE_SPAWNL */ - -/* Define to 1 if `stat' has the bug that it succeeds when given the - zero-length file name argument. */ -/* #undef HAVE_STAT_EMPTY_STRING_BUG */ - -/* Define to 1 if stdbool.h conforms to C99. */ -#define HAVE_STDBOOL_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_STDINT_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_STDLIB_H 1 - -/* Define to 1 if you have the `strchr' function. */ -#define HAVE_STRCHR 1 - -/* Define to 1 if you have the `strerror' function. */ -#define HAVE_STRERROR 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_STRINGS_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_STRING_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_SYS_IOCTL_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_SYS_STAT_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_SYS_TYPES_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_SYS_UTSNAME_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_TERMIOS_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_TERM_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_UNISTD_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_UTMP_H 1 - -/* Define to 1 if you have the `vfork' function. */ -#define HAVE_VFORK 1 - -/* Define to 1 if you have the header file. */ -/* #undef HAVE_VFORK_H */ - -/* Define to 1 if you have the `vprintf' function. */ -#define HAVE_VPRINTF 1 - -/* Define to 1 if `fork' works. */ -#define HAVE_WORKING_FORK 1 - -/* Define to 1 if `vfork' works. */ -#define HAVE_WORKING_VFORK 1 - -/* Define to 1 if the system has the type `_Bool'. */ -#define HAVE__BOOL 1 - -/* Define to 1 if you have the `_spawnl' function. */ -/* #undef HAVE__SPAWNL */ - -/* define if we should use program's load average function instead of system - */ -/* #undef LOADAV */ - -/* Define to file to use for scoreboard lockfile */ -#define LOCKFILE "rogue.lck" - -/* Define to 1 if `lstat' dereferences a symlink specified with a trailing - slash. */ -/* #undef LSTAT_FOLLOWS_SLASHED_SYMLINK */ - -/* Define to include wizard mode */ -/* #undef MASTER */ - -/* Define if maxusers feature should be enabled */ -/* #undef MAXLOAD */ - -/* Define if maxusers feature should be enabled */ -/* #undef MAXUSERS */ - -/* kernel file to pass to nlist() when reading load average (unlikely to work) - */ -/* #undef NAMELIST */ - -/* word for the number of scores to store in scoreboard */ -#define NUMNAME "Ten" - -/* number of scores to store in scoreboard */ -#define NUMSCORES 10 - -/* Define to the address where bug reports for this package should be sent. */ -#define PACKAGE_BUGREPORT "yendor@rogueforge.net" - -/* Define to the full name of this package. */ -#define PACKAGE_NAME "Rogue" - -/* Define to the full name and version of this package. */ -#define PACKAGE_STRING "Rogue 5.4.4" - -/* Define to the one symbol short name of this package. */ -#define PACKAGE_TARNAME "rogue" - -/* Define to the version of this package. */ -#define PACKAGE_VERSION "5.4.4" - -/* Define crypt(3) wizard mode password */ -/* #undef PASSWD */ - -/* Define as the return type of signal handlers (`int' or `void'). */ -#define RETSIGTYPE void - -/* Define to file to use for scoreboard */ -#define SCOREFILE "rogue.scr" - -/* Define to 1 if you have the ANSI C header files. */ -#define STDC_HEADERS 1 - -/* Define to 1 if your declares `struct tm'. */ -/* #undef TM_IN_SYS_TIME */ - -/* define if we should use program's user counting function instead of - system's */ -/* #undef UCOUNT */ - -/* utmp like file to pass to ucount() when counting online users (unlikely to - work) */ -/* #undef UTMP */ - -/* Define to empty if `const' does not conform to ANSI C. */ -/* #undef const */ - -/* Define to `int' if doesn't define. */ -/* #undef gid_t */ - -/* Define to `int' if does not define. */ -/* #undef pid_t */ - -/* Define to `unsigned int' if does not define. */ -/* #undef size_t */ - -/* Define to `int' if doesn't define. */ -/* #undef uid_t */ - -/* Define as `fork' if `vfork' does not work. */ -/* #undef vfork */ diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index 1131e3429..01ae794eb 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -23,14 +23,14 @@ #include #include -char USERPASS[8192]; +char USERPASS[8192]; uint16_t ROGUE_PORT; char Gametxidstr[67]; #define SMALLVAL 0.000000000000001 #define SATOSHIDEN ((uint64_t)100000000L) #define dstr(x) ((double)(x) / SATOSHIDEN) #define KOMODO_ASSETCHAIN_MAXLEN 65 -#define ASSETCHAINS_SYMBOL "ROGUE" +char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN]; #ifndef _BITS256 #define _BITS256 @@ -583,7 +583,6 @@ char *curl_post(CURL **cHandlep,char *url,char *userpass,char *postfields,char * return(chunk.memory); } -#ifdef autoextract uint16_t _komodo_userpass(char *username,char *password,FILE *fp) { char *rpcuser,*rpcpassword,*str,line[8192]; uint16_t port = 0; @@ -617,7 +616,7 @@ uint16_t _komodo_userpass(char *username,char *password,FILE *fp) return(port); } -void komodo_statefname(char *fname,char *symbol,char *str) +/*void komodo_statefname(char *fname,char *symbol,char *str) { int32_t n,len; sprintf(fname,"%s",getDataDir()); @@ -652,7 +651,7 @@ void komodo_statefname(char *fname,char *symbol,char *str) } strcat(fname,str); //printf("test.(%s) -> [%s] statename.(%s) %s\n",test,ASSETCHAINS_SYMBOL,symbol,fname); -} +}*/ uint16_t komodo_userpass(char *userpass,char *symbol) { @@ -667,8 +666,8 @@ uint16_t komodo_userpass(char *userpass,char *symbol) #endif } else sprintf(confname,"%s.conf",symbol); - komodo_statefname(fname,symbol,confname); - if ( (fp= fopen(fname,"rb")) != 0 ) + //komodo_statefname(fname,symbol,confname); + if ( (fp= fopen(confname,"rb")) != 0 ) { port = _komodo_userpass(username,password,fp); sprintf(userpass,"%s:%s",username,password); @@ -678,7 +677,6 @@ uint16_t komodo_userpass(char *userpass,char *symbol) } return(port); } -#endif #define is_cJSON_True(json) ((json) != 0 && ((json)->type & 0xff) == cJSON_True) @@ -703,32 +701,53 @@ char *komodo_issuemethod(char *userpass,char *method,char *params,uint16_t port) void rogue_progress(struct rogue_state *rs,uint64_t seed,char *keystrokes,int32_t num) { - char cmd[16384],hexstr[16384]; int32_t i; + char cmd[16384],hexstr[16384],params[32768]; int32_t i; if ( rs->guiflag != 0 && Gametxidstr[0] != 0 ) { for (i=0; i> keystrokes.log",Gametxidstr,hexstr); - if ( system(cmd) != 0 ) - fprintf(stderr,"error issuing (%s)\n",cmd); + if ( 0 ) + { + sprintf(cmd,"./komodo-cli -ac_name=ROGUE cclib keystrokes 17 \\\"[%%22%s%%22,%%22%s%%22]\\\" >> keystrokes.log",Gametxidstr,hexstr); + if ( system(cmd) != 0 ) + fprintf(stderr,"error issuing (%s)\n",cmd); + } + else + { + sprintf(params,"[\"keystrokes\",17,[\"%s\",\"%s\"]]",Gametxidstr,hexstr); + if ( (retstr= komodo_issuemethod(USERPASS,"cclib",params,ROGUE_PORT)) != 0 ) + { + fprintf(stderr,"KEYSTROKES.(%s)\n",retstr); + free(retstr); + } + } } } int32_t rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) { - char cmd[32768]; int32_t i,n,retval=-1; char *filestr,*pname,*statusstr,*datastr,fname[128]; long allocsize; cJSON *retjson,*array,*item; + char cmd[32768]; int32_t i,n,retval=-1; char *filestr=0,*pname,*statusstr,*datastr,fname[128]; long allocsize; cJSON *retjson,*array,*item; if ( rs->guiflag == 0 ) return(-1); if ( gametxidstr == 0 || *gametxidstr == 0 ) return(retval); - sprintf(fname,"%s.gameinfo",gametxidstr); - sprintf(cmd,"./komodo-cli -ac_name=ROGUE cclib gameinfo 17 \\\"[%%22%s%%22]\\\" > %s",gametxidstr,fname); - if ( system(cmd) != 0 ) - fprintf(stderr,"error issuing (%s)\n",cmd); + if ( 0 ) + { + sprintf(fname,"%s.gameinfo",gametxidstr); + sprintf(cmd,"./komodo-cli -ac_name=ROGUE cclib gameinfo 17 \\\"[%%22%s%%22]\\\" > %s",gametxidstr,fname); + if ( system(cmd) != 0 ) + fprintf(stderr,"error issuing (%s)\n",cmd); + else filestr = (char *)OS_fileptr(&allocsize,fname); + } else { - filestr = (char *)OS_fileptr(&allocsize,fname); + sprintf(params,"[\"gameinfo\",17,[\"%s\"]]",gametxidstr); + filestr = komodo_issuemethod(USERPASS,"cclib",params,ROGUE_PORT); + } + if ( filestr != 0 ) + { + fprintf(stderr,"gameinfo.(%s)\n",filestr); if ( (retjson= cJSON_Parse(filestr)) != 0 ) { if ( (array= jarray(&n,retjson,"players")) != 0 ) @@ -762,7 +781,20 @@ int32_t rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) int main(int argc, char **argv, char **envp) { - uint64_t seed; FILE *fp = 0; + uint64_t seed; FILE *fp = 0; int32_t i,j,c; char userpass[8192]; + for (i=j=0; argv[0][i]!=0&&j Date: Wed, 20 Feb 2019 22:09:20 -1100 Subject: [PATCH 171/390] syntax --- .gitignore | 2 ++ src/cc/rogue/main.c | 4 ++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index 030c9dc5a..2ab07ee0f 100644 --- a/.gitignore +++ b/.gitignore @@ -152,3 +152,5 @@ src/cc/rogue/config.h src/ROGUE.conf src/rogue.scr + +src/cc/rogue/confdefs.h diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index 01ae794eb..84e7ae91f 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -701,7 +701,7 @@ char *komodo_issuemethod(char *userpass,char *method,char *params,uint16_t port) void rogue_progress(struct rogue_state *rs,uint64_t seed,char *keystrokes,int32_t num) { - char cmd[16384],hexstr[16384],params[32768]; int32_t i; + char cmd[16384],hexstr[16384],params[32768],*retstr; int32_t i; if ( rs->guiflag != 0 && Gametxidstr[0] != 0 ) { for (i=0; iguiflag == 0 ) return(-1); if ( gametxidstr == 0 || *gametxidstr == 0 ) From 513a9cc3fc5b6a8b9144cc697da31973a44ed59c Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 22:20:36 -1100 Subject: [PATCH 172/390] +prints --- src/cc/cclib.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 33b76ff91..578ce84d8 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -253,7 +253,7 @@ UniValue CClib_info(struct CCcontract_info *cp) UniValue CClib(struct CCcontract_info *cp,char *method,cJSON *params) { UniValue result(UniValue::VOBJ); int32_t i; std::string rawtx; - //printf("CClib params.%p\n",params); + printf("CClib params.%p (%s)\n",params,params!=0?jprint(params,0):""); for (i=0; ievalcode == CClib_methods[i].evalcode && strcmp(method,CClib_methods[i].method) == 0 ) @@ -531,7 +531,7 @@ cJSON *cclib_reparse(int32_t *nump,cJSON *origparams) // assumes origparams will } newstr[j] = 0; params = cJSON_Parse(newstr); - if ( 0 && params != 0 ) + if ( 1 && params != 0 ) printf("new.(%s) -> %s\n",newstr,jprint(params,0)); free(newstr); *nump = cJSON_GetArraySize(params); From b60b2118c54d2031df82f95d046b3e399728f1e9 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 22:28:44 -1100 Subject: [PATCH 173/390] Stubs --- src/cc/rogue/main.c | 2 +- src/cc/rogue/rogue.c | 13 +++++++++++++ src/cc/rogue/rogue.h | 1 - 3 files changed, 14 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index 84e7ae91f..f0e7df58a 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -24,7 +24,7 @@ #include char USERPASS[8192]; uint16_t ROGUE_PORT; -char Gametxidstr[67]; +extern char Gametxidstr[67]; #define SMALLVAL 0.000000000000001 #define SATOSHIDEN ((uint64_t)100000000L) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 7e5a53fe5..b4cb6244f 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -25,6 +25,7 @@ * The main program, of course */ struct rogue_state globalR; +char Gametxidstr[67]; void garbage_collect(); void purge_obj_guess(struct obj_info *array,int32_t n) @@ -151,6 +152,18 @@ int32_t flushkeystrokes(struct rogue_state *rs) } #else +#ifdef BUILD_ROGUE +// stubs for inside daemon +void rogue_progress(struct rogue_state *rs,uint64_t seed,char *keystrokes,int32_t num) +{ +} + +int32_t rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) +{ + return(-1); +} +#endif + int32_t flushkeystrokes(struct rogue_state *rs) { if ( rs->num > 0 ) diff --git a/src/cc/rogue/rogue.h b/src/cc/rogue/rogue.h index 802dd5f64..b64af8f1a 100644 --- a/src/cc/rogue/rogue.h +++ b/src/cc/rogue/rogue.h @@ -370,7 +370,6 @@ struct rogue_state uint8_t playerdata[10000]; }; extern struct rogue_state globalR; -extern char Gametxidstr[67]; int rogue(int argc, char **argv, char **envp); void rogueiterate(struct rogue_state *rs); From 3db424cdf87bd91c3855292bc77f887bb90d3254 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 22:30:21 -1100 Subject: [PATCH 174/390] Test --- src/cc/rogue/rogue.c | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index b4cb6244f..6d0af34b2 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -154,6 +154,7 @@ int32_t flushkeystrokes(struct rogue_state *rs) #ifdef BUILD_ROGUE // stubs for inside daemon +xxx void rogue_progress(struct rogue_state *rs,uint64_t seed,char *keystrokes,int32_t num) { } From 8d39e0119b11d8084bbb724e9dd277dfc34a9a29 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 22:32:17 -1100 Subject: [PATCH 175/390] Fix --- src/cc/rogue/rogue.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 6d0af34b2..0a6d83cff 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -154,7 +154,8 @@ int32_t flushkeystrokes(struct rogue_state *rs) #ifdef BUILD_ROGUE // stubs for inside daemon -xxx +char Gametxidstr[67]; + void rogue_progress(struct rogue_state *rs,uint64_t seed,char *keystrokes,int32_t num) { } From d835211676faa3bcbdd26690ed38f0a6a7e57b21 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 22:32:57 -1100 Subject: [PATCH 176/390] -Gameidstr --- src/cc/rogue/rogue.c | 1 - 1 file changed, 1 deletion(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 0a6d83cff..e8de063de 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -154,7 +154,6 @@ int32_t flushkeystrokes(struct rogue_state *rs) #ifdef BUILD_ROGUE // stubs for inside daemon -char Gametxidstr[67]; void rogue_progress(struct rogue_state *rs,uint64_t seed,char *keystrokes,int32_t num) { From f6d2b31ab65be445a56fe70fdd5ad7e9344512ea Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 22:39:20 -1100 Subject: [PATCH 177/390] tst --- src/cc/rogue/main.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index f0e7df58a..5056ff14d 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -742,7 +742,7 @@ int32_t rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) } else { - sprintf(params,"[\"gameinfo\",17,[\"%s\"]]",gametxidstr); + sprintf(params,"[\"gameinfo\",\"17\",\"[\'%s\']\"]",gametxidstr); filestr = komodo_issuemethod(USERPASS,"cclib",params,ROGUE_PORT); } if ( filestr != 0 ) From c5dce15a91ea65c7629b3e85c9e8666d1b6dc49b Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 22:40:23 -1100 Subject: [PATCH 178/390] %22 --- src/cc/rogue/main.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index 5056ff14d..8ec480a0a 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -742,7 +742,7 @@ int32_t rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) } else { - sprintf(params,"[\"gameinfo\",\"17\",\"[\'%s\']\"]",gametxidstr); + sprintf(params,"[\"gameinfo\",\"17\",\"[%22%s%22]\"]",gametxidstr); filestr = komodo_issuemethod(USERPASS,"cclib",params,ROGUE_PORT); } if ( filestr != 0 ) From acd6f878168806bc48ac761e14215066efbd2665 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 22:41:08 -1100 Subject: [PATCH 179/390] %22 --- src/cc/rogue/main.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index 8ec480a0a..c338cf397 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -715,7 +715,7 @@ void rogue_progress(struct rogue_state *rs,uint64_t seed,char *keystrokes,int32_ } else { - sprintf(params,"[\"keystrokes\",17,[\"%s\",\"%s\"]]",Gametxidstr,hexstr); + sprintf(params,"[\"keystrokes\",\"17\",\"[%22%s%22,%22%s%22]\"]",Gametxidstr,hexstr); if ( (retstr= komodo_issuemethod(USERPASS,"cclib",params,ROGUE_PORT)) != 0 ) { fprintf(stderr,"KEYSTROKES.(%s)\n",retstr); From f394bf75acb1022d8ea37550cd23b1f87f427714 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 22:42:05 -1100 Subject: [PATCH 180/390] %% --- src/cc/rogue/main.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index c338cf397..8f674ba40 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -715,7 +715,7 @@ void rogue_progress(struct rogue_state *rs,uint64_t seed,char *keystrokes,int32_ } else { - sprintf(params,"[\"keystrokes\",\"17\",\"[%22%s%22,%22%s%22]\"]",Gametxidstr,hexstr); + sprintf(params,"[\"keystrokes\",\"17\",\"[%%22%s%%22,%%22%s%%22]\"]",Gametxidstr,hexstr); if ( (retstr= komodo_issuemethod(USERPASS,"cclib",params,ROGUE_PORT)) != 0 ) { fprintf(stderr,"KEYSTROKES.(%s)\n",retstr); @@ -742,7 +742,7 @@ int32_t rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) } else { - sprintf(params,"[\"gameinfo\",\"17\",\"[%22%s%22]\"]",gametxidstr); + sprintf(params,"[\"gameinfo\",\"17\",\"[%%22%s%%22]\"]",gametxidstr); filestr = komodo_issuemethod(USERPASS,"cclib",params,ROGUE_PORT); } if ( filestr != 0 ) From f98831dafdc41acf0ea694296a148dac2a3f1b9a Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 22:43:28 -1100 Subject: [PATCH 181/390] Test --- src/cc/rogue/main.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index 8f674ba40..a7c1d1d3f 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -690,7 +690,7 @@ char *komodo_issuemethod(char *userpass,char *method,char *params,uint16_t port) { sprintf(url,(char *)"http://127.0.0.1:%u",port); sprintf(postdata,"{\"method\":\"%s\",\"params\":%s}",method,params); - //printf("[%s] (%s) postdata.(%s) params.(%s) USERPASS.(%s)\n",ASSETCHAINS_SYMBOL,url,postdata,params,KMDUSERPASS); + printf("[%s] (%s) postdata.(%s) params.(%s) USERPASS.(%s)\n",ASSETCHAINS_SYMBOL,url,postdata,params,KMDUSERPASS); retstr2 = bitcoind_RPC(&retstr,(char *)"debug",url,userpass,method,params); //retstr = curl_post(&cHandle,url,USERPASS,postdata,0,0,0,0); } From 652d9880a7ffce3a756995a05dc0a45439fb8757 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 22:43:56 -1100 Subject: [PATCH 182/390] USERPASS --- src/cc/rogue/main.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index a7c1d1d3f..969314166 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -690,7 +690,7 @@ char *komodo_issuemethod(char *userpass,char *method,char *params,uint16_t port) { sprintf(url,(char *)"http://127.0.0.1:%u",port); sprintf(postdata,"{\"method\":\"%s\",\"params\":%s}",method,params); - printf("[%s] (%s) postdata.(%s) params.(%s) USERPASS.(%s)\n",ASSETCHAINS_SYMBOL,url,postdata,params,KMDUSERPASS); + printf("[%s] (%s) postdata.(%s) params.(%s) USERPASS.(%s)\n",ASSETCHAINS_SYMBOL,url,postdata,params,USERPASS); retstr2 = bitcoind_RPC(&retstr,(char *)"debug",url,userpass,method,params); //retstr = curl_post(&cHandle,url,USERPASS,postdata,0,0,0,0); } From 957178495bbeee8f426621ee1733903a25c2c04f Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 22:46:12 -1100 Subject: [PATCH 183/390] Test --- src/cc/rogue/main.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index 969314166..49a09a5cf 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -450,7 +450,7 @@ try_again: databuf = (char *)malloc(256 + strlen(command) + strlen(params)); sprintf(databuf,"{\"id\":\"jl777\",\"method\":\"%s\",\"params\":%s%s%s}",command,bracket0,params,bracket1); - //printf("url.(%s) userpass.(%s) databuf.(%s)\n",url,userpass,databuf); + printf("url.(%s) userpass.(%s) databuf.(%s)\n",url,userpass,databuf); // } //else if ( specialcase != 0 ) fprintf(stderr,"databuf.(%s)\n",params); curl_easy_setopt(curl_handle,CURLOPT_POST,1L); @@ -690,7 +690,7 @@ char *komodo_issuemethod(char *userpass,char *method,char *params,uint16_t port) { sprintf(url,(char *)"http://127.0.0.1:%u",port); sprintf(postdata,"{\"method\":\"%s\",\"params\":%s}",method,params); - printf("[%s] (%s) postdata.(%s) params.(%s) USERPASS.(%s)\n",ASSETCHAINS_SYMBOL,url,postdata,params,USERPASS); + //printf("[%s] (%s) postdata.(%s) params.(%s) USERPASS.(%s)\n",ASSETCHAINS_SYMBOL,url,postdata,params,USERPASS); retstr2 = bitcoind_RPC(&retstr,(char *)"debug",url,userpass,method,params); //retstr = curl_post(&cHandle,url,USERPASS,postdata,0,0,0,0); } From 3881f9cea47df07f7ad7ce02f06cdd88e0b28e95 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 22:50:57 -1100 Subject: [PATCH 184/390] Prints --- src/wallet/rpcwallet.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 47f7d3004..99d9b87f1 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -5416,6 +5416,7 @@ UniValue cclib(const UniValue& params, bool fHelp) } if ( params.size() == 3 ) { + fprintf(stderr,"params.(%s %s %s)\n",params[0].get_str().c_str(),params[1].get_str().c_str(),params[2].get_str().c_str()); jsonparams = cJSON_Parse(params[2].get_str().c_str()); } } From a65a83bdb8d4619bc45c14883d77d9ffddd81eee Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 22:55:40 -1100 Subject: [PATCH 185/390] Test --- src/cc/rogue/main.c | 6 +++--- src/wallet/rpcwallet.cpp | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index 49a09a5cf..fab4875b1 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -450,7 +450,7 @@ try_again: databuf = (char *)malloc(256 + strlen(command) + strlen(params)); sprintf(databuf,"{\"id\":\"jl777\",\"method\":\"%s\",\"params\":%s%s%s}",command,bracket0,params,bracket1); - printf("url.(%s) userpass.(%s) databuf.(%s)\n",url,userpass,databuf); + //printf("url.(%s) userpass.(%s) databuf.(%s)\n",url,userpass,databuf); // } //else if ( specialcase != 0 ) fprintf(stderr,"databuf.(%s)\n",params); curl_easy_setopt(curl_handle,CURLOPT_POST,1L); @@ -715,7 +715,7 @@ void rogue_progress(struct rogue_state *rs,uint64_t seed,char *keystrokes,int32_ } else { - sprintf(params,"[\"keystrokes\",\"17\",\"[%%22%s%%22,%%22%s%%22]\"]",Gametxidstr,hexstr); + sprintf(params,"[\"keystrokes\",\"17\",\\\"[%%22%s%%22,%%22%s%%22]\\\"]",Gametxidstr,hexstr); if ( (retstr= komodo_issuemethod(USERPASS,"cclib",params,ROGUE_PORT)) != 0 ) { fprintf(stderr,"KEYSTROKES.(%s)\n",retstr); @@ -742,7 +742,7 @@ int32_t rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) } else { - sprintf(params,"[\"gameinfo\",\"17\",\"[%%22%s%%22]\"]",gametxidstr); + sprintf(params,"[\"gameinfo\",\"17\",\\\"[%%22%s%%22]\\\"]",gametxidstr); filestr = komodo_issuemethod(USERPASS,"cclib",params,ROGUE_PORT); } if ( filestr != 0 ) diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 99d9b87f1..decb6fb96 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -5416,7 +5416,7 @@ UniValue cclib(const UniValue& params, bool fHelp) } if ( params.size() == 3 ) { - fprintf(stderr,"params.(%s %s %s)\n",params[0].get_str().c_str(),params[1].get_str().c_str(),params[2].get_str().c_str()); + //fprintf(stderr,"params.(%s %s %s)\n",params[0].get_str().c_str(),params[1].get_str().c_str(),params[2].get_str().c_str()); jsonparams = cJSON_Parse(params[2].get_str().c_str()); } } From c2def52cb232f7faf28829aa4624e1a36d9c4929 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 22:56:53 -1100 Subject: [PATCH 186/390] Test --- src/cc/rogue/main.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index fab4875b1..6ac9efe3b 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -715,7 +715,7 @@ void rogue_progress(struct rogue_state *rs,uint64_t seed,char *keystrokes,int32_ } else { - sprintf(params,"[\"keystrokes\",\"17\",\\\"[%%22%s%%22,%%22%s%%22]\\\"]",Gametxidstr,hexstr); + sprintf(params,"[\"keystrokes\",\"17\",\"[%%22%s%%22,%%22%s%%22]\"]",Gametxidstr,hexstr); if ( (retstr= komodo_issuemethod(USERPASS,"cclib",params,ROGUE_PORT)) != 0 ) { fprintf(stderr,"KEYSTROKES.(%s)\n",retstr); From 2496f79e41c478c780b6142cb1036490361c9949 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 23:05:58 -1100 Subject: [PATCH 187/390] Jsonstr --- src/cc/CCinclude.h | 2 +- src/cc/cclib.cpp | 76 +++++++++++++++++++++------------------- src/wallet/rpcwallet.cpp | 6 ++-- 3 files changed, 43 insertions(+), 41 deletions(-) diff --git a/src/cc/CCinclude.h b/src/cc/CCinclude.h index eb9297a36..ca51506e8 100644 --- a/src/cc/CCinclude.h +++ b/src/cc/CCinclude.h @@ -139,7 +139,7 @@ int32_t komodo_nextheight(); int32_t CCgetspenttxid(uint256 &spenttxid,int32_t &vini,int32_t &height,uint256 txid,int32_t vout); void CCclearvars(struct CCcontract_info *cp); -UniValue CClib(struct CCcontract_info *cp,char *method,cJSON *params); +UniValue CClib(struct CCcontract_info *cp,char *method,char *jsonstr); UniValue CClib_info(struct CCcontract_info *cp); CBlockIndex *komodo_blockindex(uint256 hash); CBlockIndex *komodo_chainactive(int32_t height); diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 578ce84d8..88db00732 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -123,9 +123,43 @@ UniValue musig_send(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); #endif -UniValue CClib_method(struct CCcontract_info *cp,char *method,cJSON *params) +cJSON *cclib_reparse(int32_t *nump,char *jsonstr) // assumes origparams will be freed by caller { - UniValue result(UniValue::VOBJ); uint64_t txfee = 10000; + cJSON *params; char *jsonstr,*newstr; int32_t i,j; + *nump = 0; + if ( jsonstr != 0 ) + { + if ( jsonstr[0] == '"' && jsonstr[strlen(jsonstr)-1] == '"' ) + { + jsonstr[strlen(jsonstr)-1] = 0; + jsonstr++; + } + newstr = (char *)malloc(strlen(jsonstr)+1); + for (i=j=0; jsonstr[i]!=0; i++) + { + if ( jsonstr[i] == '%' && jsonstr[i+1] == '2' && jsonstr[i+2] == '2' ) + { + newstr[j++] = '"'; + i += 2; + } + else if ( jsonstr[i] == '\'' ) + newstr[j++] = '"'; + else newstr[j++] = jsonstr[i]; + } + newstr[j] = 0; + params = cJSON_Parse(newstr); + if ( 1 && params != 0 ) + printf("new.(%s) -> %s\n",newstr,jprint(params,0)); + free(newstr); + *nump = cJSON_GetArraySize(params); + //free(origparams); + } else params = 0; + return(params); +} + +UniValue CClib_method(struct CCcontract_info *cp,char *method,char *jsonstr) +{ + UniValue result(UniValue::VOBJ); uint64_t txfee = 10000; int32_t m; cJSON *params = cclib_reparse(&m,jsonstr); #ifdef BUILD_ROGUE if ( cp->evalcode == EVAL_ROGUE ) { @@ -250,10 +284,10 @@ UniValue CClib_info(struct CCcontract_info *cp) return(result); } -UniValue CClib(struct CCcontract_info *cp,char *method,cJSON *params) +UniValue CClib(struct CCcontract_info *cp,char *method,char *jsonstr) { UniValue result(UniValue::VOBJ); int32_t i; std::string rawtx; - printf("CClib params.%p (%s)\n",params,params!=0?jprint(params,0):""); + printf("CClib params.(%s)\n",jsonstr!=0?jsonstr:""); for (i=0; ievalcode == CClib_methods[i].evalcode && strcmp(method,CClib_methods[i].method) == 0 ) @@ -265,7 +299,7 @@ UniValue CClib(struct CCcontract_info *cp,char *method,cJSON *params) rawtx = CClib_rawtxgen(cp,CClib_methods[i].funcid,params); result.push_back(Pair("rawtx",rawtx)); return(result); - } else return(CClib_method(cp,method,params)); + } else return(CClib_method(cp,method,jsonstr)); } } result.push_back(Pair("result","error")); @@ -507,38 +541,6 @@ uint256 juint256(cJSON *obj) return(revuint256(tmp)); } -cJSON *cclib_reparse(int32_t *nump,cJSON *origparams) // assumes origparams will be freed by caller -{ - cJSON *params; char *jsonstr,*newstr; int32_t i,j; - if ( (jsonstr= jprint(origparams,0)) != 0 ) - { - if ( jsonstr[0] == '"' && jsonstr[strlen(jsonstr)-1] == '"' ) - { - jsonstr[strlen(jsonstr)-1] = 0; - jsonstr++; - } - newstr = (char *)malloc(strlen(jsonstr)+1); - for (i=j=0; jsonstr[i]!=0; i++) - { - if ( jsonstr[i] == '%' && jsonstr[i+1] == '2' && jsonstr[i+2] == '2' ) - { - newstr[j++] = '"'; - i += 2; - } - else if ( jsonstr[i] == '\'' ) - newstr[j++] = '"'; - else newstr[j++] = jsonstr[i]; - } - newstr[j] = 0; - params = cJSON_Parse(newstr); - if ( 1 && params != 0 ) - printf("new.(%s) -> %s\n",newstr,jprint(params,0)); - free(newstr); - *nump = cJSON_GetArraySize(params); - //free(origparams); - } else params = 0; - return(params); -} #ifdef BUILD_ROGUE #include "rogue_rpc.cpp" diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index decb6fb96..3965416c4 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -5396,7 +5396,7 @@ UniValue cclibinfo(const UniValue& params, bool fHelp) UniValue cclib(const UniValue& params, bool fHelp) { - struct CCcontract_info *cp,C; char *method; cJSON *jsonparams=0; uint8_t evalcode = EVAL_FIRSTUSER; + struct CCcontract_info *cp,C; char *method,*jsonstr=0; uint8_t evalcode = EVAL_FIRSTUSER; if ( fHelp || params.size() > 3 ) throw runtime_error("cclib method [evalcode] [JSON params]\n"); if ( ASSETCHAINS_CCLIB.size() == 0 ) @@ -5417,11 +5417,11 @@ UniValue cclib(const UniValue& params, bool fHelp) if ( params.size() == 3 ) { //fprintf(stderr,"params.(%s %s %s)\n",params[0].get_str().c_str(),params[1].get_str().c_str(),params[2].get_str().c_str()); - jsonparams = cJSON_Parse(params[2].get_str().c_str()); + jsonparams = params[2].get_str().c_str(); } } cp = CCinit(&C,evalcode); - return(CClib(cp,method,jsonparams)); + return(CClib(cp,method,jsonstr)); } UniValue oraclesaddress(const UniValue& params, bool fHelp) From d9a52ff53cd8099f5dac9a768a68df26eb1f83c7 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 23:08:13 -1100 Subject: [PATCH 188/390] if ( params != 0 && (n= cJSON_GetArraySize()) > 0 ) --- src/cc/musig.cpp | 6 +++--- src/cc/rogue_rpc.cpp | 16 ++++++++-------- src/cc/sudoku.cpp | 2 +- 3 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 800102e13..04f3fe35d 100755 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -86,7 +86,7 @@ int32_t musig_prevoutmsg(uint8_t *msg,uint256 sendtxid,CScript scriptPubKey) UniValue musig_calcmsg(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { UniValue result(UniValue::VOBJ); uint256 sendtxid; int32_t i; uint8_t msg[32]; char *scriptstr,str[65]; int32_t n; - if ( (params= cclib_reparse(&n,params)) != 0 ) + if ( params != 0 && (n= cJSON_GetArraySize()) > 0 ) { if ( n == 2 ) { @@ -183,7 +183,7 @@ UniValue musig_send(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) txfee = MUSIG_TXFEE; mypk = pubkey2pk(Mypubkey()); musigpk = GetUnspendable(cp,0); - if ( (params= cclib_reparse(&n,params)) != 0 ) + if ( params != 0 && (n= cJSON_GetArraySize()) > 0 ) { if ( n == 2 && (hexstr= jstr(jitem(params,0),0)) != 0 && is_hexstr(hexstr,0) == 66 ) { @@ -206,7 +206,7 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue result(UniValue::VOBJ); std::string rawtx; CPubKey mypk,pk; secp256k1_pubkey combined_pk; char *scriptstr,*musigstr; uint8_t msg[32]; CTransaction vintx; uint256 prevhash,hashBlock; int32_t n,numvouts; CTxOut vout; secp256k1_schnorrsig musig; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); - if ( (params= cclib_reparse(&n,params)) != 0 ) + if ( params != 0 && (n= cJSON_GetArraySize()) > 0 ) { if ( n == 3 ) { diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 2d34d27c8..60d9a5cfd 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -657,7 +657,7 @@ UniValue rogue_newgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue result(UniValue::VOBJ); std::string rawtx; CPubKey roguepk,mypk; char *jsonstr; uint64_t inputsum,change,required,buyin=0; int32_t i,n,maxplayers = 1; if ( txfee == 0 ) txfee = 10000; - if ( (params= cclib_reparse(&n,params)) != 0 ) + if ( params != 0 && (n= cJSON_GetArraySize()) > 0 ) { if ( n > 0 ) { @@ -693,7 +693,7 @@ UniValue rogue_playerinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *param UniValue result(UniValue::VOBJ); std::vector playerdata; uint256 playertxid,tokenid,origplayergame;int32_t n; CPubKey pk; bits256 t; std::string symbol,pname; result.push_back(Pair("result","success")); rogue_univalue(result,"playerinfo",-1,-1); - if ( (params= cclib_reparse(&n,params)) != 0 ) + if ( params != 0 && (n= cJSON_GetArraySize()) > 0 ) { if ( n > 0 ) { @@ -723,7 +723,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) roguepk = GetUnspendable(cp,0); rogue_univalue(result,"register",-1,-1); playertxid = tokenid = zeroid; - if ( (params= cclib_reparse(&n,params)) != 0 ) + if ( params != 0 && (n= cJSON_GetArraySize()) > 0 ) { if ( n > 0 ) { @@ -803,7 +803,7 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param if ( txfee == 0 ) txfee = 10000; rogue_univalue(result,"keystrokes",-1,-1); - if ( (params= cclib_reparse(&n,params)) != 0 && n == 2 && (keystrokestr= jstr(jitem(params,1),0)) != 0 ) + if ( params != 0 && (n= cJSON_GetArraySize()) == 2 && (keystrokestr= jstr(jitem(params,1),0)) != 0 ) { gametxid = juint256(jitem(params,0)); result.push_back(Pair("gametxid",gametxid.GetHex())); @@ -896,7 +896,7 @@ UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) roguepk = GetUnspendable(cp,0); result.push_back(Pair("name","rogue")); result.push_back(Pair("method","extract")); - if ( (params= cclib_reparse(&n,params)) != 0 ) + if ( params != 0 && (n= cJSON_GetArraySize()) > 0 ) { if ( n > 0 ) { @@ -968,7 +968,7 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param funcid = 'H'; mult = 200000; } - if ( (params= cclib_reparse(&n,params)) != 0 ) + if ( params != 0 && (n= cJSON_GetArraySize()) > 0 ) { if ( n > 0 ) { @@ -1081,7 +1081,7 @@ UniValue rogue_gameinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue result(UniValue::VOBJ),a(UniValue::VARR); int32_t i,n,gameheight,maxplayers,numvouts; uint256 txid; CTransaction tx; int64_t buyin; uint64_t seed; bits256 t; char myrogueaddr[64]; CPubKey mypk,roguepk; result.push_back(Pair("name","rogue")); result.push_back(Pair("method","gameinfo")); - if ( (params= cclib_reparse(&n,params)) != 0 ) + if ( params != 0 && (n= cJSON_GetArraySize()) > 0 ) { if ( n > 0 ) { @@ -1212,7 +1212,7 @@ UniValue rogue_setname(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { UniValue result(UniValue::VOBJ); int32_t n; char *namestr = 0; rogue_univalue(result,"setname",-1,-1); - if ( (params= cclib_reparse(&n,params)) != 0 ) + if ( params != 0 && (n= cJSON_GetArraySize()) > 0 ) { if ( n > 0 ) { diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index d48a1bc2c..a8e7c651b 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -2817,7 +2817,7 @@ UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params good = 0; if ( params != 0 ) { - if ( (params= cclib_reparse(&n,params)) != 0 ) + if ( params != 0 && (n= cJSON_GetArraySize()) > 0 ) { if ( n > 2 && n <= (sizeof(timestamps)/sizeof(*timestamps))+2 ) { From 2dff5b98f025b4dda5b391d93e447956211c4934 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 23:10:26 -1100 Subject: [PATCH 189/390] Jsonstr --- src/wallet/rpcwallet.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 3965416c4..36172a612 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -5417,7 +5417,7 @@ UniValue cclib(const UniValue& params, bool fHelp) if ( params.size() == 3 ) { //fprintf(stderr,"params.(%s %s %s)\n",params[0].get_str().c_str(),params[1].get_str().c_str(),params[2].get_str().c_str()); - jsonparams = params[2].get_str().c_str(); + jsonstr = params[2].get_str().c_str(); } } cp = CCinit(&C,evalcode); From 695278546955eeab749f3f3b2b5a8f7a0f8eff5a Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 23:12:58 -1100 Subject: [PATCH 190/390] params --- src/cc/musig.cpp | 6 +++--- src/cc/rogue_rpc.cpp | 16 ++++++++-------- src/cc/sudoku.cpp | 2 +- 3 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 04f3fe35d..5d56635aa 100755 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -86,7 +86,7 @@ int32_t musig_prevoutmsg(uint8_t *msg,uint256 sendtxid,CScript scriptPubKey) UniValue musig_calcmsg(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { UniValue result(UniValue::VOBJ); uint256 sendtxid; int32_t i; uint8_t msg[32]; char *scriptstr,str[65]; int32_t n; - if ( params != 0 && (n= cJSON_GetArraySize()) > 0 ) + if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) { if ( n == 2 ) { @@ -183,7 +183,7 @@ UniValue musig_send(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) txfee = MUSIG_TXFEE; mypk = pubkey2pk(Mypubkey()); musigpk = GetUnspendable(cp,0); - if ( params != 0 && (n= cJSON_GetArraySize()) > 0 ) + if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) { if ( n == 2 && (hexstr= jstr(jitem(params,0),0)) != 0 && is_hexstr(hexstr,0) == 66 ) { @@ -206,7 +206,7 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue result(UniValue::VOBJ); std::string rawtx; CPubKey mypk,pk; secp256k1_pubkey combined_pk; char *scriptstr,*musigstr; uint8_t msg[32]; CTransaction vintx; uint256 prevhash,hashBlock; int32_t n,numvouts; CTxOut vout; secp256k1_schnorrsig musig; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); - if ( params != 0 && (n= cJSON_GetArraySize()) > 0 ) + if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) { if ( n == 3 ) { diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 60d9a5cfd..57ce1e14b 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -657,7 +657,7 @@ UniValue rogue_newgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue result(UniValue::VOBJ); std::string rawtx; CPubKey roguepk,mypk; char *jsonstr; uint64_t inputsum,change,required,buyin=0; int32_t i,n,maxplayers = 1; if ( txfee == 0 ) txfee = 10000; - if ( params != 0 && (n= cJSON_GetArraySize()) > 0 ) + if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) { if ( n > 0 ) { @@ -693,7 +693,7 @@ UniValue rogue_playerinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *param UniValue result(UniValue::VOBJ); std::vector playerdata; uint256 playertxid,tokenid,origplayergame;int32_t n; CPubKey pk; bits256 t; std::string symbol,pname; result.push_back(Pair("result","success")); rogue_univalue(result,"playerinfo",-1,-1); - if ( params != 0 && (n= cJSON_GetArraySize()) > 0 ) + if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) { if ( n > 0 ) { @@ -723,7 +723,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) roguepk = GetUnspendable(cp,0); rogue_univalue(result,"register",-1,-1); playertxid = tokenid = zeroid; - if ( params != 0 && (n= cJSON_GetArraySize()) > 0 ) + if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) { if ( n > 0 ) { @@ -803,7 +803,7 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param if ( txfee == 0 ) txfee = 10000; rogue_univalue(result,"keystrokes",-1,-1); - if ( params != 0 && (n= cJSON_GetArraySize()) == 2 && (keystrokestr= jstr(jitem(params,1),0)) != 0 ) + if ( params != 0 && (n= cJSON_GetArraySize(params)) == 2 && (keystrokestr= jstr(jitem(params,1),0)) != 0 ) { gametxid = juint256(jitem(params,0)); result.push_back(Pair("gametxid",gametxid.GetHex())); @@ -896,7 +896,7 @@ UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) roguepk = GetUnspendable(cp,0); result.push_back(Pair("name","rogue")); result.push_back(Pair("method","extract")); - if ( params != 0 && (n= cJSON_GetArraySize()) > 0 ) + if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) { if ( n > 0 ) { @@ -968,7 +968,7 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param funcid = 'H'; mult = 200000; } - if ( params != 0 && (n= cJSON_GetArraySize()) > 0 ) + if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) { if ( n > 0 ) { @@ -1081,7 +1081,7 @@ UniValue rogue_gameinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue result(UniValue::VOBJ),a(UniValue::VARR); int32_t i,n,gameheight,maxplayers,numvouts; uint256 txid; CTransaction tx; int64_t buyin; uint64_t seed; bits256 t; char myrogueaddr[64]; CPubKey mypk,roguepk; result.push_back(Pair("name","rogue")); result.push_back(Pair("method","gameinfo")); - if ( params != 0 && (n= cJSON_GetArraySize()) > 0 ) + if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) { if ( n > 0 ) { @@ -1212,7 +1212,7 @@ UniValue rogue_setname(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { UniValue result(UniValue::VOBJ); int32_t n; char *namestr = 0; rogue_univalue(result,"setname",-1,-1); - if ( params != 0 && (n= cJSON_GetArraySize()) > 0 ) + if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) { if ( n > 0 ) { diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index a8e7c651b..49bcf79d9 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -2817,7 +2817,7 @@ UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params good = 0; if ( params != 0 ) { - if ( params != 0 && (n= cJSON_GetArraySize()) > 0 ) + if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) { if ( n > 2 && n <= (sizeof(timestamps)/sizeof(*timestamps))+2 ) { From 0dd112c6d85de51692730161a31ff06646e29ea5 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 23:16:37 -1100 Subject: [PATCH 191/390] Syntax --- src/cc/cclib.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 88db00732..f17f04273 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -125,7 +125,7 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); cJSON *cclib_reparse(int32_t *nump,char *jsonstr) // assumes origparams will be freed by caller { - cJSON *params; char *jsonstr,*newstr; int32_t i,j; + cJSON *params; char *newstr; int32_t i,j; *nump = 0; if ( jsonstr != 0 ) { @@ -286,7 +286,7 @@ UniValue CClib_info(struct CCcontract_info *cp) UniValue CClib(struct CCcontract_info *cp,char *method,char *jsonstr) { - UniValue result(UniValue::VOBJ); int32_t i; std::string rawtx; + UniValue result(UniValue::VOBJ); int32_t i; std::string rawtx; cJSON *params; printf("CClib params.(%s)\n",jsonstr!=0?jsonstr:""); for (i=0; i Date: Wed, 20 Feb 2019 23:17:40 -1100 Subject: [PATCH 192/390] Char * --- src/wallet/rpcwallet.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 36172a612..ab8992c0d 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -5417,7 +5417,7 @@ UniValue cclib(const UniValue& params, bool fHelp) if ( params.size() == 3 ) { //fprintf(stderr,"params.(%s %s %s)\n",params[0].get_str().c_str(),params[1].get_str().c_str(),params[2].get_str().c_str()); - jsonstr = params[2].get_str().c_str(); + jsonstr = (char *)params[2].get_str().c_str(); } } cp = CCinit(&C,evalcode); From d58bfc8a7fbda8a03f009f2242dd5df7e3c9a106 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 23:20:37 -1100 Subject: [PATCH 193/390] Prints --- src/cc/cclib.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index f17f04273..3f4a5d6a8 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -160,6 +160,7 @@ cJSON *cclib_reparse(int32_t *nump,char *jsonstr) // assumes origparams will be UniValue CClib_method(struct CCcontract_info *cp,char *method,char *jsonstr) { UniValue result(UniValue::VOBJ); uint64_t txfee = 10000; int32_t m; cJSON *params = cclib_reparse(&m,jsonstr); + fprintf(stderr,"method.(%s) -> (%s)\n",jsonstr!=0?jsonstr:"",params!=0?jprint(params,0):""); #ifdef BUILD_ROGUE if ( cp->evalcode == EVAL_ROGUE ) { From e392999374bfb4cded273a333aeac44c52739a99 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 23:24:27 -1100 Subject: [PATCH 194/390] Jsonstr --- src/wallet/rpcwallet.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index ab8992c0d..de4b22b7e 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -5416,8 +5416,8 @@ UniValue cclib(const UniValue& params, bool fHelp) } if ( params.size() == 3 ) { - //fprintf(stderr,"params.(%s %s %s)\n",params[0].get_str().c_str(),params[1].get_str().c_str(),params[2].get_str().c_str()); jsonstr = (char *)params[2].get_str().c_str(); + fprintf(stderr,"params.(%s %s %s)\n",params[0].get_str().c_str(),params[1].get_str().c_str(),jsonstr); } } cp = CCinit(&C,evalcode); From 0cc4ef9d9008f73e3f0ff855a80bb048372de4d8 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 23:26:36 -1100 Subject: [PATCH 195/390] Test --- src/cc/rogue/main.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index 6ac9efe3b..49a09a5cf 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -450,7 +450,7 @@ try_again: databuf = (char *)malloc(256 + strlen(command) + strlen(params)); sprintf(databuf,"{\"id\":\"jl777\",\"method\":\"%s\",\"params\":%s%s%s}",command,bracket0,params,bracket1); - //printf("url.(%s) userpass.(%s) databuf.(%s)\n",url,userpass,databuf); + printf("url.(%s) userpass.(%s) databuf.(%s)\n",url,userpass,databuf); // } //else if ( specialcase != 0 ) fprintf(stderr,"databuf.(%s)\n",params); curl_easy_setopt(curl_handle,CURLOPT_POST,1L); @@ -742,7 +742,7 @@ int32_t rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) } else { - sprintf(params,"[\"gameinfo\",\"17\",\\\"[%%22%s%%22]\\\"]",gametxidstr); + sprintf(params,"[\"gameinfo\",\"17\",\"[%%22%s%%22]\"]",gametxidstr); filestr = komodo_issuemethod(USERPASS,"cclib",params,ROGUE_PORT); } if ( filestr != 0 ) From 13ba8a70ca9a86f8964d1c0b478b984b4921cadd Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 23:28:57 -1100 Subject: [PATCH 196/390] -prints --- src/cc/cclib.cpp | 4 ++-- src/cc/rogue/main.c | 2 +- src/wallet/rpcwallet.cpp | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 3f4a5d6a8..a595f5559 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -160,7 +160,7 @@ cJSON *cclib_reparse(int32_t *nump,char *jsonstr) // assumes origparams will be UniValue CClib_method(struct CCcontract_info *cp,char *method,char *jsonstr) { UniValue result(UniValue::VOBJ); uint64_t txfee = 10000; int32_t m; cJSON *params = cclib_reparse(&m,jsonstr); - fprintf(stderr,"method.(%s) -> (%s)\n",jsonstr!=0?jsonstr:"",params!=0?jprint(params,0):""); + //fprintf(stderr,"method.(%s) -> (%s)\n",jsonstr!=0?jsonstr:"",params!=0?jprint(params,0):""); #ifdef BUILD_ROGUE if ( cp->evalcode == EVAL_ROGUE ) { @@ -288,7 +288,7 @@ UniValue CClib_info(struct CCcontract_info *cp) UniValue CClib(struct CCcontract_info *cp,char *method,char *jsonstr) { UniValue result(UniValue::VOBJ); int32_t i; std::string rawtx; cJSON *params; - printf("CClib params.(%s)\n",jsonstr!=0?jsonstr:""); + //printf("CClib params.(%s)\n",jsonstr!=0?jsonstr:""); for (i=0; ievalcode == CClib_methods[i].evalcode && strcmp(method,CClib_methods[i].method) == 0 ) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index 49a09a5cf..af357feb8 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -450,7 +450,7 @@ try_again: databuf = (char *)malloc(256 + strlen(command) + strlen(params)); sprintf(databuf,"{\"id\":\"jl777\",\"method\":\"%s\",\"params\":%s%s%s}",command,bracket0,params,bracket1); - printf("url.(%s) userpass.(%s) databuf.(%s)\n",url,userpass,databuf); + //printf("url.(%s) userpass.(%s) databuf.(%s)\n",url,userpass,databuf); // } //else if ( specialcase != 0 ) fprintf(stderr,"databuf.(%s)\n",params); curl_easy_setopt(curl_handle,CURLOPT_POST,1L); diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index de4b22b7e..0ed2f866c 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -5417,7 +5417,7 @@ UniValue cclib(const UniValue& params, bool fHelp) if ( params.size() == 3 ) { jsonstr = (char *)params[2].get_str().c_str(); - fprintf(stderr,"params.(%s %s %s)\n",params[0].get_str().c_str(),params[1].get_str().c_str(),jsonstr); + //fprintf(stderr,"params.(%s %s %s)\n",params[0].get_str().c_str(),params[1].get_str().c_str(),jsonstr); } } cp = CCinit(&C,evalcode); From 89e375e95dbccb5877f55a94c298134e6f5f8fe6 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 23:32:23 -1100 Subject: [PATCH 197/390] Resultjson --- src/cc/cclib.cpp | 2 +- src/cc/rogue/main.c | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index a595f5559..625872483 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -148,7 +148,7 @@ cJSON *cclib_reparse(int32_t *nump,char *jsonstr) // assumes origparams will be } newstr[j] = 0; params = cJSON_Parse(newstr); - if ( 1 && params != 0 ) + if ( 0 && params != 0 ) printf("new.(%s) -> %s\n",newstr,jprint(params,0)); free(newstr); *nump = cJSON_GetArraySize(params); diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index af357feb8..32967614c 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -727,7 +727,7 @@ void rogue_progress(struct rogue_state *rs,uint64_t seed,char *keystrokes,int32_ int32_t rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) { - char cmd[32768]; int32_t i,n,retval=-1; char params[1024],*filestr=0,*pname,*statusstr,*datastr,fname[128]; long allocsize; cJSON *retjson,*array,*item; + char cmd[32768]; int32_t i,n,retval=-1; char params[1024],*filestr=0,*pname,*statusstr,*datastr,fname[128]; long allocsize; cJSON *retjson,*array,*item,*resultjson; if ( rs->guiflag == 0 ) return(-1); if ( gametxidstr == 0 || *gametxidstr == 0 ) @@ -747,10 +747,10 @@ int32_t rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) } if ( filestr != 0 ) { - fprintf(stderr,"gameinfo.(%s)\n",filestr); - if ( (retjson= cJSON_Parse(filestr)) != 0 ) + if ( (retjson= cJSON_Parse(filestr)) != 0 && (resultjson= jitem(retjson,"result")) != 0 ) { - if ( (array= jarray(&n,retjson,"players")) != 0 ) + fprintf(stderr,"gameinfo.(%s)\n",jprint(resultjson,0)); + if ( (array= jarray(&n,resultjson,"players")) != 0 ) { for (i=0; i Date: Wed, 20 Feb 2019 23:32:59 -1100 Subject: [PATCH 198/390] jobj --- src/cc/rogue/main.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index 32967614c..7971a9b3d 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -747,7 +747,7 @@ int32_t rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) } if ( filestr != 0 ) { - if ( (retjson= cJSON_Parse(filestr)) != 0 && (resultjson= jitem(retjson,"result")) != 0 ) + if ( (retjson= cJSON_Parse(filestr)) != 0 && (resultjson= jobj(retjson,"result")) != 0 ) { fprintf(stderr,"gameinfo.(%s)\n",jprint(resultjson,0)); if ( (array= jarray(&n,resultjson,"players")) != 0 ) From 2fdc745c0b75bf03ede1bb02be566eaff6b5b026 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 23:35:42 -1100 Subject: [PATCH 199/390] -print --- src/cc/rogue/main.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index 7971a9b3d..ca05226d3 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -718,7 +718,7 @@ void rogue_progress(struct rogue_state *rs,uint64_t seed,char *keystrokes,int32_ sprintf(params,"[\"keystrokes\",\"17\",\"[%%22%s%%22,%%22%s%%22]\"]",Gametxidstr,hexstr); if ( (retstr= komodo_issuemethod(USERPASS,"cclib",params,ROGUE_PORT)) != 0 ) { - fprintf(stderr,"KEYSTROKES.(%s)\n",retstr); + //fprintf(stderr,"KEYSTROKES.(%s)\n",retstr); free(retstr); } } @@ -749,7 +749,7 @@ int32_t rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) { if ( (retjson= cJSON_Parse(filestr)) != 0 && (resultjson= jobj(retjson,"result")) != 0 ) { - fprintf(stderr,"gameinfo.(%s)\n",jprint(resultjson,0)); + //fprintf(stderr,"gameinfo.(%s)\n",jprint(resultjson,0)); if ( (array= jarray(&n,resultjson,"players")) != 0 ) { for (i=0; i Date: Thu, 21 Feb 2019 00:19:53 -1100 Subject: [PATCH 200/390] ../secp256k1/src/ --- src/cc/cclib.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 625872483..df60833d2 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -584,9 +584,12 @@ uint256 juint256(cJSON *obj) #else #include "sudoku.cpp" -//#define USE_BASIC_CONFIG -//#include "../secp256k1/src/basic-config.h" +#define USE_BASIC_CONFIG +#include "../secp256k1/src/basic-config.h" //#include "../secp256k1/src/secp256k1.c" +#include "../secp256k1/src/modules/schnorrsig/main_impl.h" +#include "../secp256k1/src/modules/musig/main_impl.h" + #include "musig.cpp" #endif From 9d8ec78d880dce011f65bc67d680656a9d0a9322 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 00:21:49 -1100 Subject: [PATCH 201/390] ../secp256k1/src/ --- src/cc/cclib.cpp | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index df60833d2..2ccfcce46 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -586,6 +586,21 @@ uint256 juint256(cJSON *obj) #include "sudoku.cpp" #define USE_BASIC_CONFIG #include "../secp256k1/src/basic-config.h" +#include "../secp256k1/include/secp256k1.h" + +#include "../secp256k1/src/util.h" +#include "../secp256k1/src/num_impl.h" +#include "../secp256k1/src/field_impl.h" +#include "../secp256k1/src/scalar_impl.h" +#include "../secp256k1/src/group_impl.h" +#include "../secp256k1/src/ecmult_impl.h" +#include "../secp256k1/src/ecmult_const_impl.h" +#include "../secp256k1/src/ecmult_gen_impl.h" +#include "../secp256k1/src/ecdsa_impl.h" +#include "../secp256k1/src/eckey_impl.h" +#include "../secp256k1/src/hash_impl.h" +#include "../secp256k1/src/scratch_impl.h" + //#include "../secp256k1/src/secp256k1.c" #include "../secp256k1/src/modules/schnorrsig/main_impl.h" #include "../secp256k1/src/modules/musig/main_impl.h" From df9f4a10928e80e91fc83c01dc5c49767490398e Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 00:22:54 -1100 Subject: [PATCH 202/390] ARG_CHECK --- src/cc/cclib.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 2ccfcce46..b6a79b32e 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -601,6 +601,13 @@ uint256 juint256(cJSON *obj) #include "../secp256k1/src/hash_impl.h" #include "../secp256k1/src/scratch_impl.h" +#define ARG_CHECK(cond) do { \ +if (EXPECT(!(cond), 0)) { \ +secp256k1_callback_call(&ctx->illegal_callback, #cond); \ +return 0; \ +} \ +} while(0) + //#include "../secp256k1/src/secp256k1.c" #include "../secp256k1/src/modules/schnorrsig/main_impl.h" #include "../secp256k1/src/modules/musig/main_impl.h" From b9c1f3bc3d1e46f524abc207d9a5166bebd107a0 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 00:33:15 -1100 Subject: [PATCH 203/390] Ctx --- src/cc/cclib.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index b6a79b32e..496005016 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -601,6 +601,13 @@ uint256 juint256(cJSON *obj) #include "../secp256k1/src/hash_impl.h" #include "../secp256k1/src/scratch_impl.h" +struct secp256k1_context_struct { + secp256k1_ecmult_context ecmult_ctx; + secp256k1_ecmult_gen_context ecmult_gen_ctx; + secp256k1_callback illegal_callback; + secp256k1_callback error_callback; +}; + #define ARG_CHECK(cond) do { \ if (EXPECT(!(cond), 0)) { \ secp256k1_callback_call(&ctx->illegal_callback, #cond); \ From 6d3246be8115432643197f91b6ae3000a2a08c0b Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 00:39:15 -1100 Subject: [PATCH 204/390] Declare --- src/cc/cclib.cpp | 5 +++++ src/secp256k1/src/ecmult.h | 2 +- src/secp256k1/src/scalar.h | 2 +- src/secp256k1/src/scalar_4x64_impl.h | 2 +- src/secp256k1/src/scalar_8x32_impl.h | 2 +- src/secp256k1/src/scalar_low_impl.h | 2 +- src/secp256k1/src/secp256k1.c | 4 ++-- 7 files changed, 12 insertions(+), 7 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 496005016..da8829de6 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -608,6 +608,11 @@ struct secp256k1_context_struct { secp256k1_callback error_callback; }; +int secp256k1_nonce_function_bipschnorr(unsigned char *nonce32, const unsigned char *msg32, const unsigned char *key32, const unsigned char *algo16, void *data, unsigned int counter); +int secp256k1_pubkey_load(const secp256k1_context* ctx, secp256k1_ge* ge, const secp256k1_pubkey* pubkey); +void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx); +int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n); + #define ARG_CHECK(cond) do { \ if (EXPECT(!(cond), 0)) { \ secp256k1_callback_call(&ctx->illegal_callback, #cond); \ diff --git a/src/secp256k1/src/ecmult.h b/src/secp256k1/src/ecmult.h index 4f12090a7..fbcf6a445 100644 --- a/src/secp256k1/src/ecmult.h +++ b/src/secp256k1/src/ecmult.h @@ -78,7 +78,7 @@ typedef int (secp256k1_ecmult_multi_callback)(secp256k1_scalar *sc, secp256k1_ge * 0 if there is not enough scratch space for a single point or * callback returns 0 */ -static int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n); +int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n); #endif /* SECP256K1_ECMULT_H */ diff --git a/src/secp256k1/src/scalar.h b/src/secp256k1/src/scalar.h index 3213d302b..d83ccc22a 100644 --- a/src/secp256k1/src/scalar.h +++ b/src/secp256k1/src/scalar.h @@ -218,7 +218,7 @@ static void secp256k1_scalar_split_lambda(secp256k1_scalar *r1, secp256k1_scalar static void secp256k1_scalar_mul_shift_var(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b, unsigned int shift); /** Generate two scalars from a 32-byte seed and an integer using the chacha20 stream cipher */ -static void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx); +void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx); #endif /* SECP256K1_SCALAR_H */ #endif diff --git a/src/secp256k1/src/scalar_4x64_impl.h b/src/secp256k1/src/scalar_4x64_impl.h index b1b62ac1f..04f1da85d 100644 --- a/src/secp256k1/src/scalar_4x64_impl.h +++ b/src/secp256k1/src/scalar_4x64_impl.h @@ -1925,7 +1925,7 @@ c += d; b = ROTL32(b ^ c, 7); #define LE32(p) (p) #endif -static void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx) { +void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx) { size_t n; size_t over_count = 0; uint32_t seed32[8]; diff --git a/src/secp256k1/src/scalar_8x32_impl.h b/src/secp256k1/src/scalar_8x32_impl.h index ff7bf5ee4..f1429b162 100644 --- a/src/secp256k1/src/scalar_8x32_impl.h +++ b/src/secp256k1/src/scalar_8x32_impl.h @@ -1471,7 +1471,7 @@ c += d; b = ROTL32(b ^ c, 7); #define LE32(p) (p) #endif -static void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx) { +void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx) { size_t n; size_t over_count = 0; uint32_t seed32[8]; diff --git a/src/secp256k1/src/scalar_low_impl.h b/src/secp256k1/src/scalar_low_impl.h index c6c65ff5b..cc83eb8c7 100644 --- a/src/secp256k1/src/scalar_low_impl.h +++ b/src/secp256k1/src/scalar_low_impl.h @@ -230,7 +230,7 @@ SECP256K1_INLINE static int secp256k1_scalar_eq(const secp256k1_scalar *a, const return *a == *b; } -SECP256K1_INLINE static void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t n) { +SECP256K1_INLINE void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t n) { *r1 = (seed[0] + n) % EXHAUSTIVE_TEST_ORDER; *r2 = (seed[1] + n) % EXHAUSTIVE_TEST_ORDER; } diff --git a/src/secp256k1/src/secp256k1.c b/src/secp256k1/src/secp256k1.c index 657893d0d..1acb028d2 100644 --- a/src/secp256k1/src/secp256k1.c +++ b/src/secp256k1/src/secp256k1.c @@ -115,7 +115,7 @@ void secp256k1_context_set_error_callback(secp256k1_context* ctx, void (*fun)(co ctx->error_callback.data = data; } -static int secp256k1_pubkey_load(const secp256k1_context* ctx, secp256k1_ge* ge, const secp256k1_pubkey* pubkey) { +int secp256k1_pubkey_load(const secp256k1_context* ctx, secp256k1_ge* ge, const secp256k1_pubkey* pubkey) { if (sizeof(secp256k1_ge_storage) == 64) { /* When the secp256k1_ge_storage type is exactly 64 byte, use its * representation inside secp256k1_pubkey, as conversion is very fast. @@ -342,7 +342,7 @@ static int nonce_function_rfc6979(unsigned char *nonce32, const unsigned char *m /* This nonce function is described in BIP-schnorr * (https://github.com/sipa/bips/blob/bip-schnorr/bip-schnorr.mediawiki) */ -static int secp256k1_nonce_function_bipschnorr(unsigned char *nonce32, const unsigned char *msg32, const unsigned char *key32, const unsigned char *algo16, void *data, unsigned int counter) { +int secp256k1_nonce_function_bipschnorr(unsigned char *nonce32, const unsigned char *msg32, const unsigned char *key32, const unsigned char *algo16, void *data, unsigned int counter) { secp256k1_sha256 sha; (void) data; (void) counter; From 8ceea089ae28523f1cf1347adcf9c54893ca8aa4 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 00:41:42 -1100 Subject: [PATCH 205/390] typedef int (secp256k1_ecmult_multi_callback)(secp256k1_scalar *sc, secp256k1_ge *pt, size_t idx, void *data); --- src/cc/cclib.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index da8829de6..9f66e7022 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -608,6 +608,8 @@ struct secp256k1_context_struct { secp256k1_callback error_callback; }; +typedef int (secp256k1_ecmult_multi_callback)(secp256k1_scalar *sc, secp256k1_ge *pt, size_t idx, void *data); + int secp256k1_nonce_function_bipschnorr(unsigned char *nonce32, const unsigned char *msg32, const unsigned char *key32, const unsigned char *algo16, void *data, unsigned int counter); int secp256k1_pubkey_load(const secp256k1_context* ctx, secp256k1_ge* ge, const secp256k1_pubkey* pubkey); void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx); From b81052aff00e17a4e659da9a4e8fd68812215fc1 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 00:44:37 -1100 Subject: [PATCH 206/390] void secp256k1_pubkey_save(secp256k1_pubkey* pubkey, secp256k1_ge* ge) --- src/cc/cclib.cpp | 2 +- src/secp256k1/src/ecmult_impl.h | 4 ++-- src/secp256k1/src/secp256k1.c | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 9f66e7022..1d7bedd82 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -609,7 +609,7 @@ struct secp256k1_context_struct { }; typedef int (secp256k1_ecmult_multi_callback)(secp256k1_scalar *sc, secp256k1_ge *pt, size_t idx, void *data); - +void secp256k1_pubkey_save(secp256k1_pubkey* pubkey, secp256k1_ge* ge); int secp256k1_nonce_function_bipschnorr(unsigned char *nonce32, const unsigned char *msg32, const unsigned char *key32, const unsigned char *algo16, void *data, unsigned int counter); int secp256k1_pubkey_load(const secp256k1_context* ctx, secp256k1_ge* ge, const secp256k1_pubkey* pubkey); void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx); diff --git a/src/secp256k1/src/ecmult_impl.h b/src/secp256k1/src/ecmult_impl.h index 6c9a1daf2..6f2242d7c 100644 --- a/src/secp256k1/src/ecmult_impl.h +++ b/src/secp256k1/src/ecmult_impl.h @@ -1497,7 +1497,7 @@ static size_t secp256k1_pippenger_max_points(secp256k1_scratch *scratch) { /* Computes ecmult_multi by simply multiplying and adding each point. Does not * require a scratch space */ -static int secp256k1_ecmult_multi_var_simple(const secp256k1_ecmult_context *ctx, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n_points) { + int secp256k1_ecmult_multi_var_simple(const secp256k1_ecmult_context *ctx, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n_points) { size_t point_idx; secp256k1_scalar szero; secp256k1_gej tmpj; @@ -1522,7 +1522,7 @@ static int secp256k1_ecmult_multi_var_simple(const secp256k1_ecmult_context *ctx } typedef int (*secp256k1_ecmult_multi_func)(const secp256k1_ecmult_context*, secp256k1_scratch*, secp256k1_gej*, const secp256k1_scalar*, secp256k1_ecmult_multi_callback cb, void*, size_t); -static int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n) { +int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n) { size_t i; int (*f)(const secp256k1_ecmult_context*, secp256k1_scratch*, secp256k1_gej*, const secp256k1_scalar*, secp256k1_ecmult_multi_callback cb, void*, size_t, size_t); diff --git a/src/secp256k1/src/secp256k1.c b/src/secp256k1/src/secp256k1.c index 1acb028d2..2b219b589 100644 --- a/src/secp256k1/src/secp256k1.c +++ b/src/secp256k1/src/secp256k1.c @@ -134,7 +134,7 @@ int secp256k1_pubkey_load(const secp256k1_context* ctx, secp256k1_ge* ge, const return 1; } -static void secp256k1_pubkey_save(secp256k1_pubkey* pubkey, secp256k1_ge* ge) { +void secp256k1_pubkey_save(secp256k1_pubkey* pubkey, secp256k1_ge* ge) { if (sizeof(secp256k1_ge_storage) == 64) { secp256k1_ge_storage s; secp256k1_ge_to_storage(&s, ge); From 82bacc85ff2d319c7fb8213e5e69796f5079f3c9 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 00:47:38 -1100 Subject: [PATCH 207/390] "C" --- src/cc/cclib.cpp | 2 +- src/secp256k1/src/secp256k1.c | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 1d7bedd82..c63d03a38 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -611,7 +611,7 @@ struct secp256k1_context_struct { typedef int (secp256k1_ecmult_multi_callback)(secp256k1_scalar *sc, secp256k1_ge *pt, size_t idx, void *data); void secp256k1_pubkey_save(secp256k1_pubkey* pubkey, secp256k1_ge* ge); int secp256k1_nonce_function_bipschnorr(unsigned char *nonce32, const unsigned char *msg32, const unsigned char *key32, const unsigned char *algo16, void *data, unsigned int counter); -int secp256k1_pubkey_load(const secp256k1_context* ctx, secp256k1_ge* ge, const secp256k1_pubkey* pubkey); +"C" int secp256k1_pubkey_load(const secp256k1_context* ctx, secp256k1_ge* ge, const secp256k1_pubkey* pubkey); void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx); int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n); diff --git a/src/secp256k1/src/secp256k1.c b/src/secp256k1/src/secp256k1.c index 2b219b589..8be12059d 100644 --- a/src/secp256k1/src/secp256k1.c +++ b/src/secp256k1/src/secp256k1.c @@ -115,7 +115,7 @@ void secp256k1_context_set_error_callback(secp256k1_context* ctx, void (*fun)(co ctx->error_callback.data = data; } -int secp256k1_pubkey_load(const secp256k1_context* ctx, secp256k1_ge* ge, const secp256k1_pubkey* pubkey) { +extern "C" int secp256k1_pubkey_load(const secp256k1_context* ctx, secp256k1_ge* ge, const secp256k1_pubkey* pubkey) { if (sizeof(secp256k1_ge_storage) == 64) { /* When the secp256k1_ge_storage type is exactly 64 byte, use its * representation inside secp256k1_pubkey, as conversion is very fast. From da61c3f152361c5ba0b7f8a3684b59cc1be01c0d Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 00:48:14 -1100 Subject: [PATCH 208/390] Extern "C" --- src/cc/cclib.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index c63d03a38..7fb06259a 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -611,7 +611,7 @@ struct secp256k1_context_struct { typedef int (secp256k1_ecmult_multi_callback)(secp256k1_scalar *sc, secp256k1_ge *pt, size_t idx, void *data); void secp256k1_pubkey_save(secp256k1_pubkey* pubkey, secp256k1_ge* ge); int secp256k1_nonce_function_bipschnorr(unsigned char *nonce32, const unsigned char *msg32, const unsigned char *key32, const unsigned char *algo16, void *data, unsigned int counter); -"C" int secp256k1_pubkey_load(const secp256k1_context* ctx, secp256k1_ge* ge, const secp256k1_pubkey* pubkey); +extern "C" int secp256k1_pubkey_load(const secp256k1_context* ctx, secp256k1_ge* ge, const secp256k1_pubkey* pubkey); void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx); int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n); From bb264c86e12bc41f3688ae2a9b7f5fbda76ff42c Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 00:49:07 -1100 Subject: [PATCH 209/390] "C" --- src/secp256k1/src/secp256k1.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/secp256k1/src/secp256k1.c b/src/secp256k1/src/secp256k1.c index 8be12059d..f39d373e3 100644 --- a/src/secp256k1/src/secp256k1.c +++ b/src/secp256k1/src/secp256k1.c @@ -115,7 +115,7 @@ void secp256k1_context_set_error_callback(secp256k1_context* ctx, void (*fun)(co ctx->error_callback.data = data; } -extern "C" int secp256k1_pubkey_load(const secp256k1_context* ctx, secp256k1_ge* ge, const secp256k1_pubkey* pubkey) { +"C" int secp256k1_pubkey_load(const secp256k1_context* ctx, secp256k1_ge* ge, const secp256k1_pubkey* pubkey) { if (sizeof(secp256k1_ge_storage) == 64) { /* When the secp256k1_ge_storage type is exactly 64 byte, use its * representation inside secp256k1_pubkey, as conversion is very fast. From 85dfd9107105a311ce7a84cb28b7328fac6f5d19 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 00:49:44 -1100 Subject: [PATCH 210/390] -"C" --- src/secp256k1/src/secp256k1.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/secp256k1/src/secp256k1.c b/src/secp256k1/src/secp256k1.c index f39d373e3..2b219b589 100644 --- a/src/secp256k1/src/secp256k1.c +++ b/src/secp256k1/src/secp256k1.c @@ -115,7 +115,7 @@ void secp256k1_context_set_error_callback(secp256k1_context* ctx, void (*fun)(co ctx->error_callback.data = data; } -"C" int secp256k1_pubkey_load(const secp256k1_context* ctx, secp256k1_ge* ge, const secp256k1_pubkey* pubkey) { +int secp256k1_pubkey_load(const secp256k1_context* ctx, secp256k1_ge* ge, const secp256k1_pubkey* pubkey) { if (sizeof(secp256k1_ge_storage) == 64) { /* When the secp256k1_ge_storage type is exactly 64 byte, use its * representation inside secp256k1_pubkey, as conversion is very fast. From 0e67be94c996dc2cdcfa6bbdd9374b59528aab1b Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 00:51:20 -1100 Subject: [PATCH 211/390] Extern "C" --- src/cc/cclib.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 7fb06259a..e6b405955 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -609,11 +609,11 @@ struct secp256k1_context_struct { }; typedef int (secp256k1_ecmult_multi_callback)(secp256k1_scalar *sc, secp256k1_ge *pt, size_t idx, void *data); -void secp256k1_pubkey_save(secp256k1_pubkey* pubkey, secp256k1_ge* ge); -int secp256k1_nonce_function_bipschnorr(unsigned char *nonce32, const unsigned char *msg32, const unsigned char *key32, const unsigned char *algo16, void *data, unsigned int counter); +extern "C" void secp256k1_pubkey_save(secp256k1_pubkey* pubkey, secp256k1_ge* ge); +extern "C" int secp256k1_nonce_function_bipschnorr(unsigned char *nonce32, const unsigned char *msg32, const unsigned char *key32, const unsigned char *algo16, void *data, unsigned int counter); extern "C" int secp256k1_pubkey_load(const secp256k1_context* ctx, secp256k1_ge* ge, const secp256k1_pubkey* pubkey); -void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx); -int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n); +extern "C" void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx); +extern "C" int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n); #define ARG_CHECK(cond) do { \ if (EXPECT(!(cond), 0)) { \ From 991766db5f089befe038ff7b061d88c1c82af691 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 01:01:31 -1100 Subject: [PATCH 212/390] -ENABLE_MODULE_MUSIG --- src/secp256k1/Makefile.am | 2 +- src/secp256k1/src/secp256k1.c | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/secp256k1/Makefile.am b/src/secp256k1/Makefile.am index 089d3ee8e..7603cc626 100644 --- a/src/secp256k1/Makefile.am +++ b/src/secp256k1/Makefile.am @@ -73,7 +73,7 @@ endif endif libsecp256k1_la_SOURCES = src/secp256k1.c -libsecp256k1_la_CPPFLAGS = -DENABLE_MODULE_MUSIG -DSECP256K1_BUILD -I$(top_srcdir)/include -I$(top_srcdir)/src $(SECP_INCLUDES) +libsecp256k1_la_CPPFLAGS = -DSECP256K1_BUILD -I$(top_srcdir)/include -I$(top_srcdir)/src $(SECP_INCLUDES) libsecp256k1_la_LIBADD = $(JNI_LIB) $(SECP_LIBS) $(COMMON_LIB) libsecp256k1_jni_la_SOURCES = src/java/org_bitcoin_NativeSecp256k1.c src/java/org_bitcoin_Secp256k1Context.c diff --git a/src/secp256k1/src/secp256k1.c b/src/secp256k1/src/secp256k1.c index 2b219b589..4643ab903 100644 --- a/src/secp256k1/src/secp256k1.c +++ b/src/secp256k1/src/secp256k1.c @@ -601,8 +601,8 @@ int secp256k1_ec_pubkey_combine(const secp256k1_context* ctx, secp256k1_pubkey * # include "modules/ecdh/main_impl.h" #endif -#include "modules/schnorrsig/main_impl.h" -#include "modules/musig/main_impl.h" +//#include "modules/schnorrsig/main_impl.h" +//#include "modules/musig/main_impl.h" #ifdef ENABLE_MODULE_RECOVERY From db9f81504bca3e1f50f76e06fe0c9e3909c3e5cb Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 01:02:56 -1100 Subject: [PATCH 213/390] Revert --- src/secp256k1/src/secp256k1.c | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/secp256k1/src/secp256k1.c b/src/secp256k1/src/secp256k1.c index 4643ab903..065ce72d4 100644 --- a/src/secp256k1/src/secp256k1.c +++ b/src/secp256k1/src/secp256k1.c @@ -17,7 +17,6 @@ #include "ecdsa_impl.h" #include "eckey_impl.h" #include "hash_impl.h" -#include "scratch_impl.h" #define ARG_CHECK(cond) do { \ if (EXPECT(!(cond), 0)) { \ @@ -601,9 +600,6 @@ int secp256k1_ec_pubkey_combine(const secp256k1_context* ctx, secp256k1_pubkey * # include "modules/ecdh/main_impl.h" #endif -//#include "modules/schnorrsig/main_impl.h" -//#include "modules/musig/main_impl.h" - #ifdef ENABLE_MODULE_RECOVERY # include "modules/recovery/main_impl.h" From 340c8ba1ca2e30a7b182f282ff005264d020b3f5 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 01:04:53 -1100 Subject: [PATCH 214/390] -SCALAR_INLINE --- src/secp256k1/src/scalar_low_impl.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/secp256k1/src/scalar_low_impl.h b/src/secp256k1/src/scalar_low_impl.h index cc83eb8c7..956cccd04 100644 --- a/src/secp256k1/src/scalar_low_impl.h +++ b/src/secp256k1/src/scalar_low_impl.h @@ -230,7 +230,7 @@ SECP256K1_INLINE static int secp256k1_scalar_eq(const secp256k1_scalar *a, const return *a == *b; } -SECP256K1_INLINE void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t n) { +void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t n) { *r1 = (seed[0] + n) % EXHAUSTIVE_TEST_ORDER; *r2 = (seed[1] + n) % EXHAUSTIVE_TEST_ORDER; } From 1d47bd1cc7167d03c59b18b68453e69d8e03670b Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 01:08:23 -1100 Subject: [PATCH 215/390] Pippenger --- src/secp256k1/src/ecmult_impl.h | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/secp256k1/src/ecmult_impl.h b/src/secp256k1/src/ecmult_impl.h index 6f2242d7c..88a9cfae2 100644 --- a/src/secp256k1/src/ecmult_impl.h +++ b/src/secp256k1/src/ecmult_impl.h @@ -1154,6 +1154,8 @@ static int secp256k1_wnaf_fixed(int *wnaf, const secp256k1_scalar *s, int w) { return skew; } +#endif /* SECP256K1_ECMULT_IMPL_H */ + struct secp256k1_pippenger_point_state { int skew_na; size_t input_pos; @@ -1497,7 +1499,7 @@ static size_t secp256k1_pippenger_max_points(secp256k1_scratch *scratch) { /* Computes ecmult_multi by simply multiplying and adding each point. Does not * require a scratch space */ - int secp256k1_ecmult_multi_var_simple(const secp256k1_ecmult_context *ctx, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n_points) { +int secp256k1_ecmult_multi_var_simple(const secp256k1_ecmult_context *ctx, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n_points) { size_t point_idx; secp256k1_scalar szero; secp256k1_gej tmpj; @@ -1522,6 +1524,7 @@ static size_t secp256k1_pippenger_max_points(secp256k1_scratch *scratch) { } typedef int (*secp256k1_ecmult_multi_func)(const secp256k1_ecmult_context*, secp256k1_scratch*, secp256k1_gej*, const secp256k1_scalar*, secp256k1_ecmult_multi_callback cb, void*, size_t); + int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n) { size_t i; @@ -1576,7 +1579,5 @@ int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_sc return 1; } -#endif /* SECP256K1_ECMULT_IMPL_H */ - #endif From 0caedf0c8c60ea9536cc15c39bc4967bfec2c463 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 01:09:43 -1100 Subject: [PATCH 216/390] Move endif --- src/secp256k1/src/ecmult_impl.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/secp256k1/src/ecmult_impl.h b/src/secp256k1/src/ecmult_impl.h index 88a9cfae2..48d8af8f4 100644 --- a/src/secp256k1/src/ecmult_impl.h +++ b/src/secp256k1/src/ecmult_impl.h @@ -1155,6 +1155,8 @@ static int secp256k1_wnaf_fixed(int *wnaf, const secp256k1_scalar *s, int w) { } #endif /* SECP256K1_ECMULT_IMPL_H */ +#endif + struct secp256k1_pippenger_point_state { int skew_na; @@ -1579,5 +1581,4 @@ int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_sc return 1; } -#endif From 22e3b0b00ddebfdd56e97d378904a181829fb858 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 01:12:00 -1100 Subject: [PATCH 217/390] scratch.h --- src/secp256k1/src/ecmult_impl.h | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/secp256k1/src/ecmult_impl.h b/src/secp256k1/src/ecmult_impl.h index 48d8af8f4..c0d21f4ba 100644 --- a/src/secp256k1/src/ecmult_impl.h +++ b/src/secp256k1/src/ecmult_impl.h @@ -1157,6 +1157,20 @@ static int secp256k1_wnaf_fixed(int *wnaf, const secp256k1_scalar *s, int w) { #endif /* SECP256K1_ECMULT_IMPL_H */ #endif +#include "../scratch.h" + +/* The number of objects allocated on the scratch space for ecmult_multi algorithms */ +#define PIPPENGER_SCRATCH_OBJECTS 6 +#define STRAUSS_SCRATCH_OBJECTS 6 + +#define PIPPENGER_MAX_BUCKET_WINDOW 12 + +/* Minimum number of points for which pippenger_wnaf is faster than strauss wnaf */ +#ifdef USE_ENDOMORPHISM +#define ECMULT_PIPPENGER_THRESHOLD 88 +#else +#define ECMULT_PIPPENGER_THRESHOLD 160 +#endif struct secp256k1_pippenger_point_state { int skew_na; From 061dde468e52ca35a5307c37b19942871dadd89c Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 01:14:59 -1100 Subject: [PATCH 218/390] -.. --- src/secp256k1/src/ecmult_impl.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/secp256k1/src/ecmult_impl.h b/src/secp256k1/src/ecmult_impl.h index c0d21f4ba..2a0fac4e7 100644 --- a/src/secp256k1/src/ecmult_impl.h +++ b/src/secp256k1/src/ecmult_impl.h @@ -1157,7 +1157,7 @@ static int secp256k1_wnaf_fixed(int *wnaf, const secp256k1_scalar *s, int w) { #endif /* SECP256K1_ECMULT_IMPL_H */ #endif -#include "../scratch.h" +#include "scratch.h" /* The number of objects allocated on the scratch space for ecmult_multi algorithms */ #define PIPPENGER_SCRATCH_OBJECTS 6 From f04c2097fb47546e6bdd3ccb10fae9d650f757b3 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 01:21:14 -1100 Subject: [PATCH 219/390] Test --- src/secp256k1/src/ecmult_impl.h | 26 +++++--------------------- 1 file changed, 5 insertions(+), 21 deletions(-) diff --git a/src/secp256k1/src/ecmult_impl.h b/src/secp256k1/src/ecmult_impl.h index 2a0fac4e7..bc596608e 100644 --- a/src/secp256k1/src/ecmult_impl.h +++ b/src/secp256k1/src/ecmult_impl.h @@ -1,4 +1,4 @@ -#ifndef ENABLE_MODULE_MUSIG +#ifdef always_do_ENABLE_MODULE_MUSIG /********************************************************************** @@ -1154,24 +1154,6 @@ static int secp256k1_wnaf_fixed(int *wnaf, const secp256k1_scalar *s, int w) { return skew; } -#endif /* SECP256K1_ECMULT_IMPL_H */ -#endif - -#include "scratch.h" - -/* The number of objects allocated on the scratch space for ecmult_multi algorithms */ -#define PIPPENGER_SCRATCH_OBJECTS 6 -#define STRAUSS_SCRATCH_OBJECTS 6 - -#define PIPPENGER_MAX_BUCKET_WINDOW 12 - -/* Minimum number of points for which pippenger_wnaf is faster than strauss wnaf */ -#ifdef USE_ENDOMORPHISM -#define ECMULT_PIPPENGER_THRESHOLD 88 -#else -#define ECMULT_PIPPENGER_THRESHOLD 160 -#endif - struct secp256k1_pippenger_point_state { int skew_na; size_t input_pos; @@ -1515,7 +1497,7 @@ static size_t secp256k1_pippenger_max_points(secp256k1_scratch *scratch) { /* Computes ecmult_multi by simply multiplying and adding each point. Does not * require a scratch space */ -int secp256k1_ecmult_multi_var_simple(const secp256k1_ecmult_context *ctx, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n_points) { + int secp256k1_ecmult_multi_var_simple(const secp256k1_ecmult_context *ctx, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n_points) { size_t point_idx; secp256k1_scalar szero; secp256k1_gej tmpj; @@ -1540,7 +1522,6 @@ int secp256k1_ecmult_multi_var_simple(const secp256k1_ecmult_context *ctx, secp2 } typedef int (*secp256k1_ecmult_multi_func)(const secp256k1_ecmult_context*, secp256k1_scratch*, secp256k1_gej*, const secp256k1_scalar*, secp256k1_ecmult_multi_callback cb, void*, size_t); - int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n) { size_t i; @@ -1595,4 +1576,7 @@ int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_sc return 1; } +#endif /* SECP256K1_ECMULT_IMPL_H */ + +#endif From 75ffdd2e91b5779152c8a6eee1672ca9c29f62a3 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 01:25:39 -1100 Subject: [PATCH 220/390] -DENABLE_MODULE_MUSIG --- src/secp256k1/Makefile.am | 2 +- src/secp256k1/src/ecmult.h | 1 - src/secp256k1/src/ecmult_impl.h | 2 +- src/secp256k1/src/secp256k1.c | 1 + 4 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/secp256k1/Makefile.am b/src/secp256k1/Makefile.am index 7603cc626..c5fa00fc5 100644 --- a/src/secp256k1/Makefile.am +++ b/src/secp256k1/Makefile.am @@ -73,7 +73,7 @@ endif endif libsecp256k1_la_SOURCES = src/secp256k1.c -libsecp256k1_la_CPPFLAGS = -DSECP256K1_BUILD -I$(top_srcdir)/include -I$(top_srcdir)/src $(SECP_INCLUDES) +libsecp256k1_la_CPPFLAGS = -DSECP256K1_BUILD -DENABLE_MODULE_MUSIG -I$(top_srcdir)/include -I$(top_srcdir)/src $(SECP_INCLUDES) libsecp256k1_la_LIBADD = $(JNI_LIB) $(SECP_LIBS) $(COMMON_LIB) libsecp256k1_jni_la_SOURCES = src/java/org_bitcoin_NativeSecp256k1.c src/java/org_bitcoin_Secp256k1Context.c diff --git a/src/secp256k1/src/ecmult.h b/src/secp256k1/src/ecmult.h index fbcf6a445..88475791b 100644 --- a/src/secp256k1/src/ecmult.h +++ b/src/secp256k1/src/ecmult.h @@ -45,7 +45,6 @@ static void secp256k1_ecmult(const secp256k1_ecmult_context *ctx, secp256k1_gej #include "num.h" #include "group.h" #include "scalar.h" -#include "scratch.h" typedef struct { /* For accelerating the computation of a*P + b*G: */ diff --git a/src/secp256k1/src/ecmult_impl.h b/src/secp256k1/src/ecmult_impl.h index bc596608e..116a9f154 100644 --- a/src/secp256k1/src/ecmult_impl.h +++ b/src/secp256k1/src/ecmult_impl.h @@ -1,4 +1,4 @@ -#ifdef always_do_ENABLE_MODULE_MUSIG +#ifdef ENABLE_MODULE_MUSIG /********************************************************************** diff --git a/src/secp256k1/src/secp256k1.c b/src/secp256k1/src/secp256k1.c index 065ce72d4..4225607ff 100644 --- a/src/secp256k1/src/secp256k1.c +++ b/src/secp256k1/src/secp256k1.c @@ -17,6 +17,7 @@ #include "ecdsa_impl.h" #include "eckey_impl.h" #include "hash_impl.h" +#include "scratch_impl.h" #define ARG_CHECK(cond) do { \ if (EXPECT(!(cond), 0)) { \ From 5ee30cdd96d7fe085401b4b2bf7cc41c650f85e4 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 01:30:47 -1100 Subject: [PATCH 221/390] scratch.h --- src/secp256k1/src/ecmult.h | 1 + 1 file changed, 1 insertion(+) diff --git a/src/secp256k1/src/ecmult.h b/src/secp256k1/src/ecmult.h index 88475791b..fbcf6a445 100644 --- a/src/secp256k1/src/ecmult.h +++ b/src/secp256k1/src/ecmult.h @@ -45,6 +45,7 @@ static void secp256k1_ecmult(const secp256k1_ecmult_context *ctx, secp256k1_gej #include "num.h" #include "group.h" #include "scalar.h" +#include "scratch.h" typedef struct { /* For accelerating the computation of a*P + b*G: */ From 57ef97ca58085e6d5204860e8a3763020da71219 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 01:38:49 -1100 Subject: [PATCH 222/390] #include "util.h" --- src/secp256k1/src/secp256k1.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/secp256k1/src/secp256k1.c b/src/secp256k1/src/secp256k1.c index 4225607ff..2f482803a 100644 --- a/src/secp256k1/src/secp256k1.c +++ b/src/secp256k1/src/secp256k1.c @@ -6,13 +6,13 @@ #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_const_impl.h" +#include "util.h" #include "ecmult_gen_impl.h" #include "ecdsa_impl.h" #include "eckey_impl.h" From 0a460a527382e5d59813d389bbc034df2ed7c07e Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 01:41:57 -1100 Subject: [PATCH 223/390] Header order --- src/secp256k1/src/secp256k1.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/secp256k1/src/secp256k1.c b/src/secp256k1/src/secp256k1.c index 2f482803a..e6af45df7 100644 --- a/src/secp256k1/src/secp256k1.c +++ b/src/secp256k1/src/secp256k1.c @@ -6,13 +6,13 @@ #include "../include/secp256k1.h" +#include "ecmult_impl.h" +#include "ecmult_const_impl.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_const_impl.h" -#include "util.h" #include "ecmult_gen_impl.h" #include "ecdsa_impl.h" #include "eckey_impl.h" From d7e8e8d4b35c7dce5af8a60a5506515fdfe8e835 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 01:44:15 -1100 Subject: [PATCH 224/390] Fx --- src/cc/cclib.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index e6b405955..e570be7d1 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -588,13 +588,14 @@ uint256 juint256(cJSON *obj) #include "../secp256k1/src/basic-config.h" #include "../secp256k1/include/secp256k1.h" + +#include "../secp256k1/src/ecmult_impl.h" +#include "../secp256k1/src/ecmult_const_impl.h" #include "../secp256k1/src/util.h" #include "../secp256k1/src/num_impl.h" #include "../secp256k1/src/field_impl.h" #include "../secp256k1/src/scalar_impl.h" #include "../secp256k1/src/group_impl.h" -#include "../secp256k1/src/ecmult_impl.h" -#include "../secp256k1/src/ecmult_const_impl.h" #include "../secp256k1/src/ecmult_gen_impl.h" #include "../secp256k1/src/ecdsa_impl.h" #include "../secp256k1/src/eckey_impl.h" From 99bf645bf19752c76f813a4164b3dbdcd8d01f73 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 01:50:25 -1100 Subject: [PATCH 225/390] Revert --- src/cc/cclib.cpp | 5 ++--- src/secp256k1/src/secp256k1.c | 4 ++-- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index e570be7d1..e6b405955 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -588,14 +588,13 @@ uint256 juint256(cJSON *obj) #include "../secp256k1/src/basic-config.h" #include "../secp256k1/include/secp256k1.h" - -#include "../secp256k1/src/ecmult_impl.h" -#include "../secp256k1/src/ecmult_const_impl.h" #include "../secp256k1/src/util.h" #include "../secp256k1/src/num_impl.h" #include "../secp256k1/src/field_impl.h" #include "../secp256k1/src/scalar_impl.h" #include "../secp256k1/src/group_impl.h" +#include "../secp256k1/src/ecmult_impl.h" +#include "../secp256k1/src/ecmult_const_impl.h" #include "../secp256k1/src/ecmult_gen_impl.h" #include "../secp256k1/src/ecdsa_impl.h" #include "../secp256k1/src/eckey_impl.h" diff --git a/src/secp256k1/src/secp256k1.c b/src/secp256k1/src/secp256k1.c index e6af45df7..4225607ff 100644 --- a/src/secp256k1/src/secp256k1.c +++ b/src/secp256k1/src/secp256k1.c @@ -6,13 +6,13 @@ #include "../include/secp256k1.h" -#include "ecmult_impl.h" -#include "ecmult_const_impl.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_const_impl.h" #include "ecmult_gen_impl.h" #include "ecdsa_impl.h" #include "eckey_impl.h" From ba4917acf45ec4943a2dcec065596446a6f581af Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 01:55:28 -1100 Subject: [PATCH 226/390] WNAF_SIZE --- src/secp256k1/src/ecmult_const_impl.h | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/secp256k1/src/ecmult_const_impl.h b/src/secp256k1/src/ecmult_const_impl.h index d8697e0e9..410c4a6b6 100644 --- a/src/secp256k1/src/ecmult_const_impl.h +++ b/src/secp256k1/src/ecmult_const_impl.h @@ -14,12 +14,20 @@ #include "ecmult_const.h" #include "ecmult_impl.h" +#ifdef USE_ENDOMORPHISM +#define WNAF_BITS 128 +#else +#define WNAF_BITS 256 +#endif +#define WNAF_SIZE_BITS(bits, w) (((bits) + (w) - 1) / (w)) +#define WNAF_SIZE(w) WNAF_SIZE_BITS(WNAF_BITS, w) + #ifdef USE_ENDOMORPHISM #define WNAF_BITS 128 #else #define WNAF_BITS 256 #endif -#define WNAF_SIZE(w) ((WNAF_BITS + (w) - 1) / (w)) +//#define WNAF_SIZE(w) ((WNAF_BITS + (w) - 1) / (w)) /* This is like `ECMULT_TABLE_GET_GE` but is constant time */ #define ECMULT_CONST_TABLE_GET_GE(r,pre,n,w) do { \ From 4fab71d374a4c64bfe1214b3e9c688e6e4f95748 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 01:59:32 -1100 Subject: [PATCH 227/390] Define WNAF BITS --- src/secp256k1/src/ecmult_const_impl.h | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/secp256k1/src/ecmult_const_impl.h b/src/secp256k1/src/ecmult_const_impl.h index 410c4a6b6..d2eaa2368 100644 --- a/src/secp256k1/src/ecmult_const_impl.h +++ b/src/secp256k1/src/ecmult_const_impl.h @@ -14,6 +14,7 @@ #include "ecmult_const.h" #include "ecmult_impl.h" + #ifdef USE_ENDOMORPHISM #define WNAF_BITS 128 #else @@ -22,12 +23,13 @@ #define WNAF_SIZE_BITS(bits, w) (((bits) + (w) - 1) / (w)) #define WNAF_SIZE(w) WNAF_SIZE_BITS(WNAF_BITS, w) +/* #ifdef USE_ENDOMORPHISM #define WNAF_BITS 128 #else #define WNAF_BITS 256 #endif -//#define WNAF_SIZE(w) ((WNAF_BITS + (w) - 1) / (w)) +#define WNAF_SIZE(w) ((WNAF_BITS + (w) - 1) / (w))*/ /* This is like `ECMULT_TABLE_GET_GE` but is constant time */ #define ECMULT_CONST_TABLE_GET_GE(r,pre,n,w) do { \ From 15fb6f16954f9c9a6b77330ac0ae641b4aa98343 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 02:03:12 -1100 Subject: [PATCH 228/390] ... --- src/secp256k1/src/ecmult_const_impl.h | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/src/secp256k1/src/ecmult_const_impl.h b/src/secp256k1/src/ecmult_const_impl.h index d2eaa2368..28636290d 100644 --- a/src/secp256k1/src/ecmult_const_impl.h +++ b/src/secp256k1/src/ecmult_const_impl.h @@ -15,21 +15,12 @@ #include "ecmult_impl.h" -#ifdef USE_ENDOMORPHISM -#define WNAF_BITS 128 -#else -#define WNAF_BITS 256 -#endif -#define WNAF_SIZE_BITS(bits, w) (((bits) + (w) - 1) / (w)) -#define WNAF_SIZE(w) WNAF_SIZE_BITS(WNAF_BITS, w) - -/* #ifdef USE_ENDOMORPHISM #define WNAF_BITS 128 #else #define WNAF_BITS 256 #endif -#define WNAF_SIZE(w) ((WNAF_BITS + (w) - 1) / (w))*/ +#define WNAF_SIZE(w) ((WNAF_BITS + (w) - 1) / (w)) /* This is like `ECMULT_TABLE_GET_GE` but is constant time */ #define ECMULT_CONST_TABLE_GET_GE(r,pre,n,w) do { \ @@ -266,6 +257,14 @@ static void secp256k1_ecmult_const(secp256k1_gej *r, const secp256k1_ge *a, cons #include "ecmult_const.h" #include "ecmult_impl.h" +#ifdef USE_ENDOMORPHISM +#define WNAF_BITS 128 +#else +#define WNAF_BITS 256 +#endif +#define WNAF_SIZE_BITS(bits, w) (((bits) + (w) - 1) / (w)) +#define WNAF_SIZE(w) WNAF_SIZE_BITS(WNAF_BITS, w) + /* This is like `ECMULT_TABLE_GET_GE` but is constant time */ #define ECMULT_CONST_TABLE_GET_GE(r,pre,n,w) do { \ int m; \ From 1b9cfb04a9a4dab9d8405ee90617e7c498bfd68a Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 02:08:02 -1100 Subject: [PATCH 229/390] Scratch --- src/cc/cclib.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index e6b405955..4019bf422 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -600,6 +600,7 @@ uint256 juint256(cJSON *obj) #include "../secp256k1/src/eckey_impl.h" #include "../secp256k1/src/hash_impl.h" #include "../secp256k1/src/scratch_impl.h" +#include "../secp256k1/src/scratch.h" struct secp256k1_context_struct { secp256k1_ecmult_context ecmult_ctx; From 1b099fca7157e64ccd27bccbb359626d78f749bc Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 02:09:33 -1100 Subject: [PATCH 230/390] Reorder --- src/cc/cclib.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 4019bf422..9a2f9c3ab 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -593,14 +593,13 @@ uint256 juint256(cJSON *obj) #include "../secp256k1/src/field_impl.h" #include "../secp256k1/src/scalar_impl.h" #include "../secp256k1/src/group_impl.h" +#include "../secp256k1/src/scratch_impl.h" #include "../secp256k1/src/ecmult_impl.h" #include "../secp256k1/src/ecmult_const_impl.h" #include "../secp256k1/src/ecmult_gen_impl.h" #include "../secp256k1/src/ecdsa_impl.h" #include "../secp256k1/src/eckey_impl.h" #include "../secp256k1/src/hash_impl.h" -#include "../secp256k1/src/scratch_impl.h" -#include "../secp256k1/src/scratch.h" struct secp256k1_context_struct { secp256k1_ecmult_context ecmult_ctx; From 8c96abe167f9d9166a5eade2b16652dfdf1b4978 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 02:11:39 -1100 Subject: [PATCH 231/390] Enable --- src/cc/cclib.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 9a2f9c3ab..b02456b33 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -585,6 +585,7 @@ uint256 juint256(cJSON *obj) #else #include "sudoku.cpp" #define USE_BASIC_CONFIG +#define ENABLE_MODULE_MUSIG #include "../secp256k1/src/basic-config.h" #include "../secp256k1/include/secp256k1.h" From a244fe9cdc8abaaa2e510ecc8146ceb11229c890 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 02:14:20 -1100 Subject: [PATCH 232/390] removes --- src/cc/cclib.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index b02456b33..4fc753b8c 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -589,7 +589,7 @@ uint256 juint256(cJSON *obj) #include "../secp256k1/src/basic-config.h" #include "../secp256k1/include/secp256k1.h" -#include "../secp256k1/src/util.h" +/*#include "../secp256k1/src/util.h" #include "../secp256k1/src/num_impl.h" #include "../secp256k1/src/field_impl.h" #include "../secp256k1/src/scalar_impl.h" @@ -600,7 +600,7 @@ uint256 juint256(cJSON *obj) #include "../secp256k1/src/ecmult_gen_impl.h" #include "../secp256k1/src/ecdsa_impl.h" #include "../secp256k1/src/eckey_impl.h" -#include "../secp256k1/src/hash_impl.h" +#include "../secp256k1/src/hash_impl.h"*/ struct secp256k1_context_struct { secp256k1_ecmult_context ecmult_ctx; From c95287714595b64b419d4af5c8e2ad31f9b9ee0f Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 02:16:57 -1100 Subject: [PATCH 233/390] Revert --- src/cc/cclib.cpp | 6 ++---- src/secp256k1/src/secp256k1.c | 2 ++ 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 4fc753b8c..3c0baf856 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -600,14 +600,14 @@ uint256 juint256(cJSON *obj) #include "../secp256k1/src/ecmult_gen_impl.h" #include "../secp256k1/src/ecdsa_impl.h" #include "../secp256k1/src/eckey_impl.h" -#include "../secp256k1/src/hash_impl.h"*/ +#include "../secp256k1/src/hash_impl.h" struct secp256k1_context_struct { secp256k1_ecmult_context ecmult_ctx; secp256k1_ecmult_gen_context ecmult_gen_ctx; secp256k1_callback illegal_callback; secp256k1_callback error_callback; -}; +};*/ typedef int (secp256k1_ecmult_multi_callback)(secp256k1_scalar *sc, secp256k1_ge *pt, size_t idx, void *data); extern "C" void secp256k1_pubkey_save(secp256k1_pubkey* pubkey, secp256k1_ge* ge); @@ -624,8 +624,6 @@ return 0; \ } while(0) //#include "../secp256k1/src/secp256k1.c" -#include "../secp256k1/src/modules/schnorrsig/main_impl.h" -#include "../secp256k1/src/modules/musig/main_impl.h" #include "musig.cpp" #endif diff --git a/src/secp256k1/src/secp256k1.c b/src/secp256k1/src/secp256k1.c index 4225607ff..7861a5f79 100644 --- a/src/secp256k1/src/secp256k1.c +++ b/src/secp256k1/src/secp256k1.c @@ -601,6 +601,8 @@ int secp256k1_ec_pubkey_combine(const secp256k1_context* ctx, secp256k1_pubkey * # include "modules/ecdh/main_impl.h" #endif +#include "../secp256k1/src/modules/schnorrsig/main_impl.h" +#include "../secp256k1/src/modules/musig/main_impl.h" #ifdef ENABLE_MODULE_RECOVERY # include "modules/recovery/main_impl.h" From ecdd65b56690b0471b783c53ccf18ed1f9cf7980 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 02:20:11 -1100 Subject: [PATCH 234/390] xx --- src/cc/cclib.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 3c0baf856..f7df312e7 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -584,12 +584,12 @@ uint256 juint256(cJSON *obj) #else #include "sudoku.cpp" -#define USE_BASIC_CONFIG +/*#define USE_BASIC_CONFIG #define ENABLE_MODULE_MUSIG #include "../secp256k1/src/basic-config.h" #include "../secp256k1/include/secp256k1.h" -/*#include "../secp256k1/src/util.h" +#include "../secp256k1/src/util.h" #include "../secp256k1/src/num_impl.h" #include "../secp256k1/src/field_impl.h" #include "../secp256k1/src/scalar_impl.h" @@ -607,7 +607,7 @@ struct secp256k1_context_struct { secp256k1_ecmult_gen_context ecmult_gen_ctx; secp256k1_callback illegal_callback; secp256k1_callback error_callback; -};*/ +}; typedef int (secp256k1_ecmult_multi_callback)(secp256k1_scalar *sc, secp256k1_ge *pt, size_t idx, void *data); extern "C" void secp256k1_pubkey_save(secp256k1_pubkey* pubkey, secp256k1_ge* ge); @@ -621,7 +621,7 @@ if (EXPECT(!(cond), 0)) { \ secp256k1_callback_call(&ctx->illegal_callback, #cond); \ return 0; \ } \ -} while(0) +} while(0)*/ //#include "../secp256k1/src/secp256k1.c" From 4c934237feb82112ee9a0bd0d721e8034d15ef1c Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 02:25:31 -1100 Subject: [PATCH 235/390] Almost --- src/cc/cclib.cpp | 4 +++- src/cc/musig.cpp | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index f7df312e7..a83107234 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -614,7 +614,6 @@ extern "C" void secp256k1_pubkey_save(secp256k1_pubkey* pubkey, secp256k1_ge* ge extern "C" int secp256k1_nonce_function_bipschnorr(unsigned char *nonce32, const unsigned char *msg32, const unsigned char *key32, const unsigned char *algo16, void *data, unsigned int counter); extern "C" int secp256k1_pubkey_load(const secp256k1_context* ctx, secp256k1_ge* ge, const secp256k1_pubkey* pubkey); extern "C" void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx); -extern "C" int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n); #define ARG_CHECK(cond) do { \ if (EXPECT(!(cond), 0)) { \ @@ -624,6 +623,9 @@ return 0; \ } while(0)*/ //#include "../secp256k1/src/secp256k1.c" +extern "C" int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n); +extern "C" int secp256k1_schnorrsig_verify(const secp256k1_context* ctx, const secp256k1_schnorrsig *sig, const unsigned char *msg32, const secp256k1_pubkey *pk); +extern "C" int secp256k1_schnorrsig_parse(const secp256k1_context* ctx, secp256k1_schnorrsig* sig, const unsigned char *in64); #include "musig.cpp" #endif diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 5d56635aa..520234da1 100755 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -15,9 +15,11 @@ #include "../secp256k1/include/secp256k1.h" -#include "../secp256k1/include/secp256k1_schnorrsig.h" +//#include "../secp256k1/include/secp256k1_schnorrsig.h" #include "../secp256k1/include/secp256k1_musig.h" +typedef struct { unsigned char data[64]; } secp256k1_schnorrsig; + #define MUSIG_PREVN 0 // for now, just use vout0 for the musig output #define MUSIG_TXFEE 10000 From d17ef9b3e264e7bac9cccc4d27de3b19ae7fc40d Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 02:28:36 -1100 Subject: [PATCH 236/390] ees --- src/cc/cclib.cpp | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index a83107234..484be6191 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -584,10 +584,11 @@ uint256 juint256(cJSON *obj) #else #include "sudoku.cpp" +#include "../secp256k1/include/secp256k1.h" +#include "../secp256k1/src/ecmult.h" /*#define USE_BASIC_CONFIG #define ENABLE_MODULE_MUSIG #include "../secp256k1/src/basic-config.h" -#include "../secp256k1/include/secp256k1.h" #include "../secp256k1/src/util.h" #include "../secp256k1/src/num_impl.h" @@ -602,12 +603,7 @@ uint256 juint256(cJSON *obj) #include "../secp256k1/src/eckey_impl.h" #include "../secp256k1/src/hash_impl.h" -struct secp256k1_context_struct { - secp256k1_ecmult_context ecmult_ctx; - secp256k1_ecmult_gen_context ecmult_gen_ctx; - secp256k1_callback illegal_callback; - secp256k1_callback error_callback; -}; + typedef int (secp256k1_ecmult_multi_callback)(secp256k1_scalar *sc, secp256k1_ge *pt, size_t idx, void *data); extern "C" void secp256k1_pubkey_save(secp256k1_pubkey* pubkey, secp256k1_ge* ge); @@ -623,6 +619,12 @@ return 0; \ } while(0)*/ //#include "../secp256k1/src/secp256k1.c" +struct secp256k1_context_struct { + secp256k1_ecmult_context ecmult_ctx; + secp256k1_ecmult_gen_context ecmult_gen_ctx; + secp256k1_callback illegal_callback; + secp256k1_callback error_callback; +}; extern "C" int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n); extern "C" int secp256k1_schnorrsig_verify(const secp256k1_context* ctx, const secp256k1_schnorrsig *sig, const unsigned char *msg32, const secp256k1_pubkey *pk); extern "C" int secp256k1_schnorrsig_parse(const secp256k1_context* ctx, secp256k1_schnorrsig* sig, const unsigned char *in64); From 7833fc5f4b1af8d19a49edb8dfd396da3ff2c995 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 02:29:47 -1100 Subject: [PATCH 237/390] Sss --- src/cc/cclib.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 484be6191..35a6362ec 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -584,12 +584,12 @@ uint256 juint256(cJSON *obj) #else #include "sudoku.cpp" -#include "../secp256k1/include/secp256k1.h" -#include "../secp256k1/src/ecmult.h" -/*#define USE_BASIC_CONFIG +#define USE_BASIC_CONFIG #define ENABLE_MODULE_MUSIG #include "../secp256k1/src/basic-config.h" +#include "../secp256k1/include/secp256k1.h" +/* #include "../secp256k1/src/util.h" #include "../secp256k1/src/num_impl.h" #include "../secp256k1/src/field_impl.h" From 7573d3f815cca5c5d08e9e8a56c9a9b3f41c6c93 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 02:31:15 -1100 Subject: [PATCH 238/390] Tes --- src/cc/cclib.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 35a6362ec..5681a380f 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -588,6 +588,7 @@ uint256 juint256(cJSON *obj) #define ENABLE_MODULE_MUSIG #include "../secp256k1/src/basic-config.h" #include "../secp256k1/include/secp256k1.h" +#include "../secp256k1/include/ecmult.h" /* #include "../secp256k1/src/util.h" From aec159bdc0bcbceb80f2ccb4d4e3bc479854cb2d Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 02:31:47 -1100 Subject: [PATCH 239/390] Src --- src/cc/cclib.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 5681a380f..8a96a81bf 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -588,7 +588,7 @@ uint256 juint256(cJSON *obj) #define ENABLE_MODULE_MUSIG #include "../secp256k1/src/basic-config.h" #include "../secp256k1/include/secp256k1.h" -#include "../secp256k1/include/ecmult.h" +#include "../secp256k1/src/ecmult.h" /* #include "../secp256k1/src/util.h" From 3106e5f0a83784a4dff7128920acfc2f44eba786 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 02:33:11 -1100 Subject: [PATCH 240/390] typedef struct { unsigned char data[64]; } secp256k1_schnorrsig; --- src/cc/cclib.cpp | 3 +++ src/cc/musig.cpp | 1 - 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 8a96a81bf..76d1dfa39 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -589,6 +589,9 @@ uint256 juint256(cJSON *obj) #include "../secp256k1/src/basic-config.h" #include "../secp256k1/include/secp256k1.h" #include "../secp256k1/src/ecmult.h" +#include "../secp256k1/src/ecmult_gen.h" + +typedef struct { unsigned char data[64]; } secp256k1_schnorrsig; /* #include "../secp256k1/src/util.h" diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 520234da1..318cb7664 100755 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -18,7 +18,6 @@ //#include "../secp256k1/include/secp256k1_schnorrsig.h" #include "../secp256k1/include/secp256k1_musig.h" -typedef struct { unsigned char data[64]; } secp256k1_schnorrsig; #define MUSIG_PREVN 0 // for now, just use vout0 for the musig output #define MUSIG_TXFEE 10000 From 51ae3da5ec6a575c8d7b003f62e72af65a03949a Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 02:38:45 -1100 Subject: [PATCH 241/390] #ifdef __cplusplus --- src/secp256k1/src/ecmult.h | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/secp256k1/src/ecmult.h b/src/secp256k1/src/ecmult.h index fbcf6a445..3ed2e435a 100644 --- a/src/secp256k1/src/ecmult.h +++ b/src/secp256k1/src/ecmult.h @@ -78,6 +78,10 @@ typedef int (secp256k1_ecmult_multi_callback)(secp256k1_scalar *sc, secp256k1_ge * 0 if there is not enough scratch space for a single point or * callback returns 0 */ + +#ifdef __cplusplus +extern "C" +#endif int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n); #endif /* SECP256K1_ECMULT_H */ From 4da533ffc5cb53f0ea28010601e09ec8effc46c4 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 02:42:25 -1100 Subject: [PATCH 242/390] Test --- src/cc/cclib.cpp | 1 + src/secp256k1/src/ecmult_impl.h | 1 + 2 files changed, 2 insertions(+) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 76d1dfa39..5d321bdae 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -629,6 +629,7 @@ struct secp256k1_context_struct { secp256k1_callback illegal_callback; secp256k1_callback error_callback; }; + extern "C" int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n); extern "C" int secp256k1_schnorrsig_verify(const secp256k1_context* ctx, const secp256k1_schnorrsig *sig, const unsigned char *msg32, const secp256k1_pubkey *pk); extern "C" int secp256k1_schnorrsig_parse(const secp256k1_context* ctx, secp256k1_schnorrsig* sig, const unsigned char *in64); diff --git a/src/secp256k1/src/ecmult_impl.h b/src/secp256k1/src/ecmult_impl.h index 116a9f154..6fd705ef4 100644 --- a/src/secp256k1/src/ecmult_impl.h +++ b/src/secp256k1/src/ecmult_impl.h @@ -1522,6 +1522,7 @@ static size_t secp256k1_pippenger_max_points(secp256k1_scratch *scratch) { } typedef int (*secp256k1_ecmult_multi_func)(const secp256k1_ecmult_context*, secp256k1_scratch*, secp256k1_gej*, const secp256k1_scalar*, secp256k1_ecmult_multi_callback cb, void*, size_t); + int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n) { size_t i; From b09b0261aca1812eef070b5046aad2b4cbefebf7 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 02:45:02 -1100 Subject: [PATCH 243/390] Test --- src/secp256k1/src/ecmult_impl.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/secp256k1/src/ecmult_impl.h b/src/secp256k1/src/ecmult_impl.h index 6fd705ef4..bea64ebcd 100644 --- a/src/secp256k1/src/ecmult_impl.h +++ b/src/secp256k1/src/ecmult_impl.h @@ -1525,7 +1525,7 @@ typedef int (*secp256k1_ecmult_multi_func)(const secp256k1_ecmult_context*, secp int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n) { size_t i; - + xxx int (*f)(const secp256k1_ecmult_context*, secp256k1_scratch*, secp256k1_gej*, const secp256k1_scalar*, secp256k1_ecmult_multi_callback cb, void*, size_t, size_t); size_t max_points; size_t n_batches; From c44e7ae038a9b462b83f69dbb2f31d9fe1b5e97d Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 02:48:05 -1100 Subject: [PATCH 244/390] Fix --- src/secp256k1/src/ecmult_impl.h | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/secp256k1/src/ecmult_impl.h b/src/secp256k1/src/ecmult_impl.h index bea64ebcd..b761304cf 100644 --- a/src/secp256k1/src/ecmult_impl.h +++ b/src/secp256k1/src/ecmult_impl.h @@ -1,4 +1,4 @@ -#ifdef ENABLE_MODULE_MUSIG +#ifndef ENABLE_MODULE_MUSIG /********************************************************************** @@ -1525,7 +1525,6 @@ typedef int (*secp256k1_ecmult_multi_func)(const secp256k1_ecmult_context*, secp int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n) { size_t i; - xxx int (*f)(const secp256k1_ecmult_context*, secp256k1_scratch*, secp256k1_gej*, const secp256k1_scalar*, secp256k1_ecmult_multi_callback cb, void*, size_t, size_t); size_t max_points; size_t n_batches; From ccd1b516294fedc391e29b763aa640e72f58fdb0 Mon Sep 17 00:00:00 2001 From: ca333 Date: Thu, 21 Feb 2019 15:36:02 +0100 Subject: [PATCH 245/390] resolve conflict --- src/Makefile.am | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/src/Makefile.am b/src/Makefile.am index e9d41a510..22668c91f 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -572,16 +572,14 @@ komodod_LDADD += \ $(LIBVERUS_CRYPTO) \ $(LIBVERUS_PORTABLE_CRYPTO) \ $(LIBZCASH_LIBS) - + if TARGET_DARWIN -komodod_LDADD += libcc.dylib -endif -if TARGET_WINDOWS -komodod_LDADD += libcc.dll +komodod_LDADD += libcc.dylib $(LIBSECP256K1) else -komodod_LDADD += libcc.so +komodod_LDADD += libcc.so $(LIBSECP256K1) endif + if ENABLE_PROTON komodod_LDADD += $(LIBBITCOIN_PROTON) $(PROTON_LIBS) endif From a659c209e489adf22ec8cad02e016d3dd3c75731 Mon Sep 17 00:00:00 2001 From: blackjok3r Date: Thu, 21 Feb 2019 22:38:40 +0800 Subject: [PATCH 246/390] it builds --- src/cc/rogue/main.c | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index ca05226d3..93391d153 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -30,7 +30,7 @@ extern char Gametxidstr[67]; #define SATOSHIDEN ((uint64_t)100000000L) #define dstr(x) ((double)(x) / SATOSHIDEN) #define KOMODO_ASSETCHAIN_MAXLEN 65 -char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN]; +char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN],IPADDRESS[100]; #ifndef _BITS256 #define _BITS256 @@ -583,7 +583,7 @@ char *curl_post(CURL **cHandlep,char *url,char *userpass,char *postfields,char * return(chunk.memory); } -uint16_t _komodo_userpass(char *username,char *password,FILE *fp) +uint16_t _komodo_userpass(char *username, char *password, char *ipaddress, FILE *fp) { char *rpcuser,*rpcpassword,*str,line[8192]; uint16_t port = 0; rpcuser = rpcpassword = 0; @@ -602,6 +602,10 @@ uint16_t _komodo_userpass(char *username,char *password,FILE *fp) port = atoi(parse_conf_line(str,(char *)"rpcport")); //fprintf(stderr,"rpcport.%u in file\n",port); } + else if ( (str= strstr(line,(char *)"ipaddress")) != 0 ) + { + ipaddress = parse_conf_line(str,(char *)"ipaddress"); + } } if ( rpcuser != 0 && rpcpassword != 0 ) { @@ -653,7 +657,7 @@ uint16_t _komodo_userpass(char *username,char *password,FILE *fp) //printf("test.(%s) -> [%s] statename.(%s) %s\n",test,ASSETCHAINS_SYMBOL,symbol,fname); }*/ -uint16_t komodo_userpass(char *userpass,char *symbol) +uint16_t komodo_userpass(char *userpass,char *symbol,char *ipaddress) { FILE *fp; uint16_t port = 0; char fname[512],username[512],password[512],confname[KOMODO_ASSETCHAIN_MAXLEN]; userpass[0] = 0; @@ -669,7 +673,7 @@ uint16_t komodo_userpass(char *userpass,char *symbol) //komodo_statefname(fname,symbol,confname); if ( (fp= fopen(confname,"rb")) != 0 ) { - port = _komodo_userpass(username,password,fp); + port = _komodo_userpass(username,password,ipaddress,fp); sprintf(userpass,"%s:%s",username,password); if ( strcmp(symbol,ASSETCHAINS_SYMBOL) == 0 ) strcpy(USERPASS,userpass); @@ -688,7 +692,7 @@ char *komodo_issuemethod(char *userpass,char *method,char *params,uint16_t port) params = (char *)"[]"; if ( strlen(params) < sizeof(postdata)-128 ) { - sprintf(url,(char *)"http://127.0.0.1:%u",port); + sprintf(url,(char *)"http://%s:%u",IPADDRESS,port); sprintf(postdata,"{\"method\":\"%s\",\"params\":%s}",method,params); //printf("[%s] (%s) postdata.(%s) params.(%s) USERPASS.(%s)\n",ASSETCHAINS_SYMBOL,url,postdata,params,USERPASS); retstr2 = bitcoind_RPC(&retstr,(char *)"debug",url,userpass,method,params); @@ -793,7 +797,7 @@ int main(int argc, char **argv, char **envp) ASSETCHAINS_SYMBOL[j++] = toupper(c); } ASSETCHAINS_SYMBOL[j++] = 0; - ROGUE_PORT = komodo_userpass(userpass,ASSETCHAINS_SYMBOL); + ROGUE_PORT = komodo_userpass(userpass,ASSETCHAINS_SYMBOL,IPADDRESS); printf("ASSETCHAINS_SYMBOL.(%s) port.%u (%s)\n",ASSETCHAINS_SYMBOL,ROGUE_PORT,USERPASS); sleep(1); if ( argc == 2 && (fp=fopen(argv[1],"rb")) == 0 ) { @@ -813,5 +817,3 @@ int main(int argc, char **argv, char **envp) return(rogue(argc,argv,envp)); } } - - From f6d693768f1f733dbdb18c02a1b904c23cfcb5f5 Mon Sep 17 00:00:00 2001 From: ca333 Date: Thu, 21 Feb 2019 15:40:26 +0100 Subject: [PATCH 247/390] winify Makefile --- src/Makefile.am | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/Makefile.am b/src/Makefile.am index 22668c91f..fa2c17b5d 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -575,11 +575,13 @@ komodod_LDADD += \ if TARGET_DARWIN komodod_LDADD += libcc.dylib $(LIBSECP256K1) +endif +if TARGET_WINDOWS +komodod_LDADD += libcc.dll $(LIBSECP256K1) else komodod_LDADD += libcc.so $(LIBSECP256K1) endif - if ENABLE_PROTON komodod_LDADD += $(LIBBITCOIN_PROTON) $(PROTON_LIBS) endif From 0816deb0b0f328e0ded5ee722b088d359c97956a Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 04:04:18 -1100 Subject: [PATCH 248/390] Musig combine rpc --- src/cc/musig.cpp | 37 ++++++++++++++++++++++++++++++++++--- 1 file changed, 34 insertions(+), 3 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 318cb7664..865ec311c 100755 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -110,9 +110,40 @@ UniValue musig_calcmsg(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue musig_combine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); - result.push_back(Pair("result","success")); - return(result); + static secp256k1_context *ctx; secp256k1_scratch_space scratch; + size_t clen = CPubKey::PUBLIC_KEY_SIZE; + UniValue result(UniValue::VOBJ); int32_t i,n; uint8_t pkhash[32]; char *hexstr,str[67]; secp256k1_pubkey combined_pk,spk; std::vector pubkeys; + if ( ctx == 0 ) + ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); + if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) + { + for (i=0; i 0 ) + pubkeys.push_back(spk); + else return(cclib_error(result,"error parsing pk")); + } else return(cclib_error(result,"all pubkeys must be 33 bytes hexdata")); + } + if ( secp256k1_musig_pubkey_combine(ctx,&scratch,&combined_pk,pkhash,&pubkeys[0],n) > 0 ) + { + if ( secp256k1_ec_pubkey_serialize(ctx,(uint8_t *)pk.begin(),&clen,&combined_pk,SECP256K1_EC_COMPRESSED) > 0 && clen == 33 ) + { + for (i=0; i<32; i++) + sprintf(&str[i<<1],"%02x",pkhash[i]); + str[64] = 0; + result.push_back(Pair("pkhash",str)); + + for (i=0; i<33; i++) + sprintf(&str[i<<1],"%02x",((uint8_t *)pk.begin())[i]); + str[66] = 0; + result.push_back(Pair("combined_pk",str)); + result.push_back(Pair("result","success")); + } else return(cclib_error(result,"error serializeing combined_pk")); + } else return(cclib_error(result,"error combining pukbeys")); + } else return(cclib_error(result,"need pubkeys params")); } UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) From a96f0c861eae0bc5df1d327d8ddbc73a10abe5e9 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 04:06:22 -1100 Subject: [PATCH 249/390] Declare pk --- src/cc/musig.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 865ec311c..057307fae 100755 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -112,7 +112,7 @@ UniValue musig_combine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { static secp256k1_context *ctx; secp256k1_scratch_space scratch; size_t clen = CPubKey::PUBLIC_KEY_SIZE; - UniValue result(UniValue::VOBJ); int32_t i,n; uint8_t pkhash[32]; char *hexstr,str[67]; secp256k1_pubkey combined_pk,spk; std::vector pubkeys; + UniValue result(UniValue::VOBJ); CPubKey pk; int32_t i,n; uint8_t pkhash[32]; char *hexstr,str[67]; secp256k1_pubkey combined_pk,spk; std::vector pubkeys; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) From 556a45f37b87d7fe7f9ce2445a7044964dee4f81 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 04:08:41 -1100 Subject: [PATCH 250/390] Extern C --- src/cc/cclib.cpp | 19 ------------------- src/cc/musig.cpp | 22 +++++++++++++++++++++- 2 files changed, 21 insertions(+), 20 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 5d321bdae..bfd57e61d 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -584,14 +584,6 @@ uint256 juint256(cJSON *obj) #else #include "sudoku.cpp" -#define USE_BASIC_CONFIG -#define ENABLE_MODULE_MUSIG -#include "../secp256k1/src/basic-config.h" -#include "../secp256k1/include/secp256k1.h" -#include "../secp256k1/src/ecmult.h" -#include "../secp256k1/src/ecmult_gen.h" - -typedef struct { unsigned char data[64]; } secp256k1_schnorrsig; /* #include "../secp256k1/src/util.h" @@ -623,17 +615,6 @@ return 0; \ } while(0)*/ //#include "../secp256k1/src/secp256k1.c" -struct secp256k1_context_struct { - secp256k1_ecmult_context ecmult_ctx; - secp256k1_ecmult_gen_context ecmult_gen_ctx; - secp256k1_callback illegal_callback; - secp256k1_callback error_callback; -}; - -extern "C" int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n); -extern "C" int secp256k1_schnorrsig_verify(const secp256k1_context* ctx, const secp256k1_schnorrsig *sig, const unsigned char *msg32, const secp256k1_pubkey *pk); -extern "C" int secp256k1_schnorrsig_parse(const secp256k1_context* ctx, secp256k1_schnorrsig* sig, const unsigned char *in64); - #include "musig.cpp" #endif diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 057307fae..23c14bb8e 100755 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -13,8 +13,28 @@ * * ******************************************************************************/ - +#define USE_BASIC_CONFIG +#define ENABLE_MODULE_MUSIG +#include "../secp256k1/src/basic-config.h" #include "../secp256k1/include/secp256k1.h" +#include "../secp256k1/src/ecmult.h" +#include "../secp256k1/src/ecmult_gen.h" + +typedef struct { unsigned char data[64]; } secp256k1_schnorrsig; +struct secp256k1_context_struct { + secp256k1_ecmult_context ecmult_ctx; + secp256k1_ecmult_gen_context ecmult_gen_ctx; + secp256k1_callback illegal_callback; + secp256k1_callback error_callback; +}; + +extern "C" int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n); +extern "C" int secp256k1_schnorrsig_verify(const secp256k1_context* ctx, const secp256k1_schnorrsig *sig, const unsigned char *msg32, const secp256k1_pubkey *pk); +extern "C" int secp256k1_schnorrsig_parse(const secp256k1_context* ctx, secp256k1_schnorrsig* sig, const unsigned char *in64); +extern "C" int secp256k1_musig_pubkey_combine(const secp256k1_context* ctx, secp256k1_scratch_space *scratch, secp256k1_pubkey *combined_pk, unsigned char *pk_hash32, const secp256k1_pubkey *pubkeys, size_t n_pubkeys); + + +//#include "../secp256k1/include/secp256k1.h" //#include "../secp256k1/include/secp256k1_schnorrsig.h" #include "../secp256k1/include/secp256k1_musig.h" From c96ca4eab9a842e001edeedb2ad6e97a687d693c Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 04:12:42 -1100 Subject: [PATCH 251/390] Test --- src/cc/musig.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 23c14bb8e..ee4c3400e 100755 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -135,6 +135,7 @@ UniValue musig_combine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue result(UniValue::VOBJ); CPubKey pk; int32_t i,n; uint8_t pkhash[32]; char *hexstr,str[67]; secp256k1_pubkey combined_pk,spk; std::vector pubkeys; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); + fprintf(stderr,"args.(%s)\n",jprint(params,0)); if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) { for (i=0; i Date: Thu, 21 Feb 2019 04:17:20 -1100 Subject: [PATCH 252/390] Test --- src/cc/musig.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index ee4c3400e..0b8600de4 100755 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -135,9 +135,9 @@ UniValue musig_combine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue result(UniValue::VOBJ); CPubKey pk; int32_t i,n; uint8_t pkhash[32]; char *hexstr,str[67]; secp256k1_pubkey combined_pk,spk; std::vector pubkeys; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); - fprintf(stderr,"args.(%s)\n",jprint(params,0)); if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) { + fprintf(stderr,"n.%d args.(%s)\n",jprint(params,0)); for (i=0; i Date: Thu, 21 Feb 2019 04:18:37 -1100 Subject: [PATCH 253/390] N, --- src/cc/musig.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 0b8600de4..0c2ce2d15 100755 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -137,7 +137,7 @@ UniValue musig_combine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) { - fprintf(stderr,"n.%d args.(%s)\n",jprint(params,0)); + fprintf(stderr,"n.%d args.(%s)\n",n,jprint(params,0)); for (i=0; i Date: Thu, 21 Feb 2019 04:20:26 -1100 Subject: [PATCH 254/390] -scratch --- src/cc/musig.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 0c2ce2d15..0e7f374db 100755 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -130,7 +130,7 @@ UniValue musig_calcmsg(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue musig_combine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - static secp256k1_context *ctx; secp256k1_scratch_space scratch; + static secp256k1_context *ctx; size_t clen = CPubKey::PUBLIC_KEY_SIZE; UniValue result(UniValue::VOBJ); CPubKey pk; int32_t i,n; uint8_t pkhash[32]; char *hexstr,str[67]; secp256k1_pubkey combined_pk,spk; std::vector pubkeys; if ( ctx == 0 ) @@ -148,7 +148,7 @@ UniValue musig_combine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) else return(cclib_error(result,"error parsing pk")); } else return(cclib_error(result,"all pubkeys must be 33 bytes hexdata")); } - if ( secp256k1_musig_pubkey_combine(ctx,&scratch,&combined_pk,pkhash,&pubkeys[0],n) > 0 ) + if ( secp256k1_musig_pubkey_combine(ctx,NULL,&combined_pk,pkhash,&pubkeys[0],n) > 0 ) { if ( secp256k1_ec_pubkey_serialize(ctx,(uint8_t *)pk.begin(),&clen,&combined_pk,SECP256K1_EC_COMPRESSED) > 0 && clen == 33 ) { From d32c12e0bbfb75f620b80ff84e8affbd033694f0 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 04:24:21 -1100 Subject: [PATCH 255/390] Return! --- src/cc/musig.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 0e7f374db..1a664f4b4 100755 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -162,6 +162,7 @@ UniValue musig_combine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) str[66] = 0; result.push_back(Pair("combined_pk",str)); result.push_back(Pair("result","success")); + return(result); } else return(cclib_error(result,"error serializeing combined_pk")); } else return(cclib_error(result,"error combining pukbeys")); } else return(cclib_error(result,"need pubkeys params")); From c6b2a865e65c8bb54a54baafe1d2e3cb3fa064c7 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 04:33:06 -1100 Subject: [PATCH 256/390] Music usage example --- src/cc/musig.cpp | 49 ++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 47 insertions(+), 2 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 1a664f4b4..17c4d1368 100755 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -13,6 +13,52 @@ * * ******************************************************************************/ +/* first make a combined pk: +./c cclib combine 18 \"[%2202aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848%22,%22039433dc3749aece1bd568f374a45da3b0bc6856990d7da3cd175399577940a775%22]\" +{ + "pkhash": "5be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba", + "combined_pk": "032ddac56613cd0667b589bd7f32b665e2d2ce0247e337a5a0bca6c72e3d9d057b", + "result": "success" +} +*/ + +/* second, send 0.777 coins to the combined_pk + ./c cclib send 18 \"[%22032ddac56613cd0667b589bd7f32b665e2d2ce0247e337a5a0bca6c72e3d9d057b%22,0.777]\" + { + "hex": "0400008085202f8901bf7afcbbab7a5e1ba20c8010325e199305afa7d15b4bc86a589a512201d39924000000004847304402203e0cff8aaa831dd990afd979bbc0a648316f77407cb5e02780d18e0670f5172a0220283d5c52d0406b10c508cc2b19dd6dbe2420e7c5cf431a1d41072d0eec28edb901ffffffff03b0c2a10400000000302ea22c8020c71ddb3aac7f9b9e4bdacf032aaa8b8e4433c4ff9f8a43cebb9c1f5da96928a48103120c008203000401cca91e223700000000232102aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848ac0000000000000000266a24127821032ddac56613cd0667b589bd7f32b665e2d2ce0247e337a5a0bca6c72e3d9d057b00000000900000000000000000000000000000", + "txid": "cb5309ed249da95e2b5696eb763a8736e2fff1d14922ada737b931494ca3d2be", + "result": "success" + } + + { + "value": 0.77710000, + "valueZat": 77710000, + "n": 0, + "scriptPubKey": { + "asm": "a22c8020c71ddb3aac7f9b9e4bdacf032aaa8b8e4433c4ff9f8a43cebb9c1f5da96928a48103120c008203000401 OP_CHECKCRYPTOCONDITION", + "hex": "2ea22c8020c71ddb3aac7f9b9e4bdacf032aaa8b8e4433c4ff9f8a43cebb9c1f5da96928a48103120c008203000401cc", + "reqSigs": 1, + "type": "cryptocondition", + "addresses": [ + "RKWS7jxyjPX9iaJttk8iMKf1AumanKypez" + ] + } + change script: 2102aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848ac + + sendtxid: cb5309ed249da95e2b5696eb763a8736e2fff1d14922ada737b931494ca3d2be + + broadcast sendtxid and wait for it to be confirmed. then get the msg we need to sign: + + ./c cclib calcmsg 18 \"[%22cb5309ed249da95e2b5696eb763a8736e2fff1d14922ada737b931494ca3d2be%22,%222102aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848ac%22]\" + + { + "result": "success", + "msg": "63b799913d4c9487f321b32d6ae8614f653f38e0b50d4df4bc1d36339ea18485" + } + +*/ + + #define USE_BASIC_CONFIG #define ENABLE_MODULE_MUSIG #include "../secp256k1/src/basic-config.h" @@ -82,7 +128,6 @@ int32_t musig_msghash(uint8_t *msg,uint256 prevhash,int32_t prevn,CTxOut vout,CP { CScript data; uint256 hash; int32_t len = 0; data << E_MARSHAL(ss << prevhash << prevn << vout << pk); -fprintf(stderr,"data size %d\n",(int32_t)data.size()); hash = Hash(data.begin(),data.end()); memcpy(msg,&hash,sizeof(hash)); return(0); @@ -137,7 +182,7 @@ UniValue musig_combine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) { - fprintf(stderr,"n.%d args.(%s)\n",n,jprint(params,0)); + //fprintf(stderr,"n.%d args.(%s)\n",n,jprint(params,0)); for (i=0; i Date: Thu, 21 Feb 2019 16:35:00 +0100 Subject: [PATCH 257/390] add WIN makefile target: rogue.exe --- src/cc/rogue/Makefile_win | 222 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 222 insertions(+) create mode 100644 src/cc/rogue/Makefile_win diff --git a/src/cc/rogue/Makefile_win b/src/cc/rogue/Makefile_win new file mode 100644 index 000000000..dbc900e48 --- /dev/null +++ b/src/cc/rogue/Makefile_win @@ -0,0 +1,222 @@ +############################################################################### +# +# Makefile for rogue +# +# Rogue: Exploring the Dungeons of Doom +# Copyright (C) 1980-1983, 1985, 1999 Michael Toy, Ken Arnold and Glenn Wichman +# All rights reserved. +# +# See the file LICENSE.TXT for full copyright and licensing information. +# +############################################################################### + +############################################################################### +# Site configuration occurs beneath this comment +# Typically ./configure (autoconf tools) configures this section +# This section could be manually configured if autoconf/configure fails +############################################################################### + +DISTNAME=rogue5.4.4 +PACKAGE_TARNAME = rogue-5.4.4 +PROGRAM=rogue + +O=o + +#CC=gcc +CC = x86_64-w64-mingw32-gcc + +#CFLAGS=-O2 +CFLAGS= -g -O2 -I./ncurses/include + +#LIBS=-lcurses +LIBS = -L./ncurses/lib -lncursesw + +#RM=rm -f +RM = rm -f + +#GROFF=groff +GROFF = groff + +#NROFF=nroff +NROFF = nroff + +#TBL=tbl +TBL = tbl + +#COLCRT=colcrt +COLCRT = colcrt + +#SED=sed +SED = sed + +#SCOREFILE=rogue54.scr +SCOREFILE = rogue.scr + +#LOCKFILE=rogue54.lck +LOCKFILE = rogue.lck + +#GROUPOWNER=games +GROUPOWNER = + +#CPPFLAGS=-DHAVE_CONFIG_H +CPPFLAGS =-DHAVE_CONFIG_H + +#DISTFILE = $(PROGRAM) +DISTFILE = $(DISTNAME)-x86_64-w64-mingw32 + +INSTALL=./install-sh + +#INSTGROUP=-g games +INSTGROUP= +#INSTOWNER=-u root +INSTOWNER= + +CHGRP=chgrp + +MKDIR=mkdir + +TOUCH=touch + +RMDIR=rmdir + +CHMOD=chmod + +DESTDIR= + +prefix=/usr/local +exec_prefix=${prefix} +datarootdir=${prefix}/share +datadir=${datarootdir} +bindir=${exec_prefix}/bin +mandir=${datarootdir}/man +docdir=${datarootdir}/doc/${PACKAGE_TARNAME} +man6dir = $(mandir)/man6 + +############################################################################### +# Site configuration occurs above this comment +# It should not be necessary to change anything below this comment +############################################################################### + +HDRS = rogue.h extern.h score.h +OBJS1 = vers.$(O) extern.$(O) armor.$(O) chase.$(O) command.$(O) \ + daemon.$(O) daemons.$(O) fight.$(O) init.$(O) io.$(O) list.$(O) \ + mach_dep.$(O) rogue.$(O) mdport.$(O) misc.$(O) monsters.$(O) \ + move.$(O) new_level.$(O) +OBJS2 = options.$(O) pack.$(O) passages.$(O) potions.$(O) rings.$(O) \ + rip.$(O) rooms.$(O) save.$(O) scrolls.$(O) state.$(O) sticks.$(O) \ + things.$(O) weapons.$(O) wizard.$(O) xcrypt.$(O) +OBJS = main.$(O) $(OBJS1) $(OBJS2) +CFILES = vers.c extern.c armor.c chase.c command.c daemon.c \ + daemons.c fight.c init.c io.c list.c mach_dep.c \ + main.c mdport.c misc.c monsters.c move.c new_level.c \ + options.c pack.c passages.c potions.c rings.c rip.c \ + rooms.c save.c scrolls.c state.c sticks.c things.c \ + weapons.c wizard.c xcrypt.c +MISC_C = findpw.c scedit.c scmisc.c +DOCSRC = rogue.me.in rogue.6.in rogue.doc.in rogue.html.in rogue.cat.in +DOCS = $(PROGRAM).doc $(PROGRAM).html $(PROGRAM).cat $(PROGRAM).me \ + $(PROGRAM).6 +AFILES = configure Makefile.in configure.ac config.h.in config.sub config.guess \ + install-sh rogue.6.in rogue.me.in rogue.html.in rogue.doc.in rogue.cat.in +MISC = Makefile.std LICENSE.TXT rogue54.sln rogue54.vcproj rogue.spec \ + rogue.png rogue.desktop + +.SUFFIXES: .obj + +.c.obj: + $(CC) $(CFLAGS) $(CPPFLAGS) /c $*.c + +.c.o: + $(CC) $(CFLAGS) $(CPPFLAGS) -c $*.c + +#$(RM) rogue.so ; $(CC) -shared -o rogue.so cursesd.c $(OBJS1) $(OBJS2); $(CC) $(CFLAGS) $(LDFLAGS) $(OBJS) $(LIBS) -o $@ + +$(PROGRAM): $(HDRS) $(OBJS) + $(CC) $(CFLAGS) $(LDFLAGS) $(OBJS) $(LIBS) -o $@.exe + +clean: + $(RM) $(OBJS1); $(RM) main.$(O) ; $(RM) rogue.so + $(RM) $(OBJS2) + $(RM) core a.exe a.out a.exe.stackdump $(PROGRAM) $(PROGRAM).exe + $(RM) $(PROGRAM).tar $(PROGRAM).tar.gz $(PROGRAM).zip + $(RM) $(DISTNAME)/* + -rmdir $(DISTNAME) + +maintainer-clean: + $(RM) config.h + $(RM) Makefile + $(RM) config.status + $(RM) -r autom4te.cache + $(RM) config.log + $(RM) $(PROGRAM).scr $(PROGRAM).lck + +stddocs: + sed -e 's/rogue/rogue/' -e 's/rogue.scr/rogue.scr/' rogue.6.in > rogue.6 + sed -e 's/rogue/rogue/' -e 's/rogue.scr/rogue.scr/' rogue.me.in > rogue.me + sed -e 's/rogue/rogue/' -e 's/rogue.scr/rogue.scr/' rogue.html.in > rogue,html + sed -e 's/rogue/rogue/' -e 's/rogue.scr/rogue.scr/' rogue.doc.in > rogue.doc + sed -e 's/rogue/rogue/' -e 's/rogue.scr/rogue.scr/' rogue.cat.in > rogue.cat + +dist.src: + $(MAKE) $(MAKEFILE) clean + mkdir $(DISTNAME) + cp $(CFILES) $(HDRS) $(MISC) $(AFILES) $(DISTNAME) + tar cf $(DISTNAME)-src.tar $(DISTNAME) + gzip -f $(DISTNAME)-src.tar + rm -fr $(DISTNAME) + +findpw: findpw.c xcrypt.o mdport.o xcrypt.o + $(CC) -s -o findpw findpw.c xcrypt.o mdport.o -lcurses + +scedit: scedit.o scmisc.o vers.o mdport.o xcrypt.o + $(CC) -s -o scedit vers.o scedit.o scmisc.o mdport.o xcrypt.o -lcurses + +scmisc.o scedit.o: + $(CC) -O -c $(SF) $*.c + +$(PROGRAM).doc: rogue.me + if test "x$(GROFF)" != "x" -a "x$(SED)" != "x" ; then \ + $(GROFF) -P-c -t -me -Tascii rogue.me | $(SED) -e 's/.\x08//g' > $(PROGRAM).doc ;\ + elif test "x$(NROFF)" != "x" -a "x$(TBL)" != "x" -a "x$(COLCRT)" != "x" ; then \ + tbl rogue.me | $(NROFF) -me | colcrt - > $(PROGRAM).doc ;\ + fi + +$(PROGRAM).cat: rogue.6 + if test "x$(GROFF)" != "x" -a "x$(SED)" != "x" ; then \ + $(GROFF) -Tascii -man rogue.6 | $(SED) -e 's/.\x08//g' > $(PROGRAM).cat ;\ + elif test "x$(NROFF)" != "x" -a "x$(TBL)" != "x" -a "x$(COLCRT)" != "x" ; then \ + $(NROFF) -man rogue.6 | $(COLCRT) - > $(PROGRAM).cat ;\ + fi + +dist: clean $(PROGRAM) + tar cf $(DISTFILE).tar $(PROGRAM) LICENSE.TXT $(DOCS) + gzip -f $(DISTFILE).tar + +install: $(PROGRAM) + -$(TOUCH) test + -if test ! -f $(DESTDIR)$(SCOREFILE) ; then $(INSTALL) -m 0664 test $(DESTDIR)$(SCOREFILE) ; fi + -$(INSTALL) -m 0755 $(PROGRAM) $(DESTDIR)$(bindir)/$(PROGRAM) + -if test "x$(GROUPOWNER)" != "x" ; then \ + $(CHGRP) $(GROUPOWNER) $(DESTDIR)$(SCOREFILE) ; \ + $(CHGRP) $(GROUPOWNER) $(DESTDIR)$(bindir)/$(PROGRAM) ; \ + $(CHMOD) 02755 $(DESTDIR)$(bindir)/$(PROGRAM) ; \ + $(CHMOD) 0464 $(DESTDIR)$(SCOREFILE) ; \ + fi + -if test -d $(man6dir) ; then $(INSTALL) -m 0644 rogue.6 $(DESTDIR)$(man6dir)/$(PROGRAM).6 ; fi + -if test ! -d $(man6dir) ; then $(INSTALL) -m 0644 rogue.6 $(DESTDIR)$(mandir)/$(PROGRAM).6 ; fi + -$(INSTALL) -m 0644 rogue.doc $(DESTDIR)$(docdir)/$(PROGRAM).doc + -$(INSTALL) -m 0644 rogue.html $(DESTDIR)$(docdir)/$(PROGRAM).html + -$(INSTALL) -m 0644 rogue.cat $(DESTDIR)$(docdir)/$(PROGRAM).cat + -$(INSTALL) -m 0644 LICENSE.TXT $(DESTDIR)$(docdir)/LICENSE.TXT + -$(INSTALL) -m 0644 rogue.me $(DESTDIR)$(docdir)/$(PROGRAM).me + -if test ! -f $(DESTDIR)$(LOCKFILE) ; then $(INSTALL) -m 0666 test $(DESTDIR)$(LOCKFILE) ; $(RM) $(DESTDIR)$(LOCKFILE) ; fi + -$(RM) test + +uninstall: + -$(RM) $(DESTDIR)$(bindir)/$(PROGRAM) + -$(RM) $(DESTDIR)$(man6dir)/$(PROGRAM).6 + -$(RM) $(DESTDIR)$(docdir)$(PROGRAM)/$(PROGRAM).doc + -$(RM) $(DESTDIR)$(LOCKFILE) + -$(RMDIR) $(DESTDIR)$(docdir)$(PROGRAM) + +reinstall: uninstall install From e8a72377f732410718b5e4b912270a9725e2a943 Mon Sep 17 00:00:00 2001 From: ca333 Date: Thu, 21 Feb 2019 16:36:12 +0100 Subject: [PATCH 258/390] WINify makerogue modify rogue game build --- src/cc/makerogue | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/src/cc/makerogue b/src/cc/makerogue index a38eab6a4..3068fa38e 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -1,7 +1,26 @@ #!/bin/sh cd rogue; -./configure -make; cd .. + +if [ "$HOST" = "x86_64-w64-mingw32" ]; then + echo building rogue.exe... + if make -f Makefile_win "$@"; then + echo rogue.exe build SUCCESSFUL + cd .. + else + echo rogue.exe build FAILED + exit 1 + fi +else + echo building rogue... + ./configure + if make "$@"; then + echo rogue build SUCCESSFUL + cd .. + else + echo rogue build FAILED + exit 1 + fi +fi if make -f Makefile_rogue "$@"; then echo ROGUE BUILD SUCCESSFUL From cfcde22a1e0a0ce80e4c0e365ba53282e79bb920 Mon Sep 17 00:00:00 2001 From: ca333 Date: Thu, 21 Feb 2019 17:48:52 +0100 Subject: [PATCH 259/390] add ncurses for rogue.exe --- src/cc/makerogue | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/cc/makerogue b/src/cc/makerogue index 3068fa38e..ff175c586 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -3,6 +3,10 @@ cd rogue; if [ "$HOST" = "x86_64-w64-mingw32" ]; then echo building rogue.exe... + mkdir ncurses && cd ncurses + wget https://invisible-island.net/datafiles/release/mingw32.zip + unzip mingw32.zip && delete mingw32.zip + cd .. if make -f Makefile_win "$@"; then echo rogue.exe build SUCCESSFUL cd .. From 7453b21b6da2b0f7ecc5bac28832cfb3ccda88c7 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 06:01:19 -1100 Subject: [PATCH 260/390] Comments --- src/cc/musig.cpp | 151 ++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 149 insertions(+), 2 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 17c4d1368..ec7f5e788 100755 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -217,6 +217,37 @@ UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { UniValue result(UniValue::VOBJ); result.push_back(Pair("result","success")); + /** Initializes a signing session for a signer + * + * Returns: 1: session is successfully initialized + * 0: session could not be initialized: secret key or secret nonce overflow + * Args: ctx: pointer to a context object, initialized for signing (cannot + * be NULL) + * Out: session: the session structure to initialize (cannot be NULL) + * signers: an array of signers' data to be initialized. Array length must + * equal to `n_signers` (cannot be NULL) + * nonce_commitment32: filled with a 32-byte commitment to the generated nonce + * (cannot be NULL) + * In: session_id32: a *unique* 32-byte ID to assign to this session (cannot be + * NULL). If a non-unique session_id32 was given then a partial + * signature will LEAK THE SECRET KEY. + * msg32: the 32-byte message to be signed. Shouldn't be NULL unless you + * require sharing public nonces before the message is known + * because it reduces nonce misuse resistance. If NULL, must be + * set with `musig_session_set_msg` before signing and verifying. + * combined_pk: the combined public key of all signers (cannot be NULL) + * pk_hash32: the 32-byte hash of the signers' individual keys (cannot be + * NULL) + * n_signers: length of signers array. Number of signers participating in + * the MuSig. Must be greater than 0 and at most 2^32 - 1. + * my_index: index of this signer in the signers array + * seckey: the signer's 32-byte secret key (cannot be NULL) + */ + //if (!secp256k1_musig_session_initialize(ctx, &musig_session[i], signer_data[i], nonce_commitment[i], session_id32, msg32, &combined_pk, pk_hash, N_SIGNERS, i, seckeys[i])) + //return 0; + // randombytes_buf(buf, num); + + //nonce_commitment_ptr[i] = &nonce_commitment[i][0]; return(result); } @@ -224,6 +255,25 @@ UniValue musig_commit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { UniValue result(UniValue::VOBJ); result.push_back(Pair("result","success")); + /** Gets the signer's public nonce given a list of all signers' data with commitments + * + * Returns: 1: public nonce is written in nonce + * 0: signer data is missing commitments or session isn't initialized + * for signing + * Args: ctx: pointer to a context object (cannot be NULL) + * session: the signing session to get the nonce from (cannot be NULL) + * signers: an array of signers' data initialized with + * `musig_session_initialize`. Array length must equal to + * `n_commitments` (cannot be NULL) + * Out: nonce: the nonce (cannot be NULL) + * In: commitments: array of 32-byte nonce commitments (cannot be NULL) + * n_commitments: the length of commitments and signers array. Must be the total + * number of signers participating in the MuSig. + */ + // Set nonce commitments in the signer data and get the own public nonce + //if (!secp256k1_musig_session_get_public_nonce(ctx, &musig_session[i], signer_data[i], &nonce[i], nonce_commitment_ptr, N_SIGNERS)) + // return 0; + return(result); } @@ -231,13 +281,69 @@ UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { UniValue result(UniValue::VOBJ); result.push_back(Pair("result","success")); - return(result); + /** Checks a signer's public nonce against a commitment to said nonce, and update + * data structure if they match + * + * Returns: 1: commitment was valid, data structure updated + * 0: commitment was invalid, nothing happened + * Args: ctx: pointer to a context object (cannot be NULL) + * signer: pointer to the signer data to update (cannot be NULL). Must have + * been used with `musig_session_get_public_nonce` or initialized + * with `musig_session_initialize_verifier`. + * In: nonce: signer's alleged public nonce (cannot be NULL) + */ + //if (!secp256k1_musig_set_nonce(ctx, &signer_data[i][j], &nonce[j])) { + + + /** Updates a session with the combined public nonce of all signers. The combined + * public nonce is the sum of every signer's public nonce. + * + * Returns: 1: nonces are successfully combined + * 0: a signer's nonce is missing + * Args: ctx: pointer to a context object (cannot be NULL) + * session: session to update with the combined public nonce (cannot be + * NULL) + * signers: an array of signers' data, which must have had public nonces + * set with `musig_set_nonce`. Array length must equal to `n_signers` + * (cannot be NULL) + * n_signers: the length of the signers array. Must be the total number of + * signers participating in the MuSig. + * Out: nonce_is_negated: a pointer to an integer that indicates if the combined + * public nonce had to be negated. + * adaptor: point to add to the combined public nonce. If NULL, nothing is + * added to the combined nonce. + */ + // after all nonces: if (!secp256k1_musig_session_combine_nonces(ctx, &musig_session[i], signer_data[i], N_SIGNERS, NULL, NULL)) { + return(result); } UniValue musig_partialsign(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { UniValue result(UniValue::VOBJ); result.push_back(Pair("result","success")); + /** Produces a partial signature + * + * Returns: 1: partial signature constructed + * 0: session in incorrect or inconsistent state + * Args: ctx: pointer to a context object (cannot be NULL) + * session: active signing session for which the combined nonce has been + * computed (cannot be NULL) + * Out: partial_sig: partial signature (cannot be NULL) + */ + //if (!secp256k1_musig_partial_sign(ctx, &musig_session[i], &partial_sig[i])) { + /** Parse and verify a MuSig partial signature. + * + * Returns: 1 when the signature could be parsed, 0 otherwise. + * Args: ctx: a secp256k1 context object + * Out: sig: pointer to a signature object + * In: in32: pointer to the 32-byte signature to be parsed + * + * After the call, sig will always be initialized. If parsing failed or the + * encoded numbers are out of range, signature verification with it is + * guaranteed to fail for every message and public key. + */ + //SECP256K1_API int secp256k1_musig_partial_signature_parse( + return(result); } @@ -245,13 +351,54 @@ UniValue musig_sigcombine(uint64_t txfee,struct CCcontract_info *cp,cJSON *param { UniValue result(UniValue::VOBJ); result.push_back(Pair("result","success")); - return(result); + /** Checks that an individual partial signature verifies + * + * This function is essential when using protocols with adaptor signatures. + * However, it is not essential for regular MuSig's, in the sense that if any + * partial signatures does not verify, the full signature will also not verify, so the + * problem will be caught. But this function allows determining the specific party + * who produced an invalid signature, so that signing can be restarted without them. + * + * Returns: 1: partial signature verifies + * 0: invalid signature or bad data + * Args: ctx: pointer to a context object (cannot be NULL) + * session: active session for which the combined nonce has been computed + * (cannot be NULL) + * signer: data for the signer who produced this signature (cannot be NULL) + * In: partial_sig: signature to verify (cannot be NULL) + * pubkey: public key of the signer who produced the signature (cannot be NULL) + */ + //if (!secp256k1_musig_partial_sig_verify(ctx, &musig_session[i], &signer_data[i][j], &partial_sig[j], &pubkeys[j])) { + return 0; + /** Combines partial signatures + * + * Returns: 1: all partial signatures have values in range. Does NOT mean the + * resulting signature verifies. + * 0: some partial signature had s/r out of range + * Args: ctx: pointer to a context object (cannot be NULL) + * session: initialized session for which the combined nonce has been + * computed (cannot be NULL) + * Out: sig: complete signature (cannot be NULL) + * In: partial_sigs: array of partial signatures to combine (cannot be NULL) + * n_sigs: number of signatures in the partial_sigs array + */ + // after all partials: return secp256k1_musig_partial_sig_combine(ctx, &musig_session[0], sig, partial_sig, N_SIGNERS return(result); } UniValue musig_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { UniValue result(UniValue::VOBJ); result.push_back(Pair("result","success")); + /** Verify a Schnorr signature. + * + * Returns: 1: correct signature + * 0: incorrect or unparseable signature + * Args: ctx: a secp256k1 context object, initialized for verification. + * In: sig: the signature being verified (cannot be NULL) + * msg32: the 32-byte message hash being verified (cannot be NULL) + * pubkey: pointer to a public key to verify with (cannot be NULL) + */ + // if (!secp256k1_schnorrsig_verify(ctx, &sig, msg, &combined_pk)) { return(result); } From a709fe0fef57f03a74e6506b56ff450f31c6f5db Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 06:44:01 -1100 Subject: [PATCH 261/390] Remove exe permission on source files --- src/cc/dapps/cJSON.c | 0 src/cc/musig.cpp | 0 src/komodo_cJSON.c | 0 src/komodo_cJSON.h | 0 src/komodo_jumblr.h | 0 src/uthash.h | 0 src/utlist.h | 0 7 files changed, 0 insertions(+), 0 deletions(-) mode change 100755 => 100644 src/cc/dapps/cJSON.c mode change 100755 => 100644 src/cc/musig.cpp mode change 100755 => 100644 src/komodo_cJSON.c mode change 100755 => 100644 src/komodo_cJSON.h mode change 100755 => 100644 src/komodo_jumblr.h mode change 100755 => 100644 src/uthash.h mode change 100755 => 100644 src/utlist.h diff --git a/src/cc/dapps/cJSON.c b/src/cc/dapps/cJSON.c old mode 100755 new mode 100644 diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp old mode 100755 new mode 100644 diff --git a/src/komodo_cJSON.c b/src/komodo_cJSON.c old mode 100755 new mode 100644 diff --git a/src/komodo_cJSON.h b/src/komodo_cJSON.h old mode 100755 new mode 100644 diff --git a/src/komodo_jumblr.h b/src/komodo_jumblr.h old mode 100755 new mode 100644 diff --git a/src/uthash.h b/src/uthash.h old mode 100755 new mode 100644 diff --git a/src/utlist.h b/src/utlist.h old mode 100755 new mode 100644 From 7cef15077601820d30f2b14788daa3f1aad75b9d Mon Sep 17 00:00:00 2001 From: ca333 Date: Thu, 21 Feb 2019 18:48:22 +0100 Subject: [PATCH 262/390] add win deps --- src/cc/rogue/Makefile_win | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/Makefile_win b/src/cc/rogue/Makefile_win index dbc900e48..96b6e61be 100644 --- a/src/cc/rogue/Makefile_win +++ b/src/cc/rogue/Makefile_win @@ -26,7 +26,7 @@ O=o CC = x86_64-w64-mingw32-gcc #CFLAGS=-O2 -CFLAGS= -g -O2 -I./ncurses/include +CFLAGS= -g -O2 -I./ncurses/include --I../../../depends/x86_64-w64-mingw32/include #LIBS=-lcurses LIBS = -L./ncurses/lib -lncursesw From 118461e55427865e34bdbb8a873b489ca9809aab Mon Sep 17 00:00:00 2001 From: ca333 Date: Thu, 21 Feb 2019 18:51:12 +0100 Subject: [PATCH 263/390] fix typo --- src/cc/makerogue | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/makerogue b/src/cc/makerogue index ff175c586..c67892b90 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -5,7 +5,7 @@ if [ "$HOST" = "x86_64-w64-mingw32" ]; then echo building rogue.exe... mkdir ncurses && cd ncurses wget https://invisible-island.net/datafiles/release/mingw32.zip - unzip mingw32.zip && delete mingw32.zip + unzip mingw32.zip && rm mingw32.zip cd .. if make -f Makefile_win "$@"; then echo rogue.exe build SUCCESSFUL From bf44755dadc8ba400c86018d3aed161b778cb8cf Mon Sep 17 00:00:00 2001 From: ca333 Date: Thu, 21 Feb 2019 18:56:25 +0100 Subject: [PATCH 264/390] pwd --- src/cc/makerogue | 1 - 1 file changed, 1 deletion(-) diff --git a/src/cc/makerogue b/src/cc/makerogue index c67892b90..9135753c1 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -6,7 +6,6 @@ if [ "$HOST" = "x86_64-w64-mingw32" ]; then mkdir ncurses && cd ncurses wget https://invisible-island.net/datafiles/release/mingw32.zip unzip mingw32.zip && rm mingw32.zip - cd .. if make -f Makefile_win "$@"; then echo rogue.exe build SUCCESSFUL cd .. From 8998c66874885248c2ac53aa044fdee3c413bcfb Mon Sep 17 00:00:00 2001 From: ca333 Date: Thu, 21 Feb 2019 18:58:09 +0100 Subject: [PATCH 265/390] revert --- src/cc/makerogue | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/makerogue b/src/cc/makerogue index 9135753c1..c67892b90 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -6,6 +6,7 @@ if [ "$HOST" = "x86_64-w64-mingw32" ]; then mkdir ncurses && cd ncurses wget https://invisible-island.net/datafiles/release/mingw32.zip unzip mingw32.zip && rm mingw32.zip + cd .. if make -f Makefile_win "$@"; then echo rogue.exe build SUCCESSFUL cd .. From 55b7035f9b0736f06607768e13e2cd5b94a8da06 Mon Sep 17 00:00:00 2001 From: ca333 Date: Thu, 21 Feb 2019 19:04:45 +0100 Subject: [PATCH 266/390] add include --- src/cc/rogue/Makefile_win | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/Makefile_win b/src/cc/rogue/Makefile_win index 96b6e61be..17941732c 100644 --- a/src/cc/rogue/Makefile_win +++ b/src/cc/rogue/Makefile_win @@ -26,7 +26,7 @@ O=o CC = x86_64-w64-mingw32-gcc #CFLAGS=-O2 -CFLAGS= -g -O2 -I./ncurses/include --I../../../depends/x86_64-w64-mingw32/include +CFLAGS= -g -O2 -I./ncurses/include -I../../../depends/x86_64-w64-mingw32/include #LIBS=-lcurses LIBS = -L./ncurses/lib -lncursesw From 762e3582d1d1109e97c3cb81ac8fb9501236033e Mon Sep 17 00:00:00 2001 From: ca333 Date: Thu, 21 Feb 2019 19:09:07 +0100 Subject: [PATCH 267/390] pwd --- src/cc/makerogue | 1 - 1 file changed, 1 deletion(-) diff --git a/src/cc/makerogue b/src/cc/makerogue index c67892b90..9135753c1 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -6,7 +6,6 @@ if [ "$HOST" = "x86_64-w64-mingw32" ]; then mkdir ncurses && cd ncurses wget https://invisible-island.net/datafiles/release/mingw32.zip unzip mingw32.zip && rm mingw32.zip - cd .. if make -f Makefile_win "$@"; then echo rogue.exe build SUCCESSFUL cd .. From b635717ec1219c8d3542962cfc01dc43432815b1 Mon Sep 17 00:00:00 2001 From: ca333 Date: Thu, 21 Feb 2019 19:40:52 +0100 Subject: [PATCH 268/390] add ncursesw --- src/cc/rogue/Makefile_win | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/Makefile_win b/src/cc/rogue/Makefile_win index 17941732c..9c440349e 100644 --- a/src/cc/rogue/Makefile_win +++ b/src/cc/rogue/Makefile_win @@ -26,7 +26,7 @@ O=o CC = x86_64-w64-mingw32-gcc #CFLAGS=-O2 -CFLAGS= -g -O2 -I./ncurses/include -I../../../depends/x86_64-w64-mingw32/include +CFLAGS= -g -O2 -I./ncurses/include -I./ncurses/include/ncursesw -I../../../depends/x86_64-w64-mingw32/include #LIBS=-lcurses LIBS = -L./ncurses/lib -lncursesw From 47b99da2a3d4a7dfa6bd9ccce67446a6183dcabb Mon Sep 17 00:00:00 2001 From: ca333 Date: Thu, 21 Feb 2019 20:41:57 +0100 Subject: [PATCH 269/390] add debug --- src/cc/makerogue | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/cc/makerogue b/src/cc/makerogue index 9135753c1..b690e60e7 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -4,8 +4,11 @@ cd rogue; if [ "$HOST" = "x86_64-w64-mingw32" ]; then echo building rogue.exe... mkdir ncurses && cd ncurses + echo $PWD wget https://invisible-island.net/datafiles/release/mingw32.zip unzip mingw32.zip && rm mingw32.zip + echo lib archive cleaned + echo $PWD if make -f Makefile_win "$@"; then echo rogue.exe build SUCCESSFUL cd .. From fddc7d4369b242cb3b481f0a09d6247513a7913a Mon Sep 17 00:00:00 2001 From: ca333 Date: Thu, 21 Feb 2019 21:28:57 +0100 Subject: [PATCH 270/390] change dir --- src/cc/makerogue | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/makerogue b/src/cc/makerogue index b690e60e7..063de081e 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -8,6 +8,7 @@ if [ "$HOST" = "x86_64-w64-mingw32" ]; then wget https://invisible-island.net/datafiles/release/mingw32.zip unzip mingw32.zip && rm mingw32.zip echo lib archive cleaned + cd .. echo $PWD if make -f Makefile_win "$@"; then echo rogue.exe build SUCCESSFUL From adb32b5a5138baa53adb30e7d324cb3d28405fdd Mon Sep 17 00:00:00 2001 From: ca333 Date: Thu, 21 Feb 2019 22:36:25 +0100 Subject: [PATCH 271/390] add WIN ifdef --- src/cc/rogue/main.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index ca05226d3..bcd35da73 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -41,7 +41,11 @@ typedef union _bits256 bits256; double OS_milliseconds() { struct timeval tv; double millis; + #ifdef __MINGW32__ + mingw_gettimeofday(&tv,NULL); + #else gettimeofday(&tv,NULL); + #endif millis = ((double)tv.tv_sec * 1000. + (double)tv.tv_usec / 1000.); //printf("tv_sec.%ld usec.%d %f\n",tv.tv_sec,tv.tv_usec,millis); return(millis); From 064179cf1894a31b018cf1461074e6895e3b0677 Mon Sep 17 00:00:00 2001 From: ca333 Date: Thu, 21 Feb 2019 23:09:25 +0100 Subject: [PATCH 272/390] config WIN --- src/cc/makerogue | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/makerogue b/src/cc/makerogue index 063de081e..51caef6e2 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -3,6 +3,7 @@ cd rogue; if [ "$HOST" = "x86_64-w64-mingw32" ]; then echo building rogue.exe... + ./configure --host=x86_64-w64-mingw32 mkdir ncurses && cd ncurses echo $PWD wget https://invisible-island.net/datafiles/release/mingw32.zip From 6ca1613add51ece97efb7c9bb33ab878bd76cc2a Mon Sep 17 00:00:00 2001 From: ca333 Date: Fri, 22 Feb 2019 00:31:49 +0100 Subject: [PATCH 273/390] add ifdef WIN mdport --- src/cc/rogue/mdport.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/cc/rogue/mdport.c b/src/cc/rogue/mdport.c index 988e1c7b7..fd53be72c 100644 --- a/src/cc/rogue/mdport.c +++ b/src/cc/rogue/mdport.c @@ -705,7 +705,9 @@ md_erasechar() #elif defined(VERASE) return(_tty.c_cc[VERASE]); /* process erase character */ #else + #ifndef __MINGW32__ return(_tty.sg_erase); /* process erase character */ + #endif #endif } @@ -717,7 +719,9 @@ md_killchar() #elif defined(VKILL) return(_tty.c_cc[VKILL]); #else + #ifndef __MINGW32__ return(_tty.sg_kill); + #endif #endif } From ff9f59279bc6bf3a4e178b99eebda54050208014 Mon Sep 17 00:00:00 2001 From: ca333 Date: Fri, 22 Feb 2019 01:21:04 +0100 Subject: [PATCH 274/390] cache deps --- .gitlab-ci.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 3ace05cb9..a9fb7a01b 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -32,9 +32,9 @@ build:ubuntu: variables: DOCKER_DRIVER: overlay2 cache: - key: "${CI_JOB_NAME}${CI_COMMIT_REF_NAME}" + key: ${CI_COMMIT_REF_SLUG} paths: - - depends/built + - depends/ script: - zcutil/build.sh -j$(nproc) - mkdir ${PACKAGE_DIR_LINUX} From c7b070e91ca79f220e25cfae3d65e057fae519b4 Mon Sep 17 00:00:00 2001 From: ca333 Date: Fri, 22 Feb 2019 01:48:44 +0100 Subject: [PATCH 275/390] add curl --- src/cc/rogue/Makefile_win | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/Makefile_win b/src/cc/rogue/Makefile_win index 9c440349e..6e558960c 100644 --- a/src/cc/rogue/Makefile_win +++ b/src/cc/rogue/Makefile_win @@ -29,7 +29,7 @@ CC = x86_64-w64-mingw32-gcc CFLAGS= -g -O2 -I./ncurses/include -I./ncurses/include/ncursesw -I../../../depends/x86_64-w64-mingw32/include #LIBS=-lcurses -LIBS = -L./ncurses/lib -lncursesw +LIBS = -L./ncurses/lib -lncursesw -lcurl #RM=rm -f RM = rm -f From ba34a8050009e4d1bef4df01b9ec685d7db5cca1 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 19:58:07 -1100 Subject: [PATCH 276/390] +print --- src/cc/faucet.cpp | 2 +- src/cc/musig.cpp | 297 +++++++++++++++++++++++++++++++--------------- 2 files changed, 204 insertions(+), 95 deletions(-) diff --git a/src/cc/faucet.cpp b/src/cc/faucet.cpp index b44337461..3f1ac4982 100644 --- a/src/cc/faucet.cpp +++ b/src/cc/faucet.cpp @@ -124,9 +124,9 @@ bool FaucetValidate(struct CCcontract_info *cp,Eval* eval,const CTransaction &tx //int height = it->first.blockHeight; if ( CCduration(numblocks,it->first.txhash) > 0 && numblocks > 3 ) { - //fprintf(stderr,"would return error %s numblocks.%d ago\n",uint256_str(str,it->first.txhash),numblocks); return eval->Invalid("faucet is only for brand new addresses"); } + fprintf(stderr,"txid %s numblocks.%d ago\n",uint256_str(str,it->first.txhash),numblocks); } retval = PreventCC(eval,tx,preventCCvins,numvins,preventCCvouts,numvouts); if ( retval != 0 ) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index ec7f5e788..263ed2fff 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -88,6 +88,54 @@ extern "C" int secp256k1_musig_pubkey_combine(const secp256k1_context* ctx, secp #define MUSIG_PREVN 0 // for now, just use vout0 for the musig output #define MUSIG_TXFEE 10000 +struct musig_info +{ + secp256k1_musig_session musig_session; + secp256k1_pubkey combined_pk; + uint8_t *nonce_commitments; // 32*N_SIGNERS + secp256k1_musig_session_signer_data *signer_data; //[N_SIGNERS]; + secp256k1_pubkey *nonce; //[N_SIGNERS]; + secp256k1_musig_partial_signature *partial_sig; //[N_SIGNERS]; + int32_t myind,num; + uint8_t msg[32],pkhash[32],combpk[33]; +} *MUSIG; + +struct musig_info *musig_infocreate(int32_t myind,int32_t num) +{ + struct musig_info *mp = (struct musig_info *)calloc(1,sizeof(*mp)); + mp->myind = myind, mp->num = num; + mp->nonce_commitments = (uint8_t *)calloc(num,32); + mp->signer_data = (uint8_t *)calloc(num,sizeof(*np->signer_data)); + mp->nonce = (uint8_t *)calloc(num,sizeof(*np->nonce)); + mp->partial_sig = (uint8_t *)calloc(num,sizeof(*np->partial_sig)); + return(mp); +} + +void musig_infofree(struct musig_info *mp) +{ + if ( mp->partial_sig != 0 ) + { + random_buf(mp->partial_sig,num*sizeof(*np->partial_sig)) + free(mp->partial_sig); + } + if ( mp->nonce != 0 ) + { + random_buf(mp->nonce,num*sizeof(*np->nonce)) + free(mp->nonce); + } + if ( mp->signer_data != 0 ) + { + random_buf(mp->signer_data,num*sizeof(*np->signer_data)) + free(mp->signer_data); + } + if ( mp->nonce_commitments != 0 ) + { + random_buf(mp->nonce_commitments,num*32) + free(mp->nonce_commitments); + } + free(mp); +} + CScript musig_sendopret(uint8_t funcid,CPubKey pk) { CScript opret; uint8_t evalcode = EVAL_MUSIG; @@ -215,111 +263,158 @@ UniValue musig_combine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); - result.push_back(Pair("result","success")); - /** Initializes a signing session for a signer - * - * Returns: 1: session is successfully initialized - * 0: session could not be initialized: secret key or secret nonce overflow - * Args: ctx: pointer to a context object, initialized for signing (cannot - * be NULL) - * Out: session: the session structure to initialize (cannot be NULL) - * signers: an array of signers' data to be initialized. Array length must - * equal to `n_signers` (cannot be NULL) - * nonce_commitment32: filled with a 32-byte commitment to the generated nonce - * (cannot be NULL) - * In: session_id32: a *unique* 32-byte ID to assign to this session (cannot be - * NULL). If a non-unique session_id32 was given then a partial - * signature will LEAK THE SECRET KEY. - * msg32: the 32-byte message to be signed. Shouldn't be NULL unless you - * require sharing public nonces before the message is known - * because it reduces nonce misuse resistance. If NULL, must be - * set with `musig_session_set_msg` before signing and verifying. - * combined_pk: the combined public key of all signers (cannot be NULL) - * pk_hash32: the 32-byte hash of the signers' individual keys (cannot be - * NULL) - * n_signers: length of signers array. Number of signers participating in - * the MuSig. Must be greater than 0 and at most 2^32 - 1. - * my_index: index of this signer in the signers array - * seckey: the signer's 32-byte secret key (cannot be NULL) - */ - //if (!secp256k1_musig_session_initialize(ctx, &musig_session[i], signer_data[i], nonce_commitment[i], session_id32, msg32, &combined_pk, pk_hash, N_SIGNERS, i, seckeys[i])) - //return 0; - // randombytes_buf(buf, num); - - //nonce_commitment_ptr[i] = &nonce_commitment[i][0]; - return(result); + static secp256k1_context *ctx; + UniValue result(UniValue::VOBJ); int32_t i,n,myind,num; char *pkstr,*pkhashstr,*msgstr; uint8_t session[32],msg[32],pkhash[32],privkey[32],pub33[33]; CPubKey pk; char str[67]; + if ( ctx == 0 ) + ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); + if ( params != 0 && (n= cJSON_GetArraySize(params)) == 5 ) + { + // set the 5 args: myind, num, pub33, pkhash32, msg32 + if ( MUSIG != 0 ) + musig_infofree(MUSIG), MUSIG = 0; + MUSIG = musig_infocreate(myind,num); + pk = buf2pk(pub33); + if ( secp256k1_ec_pubkey_parse(ctx,&MUSIG->combined_pk,pk.begin(),33) > 0 ) + { + memcpy(MUSIG->pkhash,pkhash,sizeof(pkhash)); + memcpy(MUSIG->msg,msg,sizeof(msg)); + random_buf(session,32); + Myprivkey(privkey); + /** Initializes a signing session for a signer + * + * Returns: 1: session is successfully initialized + * 0: session could not be initialized: secret key or secret nonce overflow + * Args: ctx: pointer to a context object, initialized for signing (cannot + * be NULL) + * Out: session: the session structure to initialize (cannot be NULL) + * signers: an array of signers' data to be initialized. Array length must + * equal to `n_signers` (cannot be NULL) + * nonce_commitment32: filled with a 32-byte commitment to the generated nonce + * (cannot be NULL) + * In: session_id32: a *unique* 32-byte ID to assign to this session (cannot be + * NULL). If a non-unique session_id32 was given then a partial + * signature will LEAK THE SECRET KEY. + * msg32: the 32-byte message to be signed. Shouldn't be NULL unless you + * require sharing public nonces before the message is known + * because it reduces nonce misuse resistance. If NULL, must be + * set with `musig_session_set_msg` before signing and verifying. + * combined_pk: the combined public key of all signers (cannot be NULL) + * pk_hash32: the 32-byte hash of the signers' individual keys (cannot be + * NULL) + * n_signers: length of signers array. Number of signers participating in + * the MuSig. Must be greater than 0 and at most 2^32 - 1. + * my_index: index of this signer in the signers array + * seckey: the signer's 32-byte secret key (cannot be NULL) + */ + if ( secp256k1_musig_session_initialize(ctx,&MUSIG->musig_session,MUSIG->signer_data, &MUSIG->nonce_commitment[MUSIG->myind * 32],session,MUSIG->msg,&MUSIG->combined_pk,MUSIG->pkhash,MUSIG->num,MUSIG->myind,privkey) > 0 ) + { + result.push_back(Pair("myind",(int64_t)myind)); + result.push_back(Pair("numsigners",(int64_t)num)); + for (i=0; i<32; i++) + sprintf(&str[i<<1],"%02x",MUSIG->nonce_commitment[MUSIG->myind*32 + i]); + str[64] = 0; + result.push_back(Pair("commitment",str)); + result.push_back(Pair("result","success")); + return(result) + } else return(cclib_error(result,"couldnt initialize session")); + } else return(cclib_error(result,"couldnt parse combined pubkey")); + } else return(cclib_error(result,"wrong number of params, need 5: myindex, numsigners, combined_pk, pkhash, msg32")); } UniValue musig_commit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); - result.push_back(Pair("result","success")); - /** Gets the signer's public nonce given a list of all signers' data with commitments - * - * Returns: 1: public nonce is written in nonce - * 0: signer data is missing commitments or session isn't initialized - * for signing - * Args: ctx: pointer to a context object (cannot be NULL) - * session: the signing session to get the nonce from (cannot be NULL) - * signers: an array of signers' data initialized with - * `musig_session_initialize`. Array length must equal to - * `n_commitments` (cannot be NULL) - * Out: nonce: the nonce (cannot be NULL) - * In: commitments: array of 32-byte nonce commitments (cannot be NULL) - * n_commitments: the length of commitments and signers array. Must be the total - * number of signers participating in the MuSig. - */ - // Set nonce commitments in the signer data and get the own public nonce - //if (!secp256k1_musig_session_get_public_nonce(ctx, &musig_session[i], signer_data[i], &nonce[i], nonce_commitment_ptr, N_SIGNERS)) - // return 0; - - return(result); + static secp256k1_context *ctx; + UniValue result(UniValue::VOBJ); int32_t n; + if ( ctx == 0 ) + ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); + if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) + { + // pkhash, ind, commitment + // if all commitments, emit nonce, else just update MUSIG-> + + /** Gets the signer's public nonce given a list of all signers' data with commitments + * + * Returns: 1: public nonce is written in nonce + * 0: signer data is missing commitments or session isn't initialized + * for signing + * Args: ctx: pointer to a context object (cannot be NULL) + * session: the signing session to get the nonce from (cannot be NULL) + * signers: an array of signers' data initialized with + * `musig_session_initialize`. Array length must equal to + * `n_commitments` (cannot be NULL) + * Out: nonce: the nonce (cannot be NULL) + * In: commitments: array of 32-byte nonce commitments (cannot be NULL) + * n_commitments: the length of commitments and signers array. Must be the total + * number of signers participating in the MuSig. + */ + // Set nonce commitments in the signer data and get the own public nonce + //if (secp256k1_musig_session_get_public_nonce(ctx, &musig_session[i], signer_data[i], &nonce[i], nonce_commitment_ptr, N_SIGNERS) > 0 ) + { + // publish nonce + result.push_back(Pair("result","success")); + } + // return 0; + } else return(cclib_error(result,"wrong number of params, need 3: pkhash, ind, commitment")); } UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); - result.push_back(Pair("result","success")); - /** Checks a signer's public nonce against a commitment to said nonce, and update - * data structure if they match - * - * Returns: 1: commitment was valid, data structure updated - * 0: commitment was invalid, nothing happened - * Args: ctx: pointer to a context object (cannot be NULL) - * signer: pointer to the signer data to update (cannot be NULL). Must have - * been used with `musig_session_get_public_nonce` or initialized - * with `musig_session_initialize_verifier`. - * In: nonce: signer's alleged public nonce (cannot be NULL) - */ - //if (!secp256k1_musig_set_nonce(ctx, &signer_data[i][j], &nonce[j])) { - - - /** Updates a session with the combined public nonce of all signers. The combined - * public nonce is the sum of every signer's public nonce. - * - * Returns: 1: nonces are successfully combined - * 0: a signer's nonce is missing - * Args: ctx: pointer to a context object (cannot be NULL) - * session: session to update with the combined public nonce (cannot be - * NULL) - * signers: an array of signers' data, which must have had public nonces - * set with `musig_set_nonce`. Array length must equal to `n_signers` - * (cannot be NULL) - * n_signers: the length of the signers array. Must be the total number of - * signers participating in the MuSig. - * Out: nonce_is_negated: a pointer to an integer that indicates if the combined - * public nonce had to be negated. - * adaptor: point to add to the combined public nonce. If NULL, nothing is - * added to the combined nonce. - */ - // after all nonces: if (!secp256k1_musig_session_combine_nonces(ctx, &musig_session[i], signer_data[i], N_SIGNERS, NULL, NULL)) { + static secp256k1_context *ctx; + UniValue result(UniValue::VOBJ); int32_t n; + if ( ctx == 0 ) + ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); + if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) + { + // pkhash, ind, nonce + // if all nonces, combine nonce, else just update MUSIG-> + result.push_back(Pair("result","success")); + /** Checks a signer's public nonce against a commitment to said nonce, and update + * data structure if they match + * + * Returns: 1: commitment was valid, data structure updated + * 0: commitment was invalid, nothing happened + * Args: ctx: pointer to a context object (cannot be NULL) + * signer: pointer to the signer data to update (cannot be NULL). Must have + * been used with `musig_session_get_public_nonce` or initialized + * with `musig_session_initialize_verifier`. + * In: nonce: signer's alleged public nonce (cannot be NULL) + */ + //if (!secp256k1_musig_set_nonce(ctx, &signer_data[i][j], &nonce[j])) { + + + /** Updates a session with the combined public nonce of all signers. The combined + * public nonce is the sum of every signer's public nonce. + * + * Returns: 1: nonces are successfully combined + * 0: a signer's nonce is missing + * Args: ctx: pointer to a context object (cannot be NULL) + * session: session to update with the combined public nonce (cannot be + * NULL) + * signers: an array of signers' data, which must have had public nonces + * set with `musig_set_nonce`. Array length must equal to `n_signers` + * (cannot be NULL) + * n_signers: the length of the signers array. Must be the total number of + * signers participating in the MuSig. + * Out: nonce_is_negated: a pointer to an integer that indicates if the combined + * public nonce had to be negated. + * adaptor: point to add to the combined public nonce. If NULL, nothing is + * added to the combined nonce. + */ + // after all nonces: if (!secp256k1_musig_session_combine_nonces(ctx, &musig_session[i], signer_data[i], N_SIGNERS, NULL, NULL)) { return(result); + } else return(cclib_error(result,"wrong number of params, need 3: pkhash, ind, nonce")); } UniValue musig_partialsign(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); + static secp256k1_context *ctx; + UniValue result(UniValue::VOBJ); int32_t n; + if ( ctx == 0 ) + ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); + if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) + { + // similar to commit/nonce + } result.push_back(Pair("result","success")); /** Produces a partial signature * @@ -349,7 +444,14 @@ UniValue musig_partialsign(uint64_t txfee,struct CCcontract_info *cp,cJSON *para UniValue musig_sigcombine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); + static secp256k1_context *ctx; + UniValue result(UniValue::VOBJ); int32_t n; + if ( ctx == 0 ) + ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); + if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) + { + // finally! + } result.push_back(Pair("result","success")); /** Checks that an individual partial signature verifies * @@ -387,7 +489,14 @@ UniValue musig_sigcombine(uint64_t txfee,struct CCcontract_info *cp,cJSON *param UniValue musig_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); + static secp256k1_context *ctx; + UniValue result(UniValue::VOBJ); int32_t n; + if ( ctx == 0 ) + ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); + if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) + { + // can code this out of order + } result.push_back(Pair("result","success")); /** Verify a Schnorr signature. * From cb1a6291c6e45addf50146971703be58badeff52 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 19:59:46 -1100 Subject: [PATCH 277/390] Mp --- src/cc/musig.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 263ed2fff..b54bf26d1 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -105,9 +105,9 @@ struct musig_info *musig_infocreate(int32_t myind,int32_t num) struct musig_info *mp = (struct musig_info *)calloc(1,sizeof(*mp)); mp->myind = myind, mp->num = num; mp->nonce_commitments = (uint8_t *)calloc(num,32); - mp->signer_data = (uint8_t *)calloc(num,sizeof(*np->signer_data)); - mp->nonce = (uint8_t *)calloc(num,sizeof(*np->nonce)); - mp->partial_sig = (uint8_t *)calloc(num,sizeof(*np->partial_sig)); + mp->signer_data = (uint8_t *)calloc(num,sizeof(*mp->signer_data)); + mp->nonce = (uint8_t *)calloc(num,sizeof(*mp->nonce)); + mp->partial_sig = (uint8_t *)calloc(num,sizeof(*mp->partial_sig)); return(mp); } @@ -115,22 +115,22 @@ void musig_infofree(struct musig_info *mp) { if ( mp->partial_sig != 0 ) { - random_buf(mp->partial_sig,num*sizeof(*np->partial_sig)) + random_buf(mp->partial_sig,mp->num*sizeof(*np->partial_sig)) free(mp->partial_sig); } if ( mp->nonce != 0 ) { - random_buf(mp->nonce,num*sizeof(*np->nonce)) + random_buf(mp->nonce,mp->num*sizeof(*mp->nonce)) free(mp->nonce); } if ( mp->signer_data != 0 ) { - random_buf(mp->signer_data,num*sizeof(*np->signer_data)) + random_buf(mp->signer_data,mp->num*sizeof(*mp->signer_data)) free(mp->signer_data); } if ( mp->nonce_commitments != 0 ) { - random_buf(mp->nonce_commitments,num*32) + random_buf(mp->nonce_commitments,mp->num*32) free(mp->nonce_commitments); } free(mp); From da11af7c0ff54a3071e0e3f50723d2d6610e4364 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 20:01:06 -1100 Subject: [PATCH 278/390] Test --- src/cc/musig.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index b54bf26d1..44ddf6ef3 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -87,6 +87,7 @@ extern "C" int secp256k1_musig_pubkey_combine(const secp256k1_context* ctx, secp #define MUSIG_PREVN 0 // for now, just use vout0 for the musig output #define MUSIG_TXFEE 10000 +#define random_buf(a,b) struct musig_info { @@ -105,9 +106,9 @@ struct musig_info *musig_infocreate(int32_t myind,int32_t num) struct musig_info *mp = (struct musig_info *)calloc(1,sizeof(*mp)); mp->myind = myind, mp->num = num; mp->nonce_commitments = (uint8_t *)calloc(num,32); - mp->signer_data = (uint8_t *)calloc(num,sizeof(*mp->signer_data)); - mp->nonce = (uint8_t *)calloc(num,sizeof(*mp->nonce)); - mp->partial_sig = (uint8_t *)calloc(num,sizeof(*mp->partial_sig)); + mp->signer_data = (secp256k1_musig_session_signer_data *)calloc(num,sizeof(*mp->signer_data)); + mp->nonce = (secp256k1_pubkey *)calloc(num,sizeof(*mp->nonce)); + mp->partial_sig = (secp256k1_musig_partial_signature *)calloc(num,sizeof(*mp->partial_sig)); return(mp); } @@ -115,7 +116,7 @@ void musig_infofree(struct musig_info *mp) { if ( mp->partial_sig != 0 ) { - random_buf(mp->partial_sig,mp->num*sizeof(*np->partial_sig)) + random_buf(mp->partial_sig,mp->num*sizeof(*mp->partial_sig)) free(mp->partial_sig); } if ( mp->nonce != 0 ) From e1c434466734a26921d98c6e0db1cb12df3a2f08 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 20:02:05 -1100 Subject: [PATCH 279/390] syntax --- src/cc/musig.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 44ddf6ef3..aa821f644 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -307,16 +307,16 @@ UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) * my_index: index of this signer in the signers array * seckey: the signer's 32-byte secret key (cannot be NULL) */ - if ( secp256k1_musig_session_initialize(ctx,&MUSIG->musig_session,MUSIG->signer_data, &MUSIG->nonce_commitment[MUSIG->myind * 32],session,MUSIG->msg,&MUSIG->combined_pk,MUSIG->pkhash,MUSIG->num,MUSIG->myind,privkey) > 0 ) + if ( secp256k1_musig_session_initialize(ctx,&MUSIG->musig_session,MUSIG->signer_data, &MUSIG->nonce_commitments[MUSIG->myind * 32],session,MUSIG->msg,&MUSIG->combined_pk,MUSIG->pkhash,MUSIG->num,MUSIG->myind,privkey) > 0 ) { result.push_back(Pair("myind",(int64_t)myind)); result.push_back(Pair("numsigners",(int64_t)num)); for (i=0; i<32; i++) - sprintf(&str[i<<1],"%02x",MUSIG->nonce_commitment[MUSIG->myind*32 + i]); + sprintf(&str[i<<1],"%02x",MUSIG->nonce_commitments[MUSIG->myind*32 + i]); str[64] = 0; result.push_back(Pair("commitment",str)); result.push_back(Pair("result","success")); - return(result) + return(result); } else return(cclib_error(result,"couldnt initialize session")); } else return(cclib_error(result,"couldnt parse combined pubkey")); } else return(cclib_error(result,"wrong number of params, need 5: myindex, numsigners, combined_pk, pkhash, msg32")); From 40c26873ba97286ed860c8e4c742b68cc28f237c Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 20:03:14 -1100 Subject: [PATCH 280/390] extern "C" --- src/cc/musig.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index aa821f644..68787e67b 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -78,6 +78,7 @@ extern "C" int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, s extern "C" int secp256k1_schnorrsig_verify(const secp256k1_context* ctx, const secp256k1_schnorrsig *sig, const unsigned char *msg32, const secp256k1_pubkey *pk); extern "C" int secp256k1_schnorrsig_parse(const secp256k1_context* ctx, secp256k1_schnorrsig* sig, const unsigned char *in64); extern "C" int secp256k1_musig_pubkey_combine(const secp256k1_context* ctx, secp256k1_scratch_space *scratch, secp256k1_pubkey *combined_pk, unsigned char *pk_hash32, const secp256k1_pubkey *pubkeys, size_t n_pubkeys); +extern "C" int secp256k1_musig_session_initialize(const secp256k1_context* ctx, secp256k1_musig_session *session, secp256k1_musig_session_signer_data *signers, unsigned char *nonce_commitment32, const unsigned char *session_id32, const unsigned char *msg32, const secp256k1_pubkey *combined_pk, const unsigned char *pk_hash32, size_t n_signers, size_t my_index, const unsigned char *seckey); //#include "../secp256k1/include/secp256k1.h" From 146d452410880c1657f479c22f33d51402b667aa Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 20:03:56 -1100 Subject: [PATCH 281/390] Reorder --- src/cc/musig.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 68787e67b..8fdba80a2 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -74,18 +74,18 @@ struct secp256k1_context_struct { secp256k1_callback error_callback; }; -extern "C" int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n); -extern "C" int secp256k1_schnorrsig_verify(const secp256k1_context* ctx, const secp256k1_schnorrsig *sig, const unsigned char *msg32, const secp256k1_pubkey *pk); -extern "C" int secp256k1_schnorrsig_parse(const secp256k1_context* ctx, secp256k1_schnorrsig* sig, const unsigned char *in64); -extern "C" int secp256k1_musig_pubkey_combine(const secp256k1_context* ctx, secp256k1_scratch_space *scratch, secp256k1_pubkey *combined_pk, unsigned char *pk_hash32, const secp256k1_pubkey *pubkeys, size_t n_pubkeys); -extern "C" int secp256k1_musig_session_initialize(const secp256k1_context* ctx, secp256k1_musig_session *session, secp256k1_musig_session_signer_data *signers, unsigned char *nonce_commitment32, const unsigned char *session_id32, const unsigned char *msg32, const secp256k1_pubkey *combined_pk, const unsigned char *pk_hash32, size_t n_signers, size_t my_index, const unsigned char *seckey); - //#include "../secp256k1/include/secp256k1.h" //#include "../secp256k1/include/secp256k1_schnorrsig.h" #include "../secp256k1/include/secp256k1_musig.h" +extern "C" int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n); +extern "C" int secp256k1_schnorrsig_verify(const secp256k1_context* ctx, const secp256k1_schnorrsig *sig, const unsigned char *msg32, const secp256k1_pubkey *pk); +extern "C" int secp256k1_schnorrsig_parse(const secp256k1_context* ctx, secp256k1_schnorrsig* sig, const unsigned char *in64); +extern "C" int secp256k1_musig_pubkey_combine(const secp256k1_context* ctx, secp256k1_scratch_space *scratch, secp256k1_pubkey *combined_pk, unsigned char *pk_hash32, const secp256k1_pubkey *pubkeys, size_t n_pubkeys); +extern "C" int secp256k1_musig_session_initialize(const secp256k1_context* ctx, secp256k1_musig_session *session, secp256k1_musig_session_signer_data *signers, unsigned char *nonce_commitment32, const unsigned char *session_id32, const unsigned char *msg32, const secp256k1_pubkey *combined_pk, const unsigned char *pk_hash32, size_t n_signers, size_t my_index, const unsigned char *seckey); + #define MUSIG_PREVN 0 // for now, just use vout0 for the musig output #define MUSIG_TXFEE 10000 #define random_buf(a,b) From c76bd865230436337d54231fcaa6ca86957cb0b2 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 20:06:25 -1100 Subject: [PATCH 282/390] #ifdef __cplusplus --- src/secp256k1/include/secp256k1_musig.h | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/secp256k1/include/secp256k1_musig.h b/src/secp256k1/include/secp256k1_musig.h index 7e974e36d..d58550cf8 100644 --- a/src/secp256k1/include/secp256k1_musig.h +++ b/src/secp256k1/include/secp256k1_musig.h @@ -167,7 +167,12 @@ SECP256K1_API int secp256k1_musig_pubkey_combine( * my_index: index of this signer in the signers array * seckey: the signer's 32-byte secret key (cannot be NULL) */ -SECP256K1_API int secp256k1_musig_session_initialize( +#ifdef __cplusplus +extern "C" +#else +SECP256K1_API +#endif + int secp256k1_musig_session_initialize( const secp256k1_context* ctx, secp256k1_musig_session *session, secp256k1_musig_session_signer_data *signers, From db9149577974a6cda3a60ae4196c9b2d7a3eeec5 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 20:07:50 -1100 Subject: [PATCH 283/390] Again --- src/secp256k1/include/secp256k1_musig.h | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/secp256k1/include/secp256k1_musig.h b/src/secp256k1/include/secp256k1_musig.h index d58550cf8..a0106e691 100644 --- a/src/secp256k1/include/secp256k1_musig.h +++ b/src/secp256k1/include/secp256k1_musig.h @@ -132,7 +132,12 @@ typedef struct { * key (cannot be NULL) * n_pubkeys: length of pubkeys array */ -SECP256K1_API int secp256k1_musig_pubkey_combine( +#ifdef __cplusplus +extern "C" +#else +SECP256K1_API +#endif + int secp256k1_musig_pubkey_combine( const secp256k1_context* ctx, secp256k1_scratch_space *scratch, secp256k1_pubkey *combined_pk, From f20d2860dec77fcdca16d874787a037058855cf5 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 20:11:38 -1100 Subject: [PATCH 284/390] -print --- src/cc/faucet.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/faucet.cpp b/src/cc/faucet.cpp index 3f1ac4982..b794d9b1c 100644 --- a/src/cc/faucet.cpp +++ b/src/cc/faucet.cpp @@ -126,7 +126,7 @@ bool FaucetValidate(struct CCcontract_info *cp,Eval* eval,const CTransaction &tx { return eval->Invalid("faucet is only for brand new addresses"); } - fprintf(stderr,"txid %s numblocks.%d ago\n",uint256_str(str,it->first.txhash),numblocks); + //fprintf(stderr,"txid %s numblocks.%d ago\n",uint256_str(str,it->first.txhash),numblocks); } retval = PreventCC(eval,tx,preventCCvins,numvins,preventCCvouts,numvouts); if ( retval != 0 ) From f448c53ac872751e8a2f3d5bd6ed562b61e28443 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 20:13:18 -1100 Subject: [PATCH 285/390] (uint8_t *) --- src/cc/musig.cpp | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 8fdba80a2..80da59927 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -88,7 +88,6 @@ extern "C" int secp256k1_musig_session_initialize(const secp256k1_context* ctx, #define MUSIG_PREVN 0 // for now, just use vout0 for the musig output #define MUSIG_TXFEE 10000 -#define random_buf(a,b) struct musig_info { @@ -117,22 +116,22 @@ void musig_infofree(struct musig_info *mp) { if ( mp->partial_sig != 0 ) { - random_buf(mp->partial_sig,mp->num*sizeof(*mp->partial_sig)) + GetRandBytes((uint8_t *)mp->partial_sig,mp->num*sizeof(*mp->partial_sig)) free(mp->partial_sig); } if ( mp->nonce != 0 ) { - random_buf(mp->nonce,mp->num*sizeof(*mp->nonce)) + GetRandBytes((uint8_t *)mp->nonce,mp->num*sizeof(*mp->nonce)) free(mp->nonce); } if ( mp->signer_data != 0 ) { - random_buf(mp->signer_data,mp->num*sizeof(*mp->signer_data)) + GetRandBytes((uint8_t *)mp->signer_data,mp->num*sizeof(*mp->signer_data)) free(mp->signer_data); } if ( mp->nonce_commitments != 0 ) { - random_buf(mp->nonce_commitments,mp->num*32) + GetRandBytes((uint8_t *)mp->nonce_commitments,mp->num*32) free(mp->nonce_commitments); } free(mp); @@ -280,7 +279,7 @@ UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { memcpy(MUSIG->pkhash,pkhash,sizeof(pkhash)); memcpy(MUSIG->msg,msg,sizeof(msg)); - random_buf(session,32); + GetRandBytes(session,32); Myprivkey(privkey); /** Initializes a signing session for a signer * From 41d1eef0191a48413140f73c5d8abb30602cfceb Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 20:14:14 -1100 Subject: [PATCH 286/390] ; --- src/cc/musig.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 80da59927..633c95feb 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -116,24 +116,25 @@ void musig_infofree(struct musig_info *mp) { if ( mp->partial_sig != 0 ) { - GetRandBytes((uint8_t *)mp->partial_sig,mp->num*sizeof(*mp->partial_sig)) + GetRandBytes((uint8_t *)mp->partial_sig,mp->num*sizeof(*mp->partial_sig)); free(mp->partial_sig); } if ( mp->nonce != 0 ) { - GetRandBytes((uint8_t *)mp->nonce,mp->num*sizeof(*mp->nonce)) + GetRandBytes((uint8_t *)mp->nonce,mp->num*sizeof(*mp->nonce)); free(mp->nonce); } if ( mp->signer_data != 0 ) { - GetRandBytes((uint8_t *)mp->signer_data,mp->num*sizeof(*mp->signer_data)) + GetRandBytes((uint8_t *)mp->signer_data,mp->num*sizeof(*mp->signer_data)); free(mp->signer_data); } if ( mp->nonce_commitments != 0 ) { - GetRandBytes((uint8_t *)mp->nonce_commitments,mp->num*32) + GetRandBytes((uint8_t *)mp->nonce_commitments,mp->num*32); free(mp->nonce_commitments); } + GetRandBytes((uint8_t *)mp,sizeof(*mp)); free(mp); } From dc3767b68f5369114164235da1297ebb07525356 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 20:15:40 -1100 Subject: [PATCH 287/390] Session --- src/cc/musig.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 633c95feb..9f529a341 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -281,6 +281,10 @@ UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) memcpy(MUSIG->pkhash,pkhash,sizeof(pkhash)); memcpy(MUSIG->msg,msg,sizeof(msg)); GetRandBytes(session,32); + for (i=0; i<32; i++) + sprintf(&str[i<<1],"%02x",session[i]); + str[64] = 0; + fprintf(stderr,"session %s\n",str); Myprivkey(privkey); /** Initializes a signing session for a signer * From 3bc10962e5af83cbca4eaf7f8edf5046ce21b5d0 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 20:17:28 -1100 Subject: [PATCH 288/390] Move --- src/cc/musig.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 9f529a341..fc83fe382 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -276,15 +276,15 @@ UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) musig_infofree(MUSIG), MUSIG = 0; MUSIG = musig_infocreate(myind,num); pk = buf2pk(pub33); + GetRandBytes(session,32); + for (i=0; i<32; i++) + sprintf(&str[i<<1],"%02x",session[i]); + str[64] = 0; + fprintf(stderr,"session %s\n",str); if ( secp256k1_ec_pubkey_parse(ctx,&MUSIG->combined_pk,pk.begin(),33) > 0 ) { memcpy(MUSIG->pkhash,pkhash,sizeof(pkhash)); memcpy(MUSIG->msg,msg,sizeof(msg)); - GetRandBytes(session,32); - for (i=0; i<32; i++) - sprintf(&str[i<<1],"%02x",session[i]); - str[64] = 0; - fprintf(stderr,"session %s\n",str); Myprivkey(privkey); /** Initializes a signing session for a signer * From d84a9afe6f071c0801f1350c9acbf7a128f96c55 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 22:03:15 -1100 Subject: [PATCH 289/390] Add parsing for session --- src/cc/musig.cpp | 64 ++++++++++++++++++++++++++++++++++-------------- 1 file changed, 46 insertions(+), 18 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index fc83fe382..ccb554e0f 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -223,6 +223,27 @@ UniValue musig_calcmsg(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) } else return(cclib_error(result,"couldnt parse params")); } +int32_t musig_parsepubkey(secp256k1_context *ctx,secp256k1_pubkey &spk,cJSON *item) +{ + char *hexstr; + if ( (hexstr= jstr(item,0)) != 0 && is_hexstr(hexstr,0) == 66 ) + { + CPubKey pk(ParseHex(hexstr)); + if ( secp256k1_ec_pubkey_parse(ctx,&spk,pk.begin(),33) > 0 ) + return(1); + } else return(-1); +} + +int32_t musig_parsehash32(uint8_t *hash32,cJSON *item) +{ + char *hexstr; + if ( (hexstr= jstr(item,0)) != 0 && is_hexstr(hexstr,0) == 64 ) + { + decode_hex(hash32,32,hexstr); + return(0); + } else return(-1); +} + UniValue musig_combine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { static secp256k1_context *ctx; @@ -235,13 +256,9 @@ UniValue musig_combine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) //fprintf(stderr,"n.%d args.(%s)\n",n,jprint(params,0)); for (i=0; i 0 ) - pubkeys.push_back(spk); - else return(cclib_error(result,"error parsing pk")); - } else return(cclib_error(result,"all pubkeys must be 33 bytes hexdata")); + if ( musig_parsepubkey(ctx,spk,jitem(params,i)) < 0 ) + return(cclib_error(result,"error parsing pk")); + pubkeys.push_back(spk); } if ( secp256k1_musig_pubkey_combine(ctx,NULL,&combined_pk,pkhash,&pubkeys[0],n) > 0 ) { @@ -271,21 +288,26 @@ UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); if ( params != 0 && (n= cJSON_GetArraySize(params)) == 5 ) { - // set the 5 args: myind, num, pub33, pkhash32, msg32 + myind = juint(jitem(params,0),0); + num = juint(jitem(params,1),0); + if ( myind < 0 || myind >= num || num <= 0 ) + return(cclib_error(result,"illegal myindex and numsigners")); if ( MUSIG != 0 ) musig_infofree(MUSIG), MUSIG = 0; MUSIG = musig_infocreate(myind,num); - pk = buf2pk(pub33); - GetRandBytes(session,32); - for (i=0; i<32; i++) - sprintf(&str[i<<1],"%02x",session[i]); - str[64] = 0; - fprintf(stderr,"session %s\n",str); - if ( secp256k1_ec_pubkey_parse(ctx,&MUSIG->combined_pk,pk.begin(),33) > 0 ) + if ( musig_parsepubkey(ctx,MUSIG->combined_pk,jitem(params,2)) < 0 ) + return(cclib_error(result,"error parsing combined_pubkey")); { - memcpy(MUSIG->pkhash,pkhash,sizeof(pkhash)); - memcpy(MUSIG->msg,msg,sizeof(msg)); + if ( musig_parsehash32(MUSIG->pkhash,jitem(params,3)) < 0 ) + return(cclib_error(result,"error parsing pkhash")); + if ( musig_parsehash32(MUSIG->msg,jitem(params,4)) < 0 ) + return(cclib_error(result,"error parsing msg")); Myprivkey(privkey); + GetRandBytes(session,32); + for (i=0; i<32; i++) + sprintf(&str[i<<1],"%02x",session[i]); + str[64] = 0; + fprintf(stderr,"session %s\n",str); /** Initializes a signing session for a signer * * Returns: 1: session is successfully initialized @@ -314,6 +336,7 @@ UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) */ if ( secp256k1_musig_session_initialize(ctx,&MUSIG->musig_session,MUSIG->signer_data, &MUSIG->nonce_commitments[MUSIG->myind * 32],session,MUSIG->msg,&MUSIG->combined_pk,MUSIG->pkhash,MUSIG->num,MUSIG->myind,privkey) > 0 ) { + memset(session,0,sizeof(session)); result.push_back(Pair("myind",(int64_t)myind)); result.push_back(Pair("numsigners",(int64_t)num)); for (i=0; i<32; i++) @@ -322,7 +345,12 @@ UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) result.push_back(Pair("commitment",str)); result.push_back(Pair("result","success")); return(result); - } else return(cclib_error(result,"couldnt initialize session")); + } + else + { + memset(session,0,sizeof(session)); + return(cclib_error(result,"couldnt initialize session")); + } } else return(cclib_error(result,"couldnt parse combined pubkey")); } else return(cclib_error(result,"wrong number of params, need 5: myindex, numsigners, combined_pk, pkhash, msg32")); } From 101a4153799c06ce3efc6705286c36184c3c383b Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 22:05:27 -1100 Subject: [PATCH 290/390] Fix --- src/cc/musig.cpp | 52 +++++++++++++++++++++--------------------------- 1 file changed, 23 insertions(+), 29 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index ccb554e0f..7b9510b2a 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -297,17 +297,12 @@ UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) MUSIG = musig_infocreate(myind,num); if ( musig_parsepubkey(ctx,MUSIG->combined_pk,jitem(params,2)) < 0 ) return(cclib_error(result,"error parsing combined_pubkey")); - { - if ( musig_parsehash32(MUSIG->pkhash,jitem(params,3)) < 0 ) - return(cclib_error(result,"error parsing pkhash")); - if ( musig_parsehash32(MUSIG->msg,jitem(params,4)) < 0 ) - return(cclib_error(result,"error parsing msg")); - Myprivkey(privkey); - GetRandBytes(session,32); - for (i=0; i<32; i++) - sprintf(&str[i<<1],"%02x",session[i]); - str[64] = 0; - fprintf(stderr,"session %s\n",str); + else if ( musig_parsehash32(MUSIG->pkhash,jitem(params,3)) < 0 ) + return(cclib_error(result,"error parsing pkhash")); + else if ( musig_parsehash32(MUSIG->msg,jitem(params,4)) < 0 ) + return(cclib_error(result,"error parsing msg")); + Myprivkey(privkey); + GetRandBytes(session,32); /** Initializes a signing session for a signer * * Returns: 1: session is successfully initialized @@ -334,24 +329,23 @@ UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) * my_index: index of this signer in the signers array * seckey: the signer's 32-byte secret key (cannot be NULL) */ - if ( secp256k1_musig_session_initialize(ctx,&MUSIG->musig_session,MUSIG->signer_data, &MUSIG->nonce_commitments[MUSIG->myind * 32],session,MUSIG->msg,&MUSIG->combined_pk,MUSIG->pkhash,MUSIG->num,MUSIG->myind,privkey) > 0 ) - { - memset(session,0,sizeof(session)); - result.push_back(Pair("myind",(int64_t)myind)); - result.push_back(Pair("numsigners",(int64_t)num)); - for (i=0; i<32; i++) - sprintf(&str[i<<1],"%02x",MUSIG->nonce_commitments[MUSIG->myind*32 + i]); - str[64] = 0; - result.push_back(Pair("commitment",str)); - result.push_back(Pair("result","success")); - return(result); - } - else - { - memset(session,0,sizeof(session)); - return(cclib_error(result,"couldnt initialize session")); - } - } else return(cclib_error(result,"couldnt parse combined pubkey")); + if ( secp256k1_musig_session_initialize(ctx,&MUSIG->musig_session,MUSIG->signer_data, &MUSIG->nonce_commitments[MUSIG->myind * 32],session,MUSIG->msg,&MUSIG->combined_pk,MUSIG->pkhash,MUSIG->num,MUSIG->myind,privkey) > 0 ) + { + memset(session,0,sizeof(session)); + result.push_back(Pair("myind",(int64_t)myind)); + result.push_back(Pair("numsigners",(int64_t)num)); + for (i=0; i<32; i++) + sprintf(&str[i<<1],"%02x",MUSIG->nonce_commitments[MUSIG->myind*32 + i]); + str[64] = 0; + result.push_back(Pair("commitment",str)); + result.push_back(Pair("result","success")); + return(result); + } + else + { + memset(session,0,sizeof(session)); + return(cclib_error(result,"couldnt initialize session")); + } } else return(cclib_error(result,"wrong number of params, need 5: myindex, numsigners, combined_pk, pkhash, msg32")); } From eb09e81eaedefc639bb3ea61729066e3b33224b4 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 23:29:46 -1100 Subject: [PATCH 291/390] Musig commitment, nonce and partial sig roc --- src/cc/cclib.cpp | 20 +- src/cc/musig.cpp | 231 +++++++++++-------- src/secp256k1/include/secp256k1_musig.h | 84 ++++++- src/secp256k1/include/secp256k1_schnorrsig.h | 14 +- 4 files changed, 226 insertions(+), 123 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index bfd57e61d..ec74877b6 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -72,12 +72,11 @@ CClib_methods[] = { (char *)"sudoku", (char *)"pending", (char *)"", 0, 0, 'U', EVAL_SUDOKU }, { (char *)"sudoku", (char *)"solution", (char *)"txid solution timestamps[81]", 83, 83, 'S', EVAL_SUDOKU }, { (char *)"musig", (char *)"calcmsg", (char *)"sendtxid scriptPubKey", 2, 2, 'C', EVAL_MUSIG }, - { (char *)"musig", (char *)"combine", (char *)"pubkeys ...", 2, 256, 'P', EVAL_MUSIG }, - { (char *)"musig", (char *)"session", (char *)"msg pkhash", 2, 2, 'R', EVAL_MUSIG }, - { (char *)"musig", (char *)"commit", (char *)"pubkeys ...", 2, 256, 'H', EVAL_MUSIG }, - { (char *)"musig", (char *)"nonce", (char *)"pubkeys ...", 2, 256, 'N', EVAL_MUSIG }, - { (char *)"musig", (char *)"partialsign", (char *)"pubkeys ...", 2, 256, 'S', EVAL_MUSIG }, - { (char *)"musig", (char *)"sigcombine", (char *)"pubkeys ...", 2, 256, 'M', EVAL_MUSIG }, + { (char *)"musig", (char *)"combine", (char *)"pubkeys ...", 2, 999999999, 'P', EVAL_MUSIG }, + { (char *)"musig", (char *)"session", (char *)"myindex,numsigners,combined_pk,pkhash,msg32", 5, 5, 'R', EVAL_MUSIG }, + { (char *)"musig", (char *)"commit", (char *)"pkhash,ind,commitment", 3, 3, 'H', EVAL_MUSIG }, + { (char *)"musig", (char *)"nonce", (char *)"pkhash,ind,nonce", 3, 3, 'N', EVAL_MUSIG }, + { (char *)"musig", (char *)"partialsig", (char *)"pkhash,ind,partialsig", 3, 3, 'S', EVAL_MUSIG }, { (char *)"musig", (char *)"verify", (char *)"msg sig pubkey", 3, 3, 'V', EVAL_MUSIG }, { (char *)"musig", (char *)"send", (char *)"combined_pk amount", 2, 2, 'x', EVAL_MUSIG }, { (char *)"musig", (char *)"spend", (char *)"sendtxid sig destpubkey", 3, 3, 'y', EVAL_MUSIG }, @@ -116,8 +115,7 @@ UniValue musig_combine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue musig_commit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); -UniValue musig_partialsign(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); -UniValue musig_sigcombine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +UniValue musig_partialsig(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue musig_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue musig_send(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); @@ -229,10 +227,8 @@ UniValue CClib_method(struct CCcontract_info *cp,char *method,char *jsonstr) return(musig_commit(txfee,cp,params)); else if ( strcmp(method,"nonce") == 0 ) // returns combined nonce if ready return(musig_nonce(txfee,cp,params)); - else if ( strcmp(method,"partialsign") == 0 ) - return(musig_partialsign(txfee,cp,params)); - else if ( strcmp(method,"sigcombine") == 0 ) - return(musig_sigcombine(txfee,cp,params)); + else if ( strcmp(method,"partialsig") == 0 ) + return(musig_partialsig(txfee,cp,params)); else if ( strcmp(method,"verify") == 0 ) return(musig_verify(txfee,cp,params)); else if ( strcmp(method,"send") == 0 ) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 7b9510b2a..f6a7bf7b7 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -20,6 +20,7 @@ "combined_pk": "032ddac56613cd0667b589bd7f32b665e2d2ce0247e337a5a0bca6c72e3d9d057b", "result": "success" } + the combined_pk and pkhash will be needed for various other rpc calls */ /* second, send 0.777 coins to the combined_pk @@ -55,6 +56,33 @@ "result": "success", "msg": "63b799913d4c9487f321b32d6ae8614f653f38e0b50d4df4bc1d36339ea18485" } +the "msg" is what needs to be signed to create a valid spend + + now on each signing node, a session needs to be created: + 5 args: ind, numsigners, combined_pk, pkhash, message to be signed + + on node with pubkey: 02aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848 + ./c cclib session 18 \"[0,2,%22032ddac56613cd0667b589bd7f32b665e2d2ce0247e337a5a0bca6c72e3d9d057b%22,%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,%2263b799913d4c9487f321b32d6ae8614f653f38e0b50d4df4bc1d36339ea18485%22]\" + { + "myind": 0, + "numsigners": 2, + "commitment": "053a97ba56b1b8adf174a0a28dc16b1bb4e91a33ca0b52a579ce9ba4af299973", + "result": "success" + } + + on node with pubkey: 039433dc3749aece1bd568f374a45da3b0bc6856990d7da3cd175399577940a775 + ./c cclib session 18 \"[1,2,%22032ddac56613cd0667b589bd7f32b665e2d2ce0247e337a5a0bca6c72e3d9d057b%22,%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,%2263b799913d4c9487f321b32d6ae8614f653f38e0b50d4df4bc1d36339ea18485%22]\" + { + "myind": 1, + "numsigners": 2, + "commitment": "8c8dc6717aaa1994d4a51d1094c0c5cbfaf033c11642dbeeab32a32de4cfbc86", + "result": "success" + } + + now we need to get the commitment from each node to the other one. the session already put the commitment for each node into the global struct. Keep in mind there is a single global struct with session unique to each cclib session call. that means no restarting any deamon in the middle of the process on any of the nodes and only call cclib session a single time. this is an artificial restriction just to simplify the initial implementation of musig + + ./c cclib commitment 18 \"[1,%228c8dc6717aaa1994d4a51d1094c0c5cbfaf033c11642dbeeab32a32de4cfbc86%22]\" + ./c cclib commitment 18 \"[0,%22053a97ba56b1b8adf174a0a28dc16b1bb4e91a33ca0b52a579ce9ba4af299973%22]\" */ @@ -91,9 +119,9 @@ extern "C" int secp256k1_musig_session_initialize(const secp256k1_context* ctx, struct musig_info { - secp256k1_musig_session musig_session; + secp256k1_musig_session session; secp256k1_pubkey combined_pk; - uint8_t *nonce_commitments; // 32*N_SIGNERS + uint8_t *nonce_commitments,**commitment_ptrs; // 32*N_SIGNERS secp256k1_musig_session_signer_data *signer_data; //[N_SIGNERS]; secp256k1_pubkey *nonce; //[N_SIGNERS]; secp256k1_musig_partial_signature *partial_sig; //[N_SIGNERS]; @@ -103,9 +131,12 @@ struct musig_info struct musig_info *musig_infocreate(int32_t myind,int32_t num) { - struct musig_info *mp = (struct musig_info *)calloc(1,sizeof(*mp)); + int32_t i; struct musig_info *mp = (struct musig_info *)calloc(1,sizeof(*mp)); mp->myind = myind, mp->num = num; mp->nonce_commitments = (uint8_t *)calloc(num,32); + mp->commitment_ptrs = (uint8_t **)calloc(num,sizeof(*mp->commitment_ptrs)); + for (i=0; icommitment_ptrs[i] = &mp->nonce_commitments[i*32]; mp->signer_data = (secp256k1_musig_session_signer_data *)calloc(num,sizeof(*mp->signer_data)); mp->nonce = (secp256k1_pubkey *)calloc(num,sizeof(*mp->nonce)); mp->partial_sig = (secp256k1_musig_partial_signature *)calloc(num,sizeof(*mp->partial_sig)); @@ -134,6 +165,11 @@ void musig_infofree(struct musig_info *mp) GetRandBytes((uint8_t *)mp->nonce_commitments,mp->num*32); free(mp->nonce_commitments); } + if ( mp->commitment_ptrs != 0 ) + { + GetRandBytes((uint8_t *)mp->commitment_ptrs,mp->num*sizeof(*mp->commitment_ptrs)); + free(mp->commitment_ptrs); + } GetRandBytes((uint8_t *)mp,sizeof(*mp)); free(mp); } @@ -329,7 +365,7 @@ UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) * my_index: index of this signer in the signers array * seckey: the signer's 32-byte secret key (cannot be NULL) */ - if ( secp256k1_musig_session_initialize(ctx,&MUSIG->musig_session,MUSIG->signer_data, &MUSIG->nonce_commitments[MUSIG->myind * 32],session,MUSIG->msg,&MUSIG->combined_pk,MUSIG->pkhash,MUSIG->num,MUSIG->myind,privkey) > 0 ) + if ( secp256k1_musig_session_initialize(ctx,&MUSIG->session,MUSIG->signer_data, &MUSIG->nonce_commitments[MUSIG->myind * 32],session,MUSIG->msg,&MUSIG->combined_pk,MUSIG->pkhash,MUSIG->num,MUSIG->myind,privkey) > 0 ) { memset(session,0,sizeof(session)); result.push_back(Pair("myind",(int64_t)myind)); @@ -352,14 +388,19 @@ UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue musig_commit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { static secp256k1_context *ctx; - UniValue result(UniValue::VOBJ); int32_t n; + UniValue result(UniValue::VOBJ); int32_t n,ind; uint8_t pkhash[32]; CPubKey pk; char str[67]; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) { - // pkhash, ind, commitment - // if all commitments, emit nonce, else just update MUSIG-> - + if ( musig_parsehash32(pkhash,jitem(params,0)) < 0 ) + return(cclib_error(result,"error parsing pkhash")); + else if ( memcmp(MUSING->pkhash,pkhash,32) != 0 ) + return(cclib_error(result,"pkhash doesnt match session pkhash")); + else if ( (ind= juint(jitem(params,1),0)) < 0 || ind >= MUSIG->num ) + return(cclib_error(result,"illegal ind for session")); + else if ( musig_parsehash32(&MUSIG->commitment[ind*32],jitem(params,2)) < 0 ) + return(cclib_error(result,"error parsing commitment")); /** Gets the signer's public nonce given a list of all signers' data with commitments * * Returns: 1: public nonce is written in nonce @@ -375,27 +416,44 @@ UniValue musig_commit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) * n_commitments: the length of commitments and signers array. Must be the total * number of signers participating in the MuSig. */ - // Set nonce commitments in the signer data and get the own public nonce - //if (secp256k1_musig_session_get_public_nonce(ctx, &musig_session[i], signer_data[i], &nonce[i], nonce_commitment_ptr, N_SIGNERS) > 0 ) + result.push_back(Pair("added_index",ind)); + if ( secp256k1_musig_session_get_public_nonce(ctx,&MUSIG->session,MUSIG->signer_data,&MUSIG->nonces[MUSIG->myind],MUSIG->nonce_commitments,MUSIG->num) > 0 ) { - // publish nonce + if ( secp256k1_ec_pubkey_serialize(ctx,(uint8_t *)pk.begin(),&clen,&MUSIG->nonces[MUSIG->myind],SECP256K1_EC_COMPRESSED) > 0 && clen == 33 ) + { + for (i=0; i<33; i++) + sprintf(&str[i<<1],"%02x",((uint8_t *)pk.begin())[i]); + str[66] = 0; + result.push_back(Pair("nonce",str)); + result.push_back(Pair("result","success")); + } else return(cclib_error(result,"error serializing nonce (pubkey)")); + } + else + { + result.push_back(Pair("status","not enough commitments")); result.push_back(Pair("result","success")); } - // return 0; + return(result); } else return(cclib_error(result,"wrong number of params, need 3: pkhash, ind, commitment")); } UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { static secp256k1_context *ctx; - UniValue result(UniValue::VOBJ); int32_t n; + UniValue result(UniValue::VOBJ); int32_t i,n,ind; uint8_t pkhash[32],psig[32]; CPubKey pk; char str[67]; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); - if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) + if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) { - // pkhash, ind, nonce - // if all nonces, combine nonce, else just update MUSIG-> - result.push_back(Pair("result","success")); + if ( musig_parsehash32(pkhash,jitem(params,0)) < 0 ) + return(cclib_error(result,"error parsing pkhash")); + else if ( memcmp(MUSING->pkhash,pkhash,32) != 0 ) + return(cclib_error(result,"pkhash doesnt match session pkhash")); + else if ( (ind= juint(jitem(params,1),0)) < 0 || ind >= MUSIG->num ) + return(cclib_error(result,"illegal ind for session")); + else if ( musig_parsepubkey(ctx,&MUSIG->nonces[ind],jitem(params,2)) < 0 ) + return(cclib_error(result,"error parsing nonce")); + result.push_back(Pair("added_index",ind)); /** Checks a signer's public nonce against a commitment to said nonce, and update * data structure if they match * @@ -407,9 +465,11 @@ UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) * with `musig_session_initialize_verifier`. * In: nonce: signer's alleged public nonce (cannot be NULL) */ - //if (!secp256k1_musig_set_nonce(ctx, &signer_data[i][j], &nonce[j])) { - - + for (i=0; inum; i++) + { + if ( secp256k1_musig_set_nonce(ctx,&MUSIG->signer_data[i],&MUSIG->nonces[i]) == 0 ) + return(cclib_error(result,"error setting nonce")); + } /** Updates a session with the combined public nonce of all signers. The combined * public nonce is the sum of every signer's public nonce. * @@ -428,91 +488,68 @@ UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) * adaptor: point to add to the combined public nonce. If NULL, nothing is * added to the combined nonce. */ - // after all nonces: if (!secp256k1_musig_session_combine_nonces(ctx, &musig_session[i], signer_data[i], N_SIGNERS, NULL, NULL)) { - return(result); + if ( secp256k1_musig_session_combine_nonces(ctx,&MUSIG->session,MUSIG->signer_data,MUSIG->num,NULL,NULL) > 0 ) + { + if ( secp256k1_musig_partial_sign(ctx,&MUSIG->session,&MUSIG->partial_sig[MUSIG->myind]) > 0 ) + { + if ( secp256k1_musig_partial_signature_serialize(ctx,psig,&MUSIG->partial_sig[MUSIG->myind]) > 0 ) + { + result.push_back(Pair("myind",ind)); + for (i=0; i<32; i++) + sprintf(&str[i<<1],"%02x",psig[i]); + str[64] = 0; + result.push_back(Pair("partialsig",str)); + result.push_back(Pair("result","success")); + return(result); + } else return(cclib_error(result,"error serializing partial sig")); + } else return(cclib_error(result,"error making partial sig")); + } else return(cclib_error(result,"error combining nonces")); } else return(cclib_error(result,"wrong number of params, need 3: pkhash, ind, nonce")); } -UniValue musig_partialsign(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +UniValue musig_partialsig(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { static secp256k1_context *ctx; - UniValue result(UniValue::VOBJ); int32_t n; + UniValue result(UniValue::VOBJ); int32_t ind,n; uint8_t pkhash[32],psig[32],out64[64]; char str[129]; secp256k1_schnorrsig sig; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); - if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) + if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) { - // similar to commit/nonce - } - result.push_back(Pair("result","success")); - /** Produces a partial signature - * - * Returns: 1: partial signature constructed - * 0: session in incorrect or inconsistent state - * Args: ctx: pointer to a context object (cannot be NULL) - * session: active signing session for which the combined nonce has been - * computed (cannot be NULL) - * Out: partial_sig: partial signature (cannot be NULL) - */ - //if (!secp256k1_musig_partial_sign(ctx, &musig_session[i], &partial_sig[i])) { - /** Parse and verify a MuSig partial signature. - * - * Returns: 1 when the signature could be parsed, 0 otherwise. - * Args: ctx: a secp256k1 context object - * Out: sig: pointer to a signature object - * In: in32: pointer to the 32-byte signature to be parsed - * - * After the call, sig will always be initialized. If parsing failed or the - * encoded numbers are out of range, signature verification with it is - * guaranteed to fail for every message and public key. - */ - //SECP256K1_API int secp256k1_musig_partial_signature_parse( - - return(result); -} - -UniValue musig_sigcombine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) -{ - static secp256k1_context *ctx; - UniValue result(UniValue::VOBJ); int32_t n; - if ( ctx == 0 ) - ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); - if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) - { - // finally! - } - result.push_back(Pair("result","success")); - /** Checks that an individual partial signature verifies - * - * This function is essential when using protocols with adaptor signatures. - * However, it is not essential for regular MuSig's, in the sense that if any - * partial signatures does not verify, the full signature will also not verify, so the - * problem will be caught. But this function allows determining the specific party - * who produced an invalid signature, so that signing can be restarted without them. - * - * Returns: 1: partial signature verifies - * 0: invalid signature or bad data - * Args: ctx: pointer to a context object (cannot be NULL) - * session: active session for which the combined nonce has been computed - * (cannot be NULL) - * signer: data for the signer who produced this signature (cannot be NULL) - * In: partial_sig: signature to verify (cannot be NULL) - * pubkey: public key of the signer who produced the signature (cannot be NULL) - */ - //if (!secp256k1_musig_partial_sig_verify(ctx, &musig_session[i], &signer_data[i][j], &partial_sig[j], &pubkeys[j])) { - return 0; - /** Combines partial signatures - * - * Returns: 1: all partial signatures have values in range. Does NOT mean the - * resulting signature verifies. - * 0: some partial signature had s/r out of range - * Args: ctx: pointer to a context object (cannot be NULL) - * session: initialized session for which the combined nonce has been - * computed (cannot be NULL) - * Out: sig: complete signature (cannot be NULL) - * In: partial_sigs: array of partial signatures to combine (cannot be NULL) - * n_sigs: number of signatures in the partial_sigs array - */ - // after all partials: return secp256k1_musig_partial_sig_combine(ctx, &musig_session[0], sig, partial_sig, N_SIGNERS return(result); + if ( musig_parsehash32(pkhash,jitem(params,0)) < 0 ) + return(cclib_error(result,"error parsing pkhash")); + else if ( memcmp(MUSING->pkhash,pkhash,32) != 0 ) + return(cclib_error(result,"pkhash doesnt match session pkhash")); + else if ( (ind= juint(jitem(params,1),0)) < 0 || ind >= MUSIG->num ) + return(cclib_error(result,"illegal ind for session")); + else if ( musig_parsepartial(ctx,&MUSIG->partial_sig[ind],jitem(params,2)) < 0 ) + return(cclib_error(result,"error parsing partialsig")); + result.push_back(Pair("added_index",ind)); + if (secp256k1_musig_partial_sig_combine(ctx,&MUSIG->session,&sig,MUSIG->partial_sig,MUSIG->num) > 0 ) + { + if ( secp256k1_schnorrsig_serialize(ctx,out64,&sig) > 0 ) + { + result.push_back(Pair("result","success")); + for (i=0; i<64; i++) + sprintf(&str[i<<1],"%02x",out64[i]); + str[128] = 0; + result.push_back(Pair("combinedsig",str)); + } else return(cclib_error(result,"error serializing combinedsig")); + } + else + { + if ( secp256k1_musig_partial_signature_serialize(ctx,psig,&MUSIG->partial_sig[MUSIG->myind]) > 0 ) + { + result.push_back(Pair("myind",ind)); + for (i=0; i<32; i++) + sprintf(&str[i<<1],"%02x",psig[i]); + str[64] = 0; + result.push_back(Pair("partialsig",str)); + result.push_back(Pair("result","success")); + result.push_back(Pair("status","need more partialsigs")); + } else return(cclib_error(result,"error generating my partialsig")); + } + return(result); + } else return(cclib_error(result,"wrong number of params, need 3: pkhash, ind, partialsig")); } UniValue musig_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) diff --git a/src/secp256k1/include/secp256k1_musig.h b/src/secp256k1/include/secp256k1_musig.h index a0106e691..84106822a 100644 --- a/src/secp256k1/include/secp256k1_musig.h +++ b/src/secp256k1/include/secp256k1_musig.h @@ -206,7 +206,12 @@ SECP256K1_API * n_commitments: the length of commitments and signers array. Must be the total * number of signers participating in the MuSig. */ -SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_session_get_public_nonce( +#ifdef __cplusplus +extern "C" +#else +SECP256K1_API +#endif + SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_session_get_public_nonce( const secp256k1_context* ctx, secp256k1_musig_session *session, secp256k1_musig_session_signer_data *signers, @@ -235,7 +240,12 @@ SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_session_get_publi * participating in the MuSig. Must be greater than 0 and at most * 2^32 - 1. */ -SECP256K1_API int secp256k1_musig_session_initialize_verifier( +#ifdef __cplusplus +extern "C" +#else +SECP256K1_API +#endif + int secp256k1_musig_session_initialize_verifier( const secp256k1_context* ctx, secp256k1_musig_session *session, secp256k1_musig_session_signer_data *signers, @@ -257,7 +267,12 @@ SECP256K1_API int secp256k1_musig_session_initialize_verifier( * with `musig_session_initialize_verifier`. * In: nonce: signer's alleged public nonce (cannot be NULL) */ -SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_set_nonce( +#ifdef __cplusplus +extern "C" +#else +SECP256K1_API +#endif + SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_set_nonce( const secp256k1_context* ctx, secp256k1_musig_session_signer_data *signer, const secp256k1_pubkey *nonce @@ -281,7 +296,12 @@ SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_set_nonce( * adaptor: point to add to the combined public nonce. If NULL, nothing is * added to the combined nonce. */ -SECP256K1_API int secp256k1_musig_session_combine_nonces( +#ifdef __cplusplus +extern "C" +#else +SECP256K1_API +#endif + int secp256k1_musig_session_combine_nonces( const secp256k1_context* ctx, secp256k1_musig_session *session, const secp256k1_musig_session_signer_data *signers, @@ -298,7 +318,12 @@ SECP256K1_API int secp256k1_musig_session_combine_nonces( * session: the session structure to update with the message (cannot be NULL) * In: msg32: the 32-byte message to be signed (cannot be NULL) */ -SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_session_set_msg( +#ifdef __cplusplus +extern "C" +#else +SECP256K1_API +#endif + SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_session_set_msg( const secp256k1_context* ctx, secp256k1_musig_session *session, const unsigned char *msg32 @@ -311,7 +336,12 @@ SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_session_set_msg( * Out: out32: pointer to a 32-byte array to store the serialized signature * In: sig: pointer to the signature */ -SECP256K1_API int secp256k1_musig_partial_signature_serialize( +#ifdef __cplusplus +extern "C" +#else +SECP256K1_API +#endif + int secp256k1_musig_partial_signature_serialize( const secp256k1_context* ctx, unsigned char *out32, const secp256k1_musig_partial_signature* sig @@ -328,7 +358,12 @@ SECP256K1_API int secp256k1_musig_partial_signature_serialize( * encoded numbers are out of range, signature verification with it is * guaranteed to fail for every message and public key. */ -SECP256K1_API int secp256k1_musig_partial_signature_parse( +#ifdef __cplusplus +extern "C" +#else +SECP256K1_API +#endif + int secp256k1_musig_partial_signature_parse( const secp256k1_context* ctx, secp256k1_musig_partial_signature* sig, const unsigned char *in32 @@ -343,7 +378,12 @@ SECP256K1_API int secp256k1_musig_partial_signature_parse( * computed (cannot be NULL) * Out: partial_sig: partial signature (cannot be NULL) */ -SECP256K1_API int secp256k1_musig_partial_sign( +#ifdef __cplusplus +extern "C" +#else +SECP256K1_API +#endif + int secp256k1_musig_partial_sign( const secp256k1_context* ctx, const secp256k1_musig_session *session, secp256k1_musig_partial_signature *partial_sig @@ -366,7 +406,12 @@ SECP256K1_API int secp256k1_musig_partial_sign( * In: partial_sig: signature to verify (cannot be NULL) * pubkey: public key of the signer who produced the signature (cannot be NULL) */ -SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_partial_sig_verify( +#ifdef __cplusplus +extern "C" +#else +SECP256K1_API +#endif + SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_partial_sig_verify( const secp256k1_context* ctx, const secp256k1_musig_session *session, const secp256k1_musig_session_signer_data *signer, @@ -386,7 +431,12 @@ SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_partial_sig_verif * In: partial_sigs: array of partial signatures to combine (cannot be NULL) * n_sigs: number of signatures in the partial_sigs array */ -SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_partial_sig_combine( +#ifdef __cplusplus +extern "C" +#else +SECP256K1_API +#endif + SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_partial_sig_combine( const secp256k1_context* ctx, const secp256k1_musig_session *session, secp256k1_schnorrsig *sig, @@ -406,7 +456,12 @@ SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_partial_sig_combi * be NULL) * nonce_is_negated: the `nonce_is_negated` output of `musig_session_combine_nonces` */ -SECP256K1_API int secp256k1_musig_partial_sig_adapt( +#ifdef __cplusplus +extern "C" +#else +SECP256K1_API +#endif + int secp256k1_musig_partial_sig_adapt( const secp256k1_context* ctx, secp256k1_musig_partial_signature *adaptor_sig, const secp256k1_musig_partial_signature *partial_sig, @@ -429,7 +484,12 @@ SECP256K1_API int secp256k1_musig_partial_sig_adapt( * n_partial_sigs: number of elements in partial_sigs array * nonce_is_negated: the `nonce_is_negated` output of `musig_session_combine_nonces` */ -SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_extract_secret_adaptor( +#ifdef __cplusplus +extern "C" +#else +SECP256K1_API +#endif + SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_extract_secret_adaptor( const secp256k1_context* ctx, unsigned char *sec_adaptor32, const secp256k1_schnorrsig *sig, diff --git a/src/secp256k1/include/secp256k1_schnorrsig.h b/src/secp256k1/include/secp256k1_schnorrsig.h index 9dea16653..e4d02f34f 100644 --- a/src/secp256k1/include/secp256k1_schnorrsig.h +++ b/src/secp256k1/include/secp256k1_schnorrsig.h @@ -28,7 +28,12 @@ typedef struct { * * See secp256k1_schnorrsig_parse for details about the encoding. */ -SECP256K1_API int secp256k1_schnorrsig_serialize( +#ifdef __cplusplus +extern "C" +#else +SECP256K1_API +#endif +int secp256k1_schnorrsig_serialize( const secp256k1_context* ctx, unsigned char *out64, const secp256k1_schnorrsig* sig @@ -50,7 +55,12 @@ SECP256K1_API int secp256k1_schnorrsig_serialize( * encoded numbers are out of range, signature validation with it is * guaranteed to fail for every message and public key. */ -SECP256K1_API int secp256k1_schnorrsig_parse( +#ifdef __cplusplus +extern "C" +#else +SECP256K1_API +#endif +int secp256k1_schnorrsig_parse( const secp256k1_context* ctx, secp256k1_schnorrsig* sig, const unsigned char *in64 From 141790634d27cc0461329d2261859c54ec3bebfa Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 23:33:13 -1100 Subject: [PATCH 292/390] Syntax --- src/cc/musig.cpp | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index f6a7bf7b7..8696809da 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -123,7 +123,7 @@ struct musig_info secp256k1_pubkey combined_pk; uint8_t *nonce_commitments,**commitment_ptrs; // 32*N_SIGNERS secp256k1_musig_session_signer_data *signer_data; //[N_SIGNERS]; - secp256k1_pubkey *nonce; //[N_SIGNERS]; + secp256k1_pubkey *nonces; //[N_SIGNERS]; secp256k1_musig_partial_signature *partial_sig; //[N_SIGNERS]; int32_t myind,num; uint8_t msg[32],pkhash[32],combpk[33]; @@ -138,7 +138,7 @@ struct musig_info *musig_infocreate(int32_t myind,int32_t num) for (i=0; icommitment_ptrs[i] = &mp->nonce_commitments[i*32]; mp->signer_data = (secp256k1_musig_session_signer_data *)calloc(num,sizeof(*mp->signer_data)); - mp->nonce = (secp256k1_pubkey *)calloc(num,sizeof(*mp->nonce)); + mp->nonces = (secp256k1_pubkey *)calloc(num,sizeof(*mp->nonces)); mp->partial_sig = (secp256k1_musig_partial_signature *)calloc(num,sizeof(*mp->partial_sig)); return(mp); } @@ -150,10 +150,10 @@ void musig_infofree(struct musig_info *mp) GetRandBytes((uint8_t *)mp->partial_sig,mp->num*sizeof(*mp->partial_sig)); free(mp->partial_sig); } - if ( mp->nonce != 0 ) + if ( mp->nonces != 0 ) { - GetRandBytes((uint8_t *)mp->nonce,mp->num*sizeof(*mp->nonce)); - free(mp->nonce); + GetRandBytes((uint8_t *)mp->nonces,mp->num*sizeof(*mp->nonces)); + free(mp->nonces); } if ( mp->signer_data != 0 ) { @@ -388,14 +388,14 @@ UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue musig_commit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { static secp256k1_context *ctx; - UniValue result(UniValue::VOBJ); int32_t n,ind; uint8_t pkhash[32]; CPubKey pk; char str[67]; + UniValue result(UniValue::VOBJ); int32_t i,n,ind; uint8_t pkhash[32]; CPubKey pk; char str[67]; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) { if ( musig_parsehash32(pkhash,jitem(params,0)) < 0 ) return(cclib_error(result,"error parsing pkhash")); - else if ( memcmp(MUSING->pkhash,pkhash,32) != 0 ) + else if ( memcmp(MUSIG->pkhash,pkhash,32) != 0 ) return(cclib_error(result,"pkhash doesnt match session pkhash")); else if ( (ind= juint(jitem(params,1),0)) < 0 || ind >= MUSIG->num ) return(cclib_error(result,"illegal ind for session")); @@ -424,6 +424,7 @@ UniValue musig_commit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) for (i=0; i<33; i++) sprintf(&str[i<<1],"%02x",((uint8_t *)pk.begin())[i]); str[66] = 0; + result.push_back(Pair("myind",MUSIG->myind)); result.push_back(Pair("nonce",str)); result.push_back(Pair("result","success")); } else return(cclib_error(result,"error serializing nonce (pubkey)")); @@ -447,7 +448,7 @@ UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { if ( musig_parsehash32(pkhash,jitem(params,0)) < 0 ) return(cclib_error(result,"error parsing pkhash")); - else if ( memcmp(MUSING->pkhash,pkhash,32) != 0 ) + else if ( memcmp(MUSIG->pkhash,pkhash,32) != 0 ) return(cclib_error(result,"pkhash doesnt match session pkhash")); else if ( (ind= juint(jitem(params,1),0)) < 0 || ind >= MUSIG->num ) return(cclib_error(result,"illegal ind for session")); @@ -498,6 +499,7 @@ UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) for (i=0; i<32; i++) sprintf(&str[i<<1],"%02x",psig[i]); str[64] = 0; + result.push_back(Pair("myind",MUSIG->myind)); result.push_back(Pair("partialsig",str)); result.push_back(Pair("result","success")); return(result); @@ -510,14 +512,14 @@ UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue musig_partialsig(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { static secp256k1_context *ctx; - UniValue result(UniValue::VOBJ); int32_t ind,n; uint8_t pkhash[32],psig[32],out64[64]; char str[129]; secp256k1_schnorrsig sig; + UniValue result(UniValue::VOBJ); int32_t i,ind,n; uint8_t pkhash[32],psig[32],out64[64]; char str[129]; secp256k1_schnorrsig sig; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) { if ( musig_parsehash32(pkhash,jitem(params,0)) < 0 ) return(cclib_error(result,"error parsing pkhash")); - else if ( memcmp(MUSING->pkhash,pkhash,32) != 0 ) + else if ( memcmp(MUSIG->pkhash,pkhash,32) != 0 ) return(cclib_error(result,"pkhash doesnt match session pkhash")); else if ( (ind= juint(jitem(params,1),0)) < 0 || ind >= MUSIG->num ) return(cclib_error(result,"illegal ind for session")); From 3d99ab8a66a0de574abfd066ff6980390734f860 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 23:39:37 -1100 Subject: [PATCH 293/390] Fix --- src/cc/musig.cpp | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 8696809da..2d4002059 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -388,6 +388,7 @@ UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue musig_commit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { static secp256k1_context *ctx; + size_t clen = CPubKey::PUBLIC_KEY_SIZE; UniValue result(UniValue::VOBJ); int32_t i,n,ind; uint8_t pkhash[32]; CPubKey pk; char str[67]; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); @@ -399,7 +400,7 @@ UniValue musig_commit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) return(cclib_error(result,"pkhash doesnt match session pkhash")); else if ( (ind= juint(jitem(params,1),0)) < 0 || ind >= MUSIG->num ) return(cclib_error(result,"illegal ind for session")); - else if ( musig_parsehash32(&MUSIG->commitment[ind*32],jitem(params,2)) < 0 ) + else if ( musig_parsehash32(&MUSIG->nonce_commitments[ind*32],jitem(params,2)) < 0 ) return(cclib_error(result,"error parsing commitment")); /** Gets the signer's public nonce given a list of all signers' data with commitments * @@ -417,7 +418,7 @@ UniValue musig_commit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) * number of signers participating in the MuSig. */ result.push_back(Pair("added_index",ind)); - if ( secp256k1_musig_session_get_public_nonce(ctx,&MUSIG->session,MUSIG->signer_data,&MUSIG->nonces[MUSIG->myind],MUSIG->nonce_commitments,MUSIG->num) > 0 ) + if ( secp256k1_musig_session_get_public_nonce(ctx,&MUSIG->session,MUSIG->signer_data,&MUSIG->nonces[MUSIG->myind],MUSIG->commitment_ptrs,MUSIG->num) > 0 ) { if ( secp256k1_ec_pubkey_serialize(ctx,(uint8_t *)pk.begin(),&clen,&MUSIG->nonces[MUSIG->myind],SECP256K1_EC_COMPRESSED) > 0 && clen == 33 ) { @@ -452,7 +453,7 @@ UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) return(cclib_error(result,"pkhash doesnt match session pkhash")); else if ( (ind= juint(jitem(params,1),0)) < 0 || ind >= MUSIG->num ) return(cclib_error(result,"illegal ind for session")); - else if ( musig_parsepubkey(ctx,&MUSIG->nonces[ind],jitem(params,2)) < 0 ) + else if ( musig_parsepubkey(ctx,MUSIG->nonces[ind],jitem(params,2)) < 0 ) return(cclib_error(result,"error parsing nonce")); result.push_back(Pair("added_index",ind)); /** Checks a signer's public nonce against a commitment to said nonce, and update @@ -523,7 +524,9 @@ UniValue musig_partialsig(uint64_t txfee,struct CCcontract_info *cp,cJSON *param return(cclib_error(result,"pkhash doesnt match session pkhash")); else if ( (ind= juint(jitem(params,1),0)) < 0 || ind >= MUSIG->num ) return(cclib_error(result,"illegal ind for session")); - else if ( musig_parsepartial(ctx,&MUSIG->partial_sig[ind],jitem(params,2)) < 0 ) + else if ( musig_parsehash32(ctx,psig,jitem(params,2)) < 0 ) + return(cclib_error(result,"error parsing psig")); + else if ( secp256k1_musig_partial_signature_parse(ctx,&MUSIG->partial_sig[ind],psig) == 0 ) return(cclib_error(result,"error parsing partialsig")); result.push_back(Pair("added_index",ind)); if (secp256k1_musig_partial_sig_combine(ctx,&MUSIG->session,&sig,MUSIG->partial_sig,MUSIG->num) > 0 ) From b17065ce1762782a13ab6205c06bd20df5a644ba Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 23:41:10 -1100 Subject: [PATCH 294/390] extern "C" --- src/cc/musig.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 2d4002059..03eb01e3e 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -113,6 +113,7 @@ extern "C" int secp256k1_schnorrsig_verify(const secp256k1_context* ctx, const s extern "C" int secp256k1_schnorrsig_parse(const secp256k1_context* ctx, secp256k1_schnorrsig* sig, const unsigned char *in64); extern "C" int secp256k1_musig_pubkey_combine(const secp256k1_context* ctx, secp256k1_scratch_space *scratch, secp256k1_pubkey *combined_pk, unsigned char *pk_hash32, const secp256k1_pubkey *pubkeys, size_t n_pubkeys); extern "C" int secp256k1_musig_session_initialize(const secp256k1_context* ctx, secp256k1_musig_session *session, secp256k1_musig_session_signer_data *signers, unsigned char *nonce_commitment32, const unsigned char *session_id32, const unsigned char *msg32, const secp256k1_pubkey *combined_pk, const unsigned char *pk_hash32, size_t n_signers, size_t my_index, const unsigned char *seckey); +extern "C" int secp256k1_schnorrsig_serialize(const secp256k1_context* ctx, unsigned char *out64, const secp256k1_schnorrsig* sig); #define MUSIG_PREVN 0 // for now, just use vout0 for the musig output #define MUSIG_TXFEE 10000 @@ -524,12 +525,12 @@ UniValue musig_partialsig(uint64_t txfee,struct CCcontract_info *cp,cJSON *param return(cclib_error(result,"pkhash doesnt match session pkhash")); else if ( (ind= juint(jitem(params,1),0)) < 0 || ind >= MUSIG->num ) return(cclib_error(result,"illegal ind for session")); - else if ( musig_parsehash32(ctx,psig,jitem(params,2)) < 0 ) + else if ( musig_parsehash32(psig,jitem(params,2)) < 0 ) return(cclib_error(result,"error parsing psig")); else if ( secp256k1_musig_partial_signature_parse(ctx,&MUSIG->partial_sig[ind],psig) == 0 ) return(cclib_error(result,"error parsing partialsig")); result.push_back(Pair("added_index",ind)); - if (secp256k1_musig_partial_sig_combine(ctx,&MUSIG->session,&sig,MUSIG->partial_sig,MUSIG->num) > 0 ) + if ( secp256k1_musig_partial_sig_combine(ctx,&MUSIG->session,&sig,MUSIG->partial_sig,MUSIG->num) > 0 ) { if ( secp256k1_schnorrsig_serialize(ctx,out64,&sig) > 0 ) { From c07c6724b2d05dac81104b69a53f8fc23c49b845 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 23:52:20 -1100 Subject: [PATCH 295/390] Rpc examples to make a combined signature "combinedsig": "bc0062cd3233433e098fbf4f3c333946779c3dccfaefc423243e3f90edfdf9a6dbfabf4 2d26f3c668fe6e10f1ed367a46dfddbafaee82b3eb79722ae49f45320" --- src/cc/musig.cpp | 67 ++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 62 insertions(+), 5 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 03eb01e3e..4f08dd4cf 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -66,7 +66,7 @@ the "msg" is what needs to be signed to create a valid spend { "myind": 0, "numsigners": 2, - "commitment": "053a97ba56b1b8adf174a0a28dc16b1bb4e91a33ca0b52a579ce9ba4af299973", + "commitment": "89af8f6db69fc3d4b95480a914dceba9933039e9823151a82677c3ca4e961fcc", "result": "success" } @@ -75,15 +75,73 @@ the "msg" is what needs to be signed to create a valid spend { "myind": 1, "numsigners": 2, - "commitment": "8c8dc6717aaa1994d4a51d1094c0c5cbfaf033c11642dbeeab32a32de4cfbc86", + "commitment": "a43da5ef8322abb43b9fddadef7b6479baf7853e860f915e01521e3060e5342b", "result": "success" } now we need to get the commitment from each node to the other one. the session already put the commitment for each node into the global struct. Keep in mind there is a single global struct with session unique to each cclib session call. that means no restarting any deamon in the middle of the process on any of the nodes and only call cclib session a single time. this is an artificial restriction just to simplify the initial implementation of musig - ./c cclib commitment 18 \"[1,%228c8dc6717aaa1994d4a51d1094c0c5cbfaf033c11642dbeeab32a32de4cfbc86%22]\" - ./c cclib commitment 18 \"[0,%22053a97ba56b1b8adf174a0a28dc16b1bb4e91a33ca0b52a579ce9ba4af299973%22]\" + ./c cclib commit 18 \"[%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,1,%22a43da5ef8322abb43b9fddadef7b6479baf7853e860f915e01521e3060e5342b%22]\" + { + "added_index": 1, + "myind": 0, + "nonce": "03bf28874f5e5dccf55170406d58ded84ac6ca713011d718c6048400d700cb879a", + "result": "success" + } + + ./c cclib commit 18 \"[%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,0,%2289af8f6db69fc3d4b95480a914dceba9933039e9823151a82677c3ca4e961fcc%22]\" + { + "added_index": 0, + "myind": 1, + "nonce": "039ae1f542e8f0f6d03d734dc2295651973e1b7fa99508e2f36dad5d21f09889f6", + "result": "success" + } + + Now exchange the revealed nonces to each node: + + ./c cclib nonce 18 \"[%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,1,%22039ae1f542e8f0f6d03d734dc2295651973e1b7fa99508e2f36dad5d21f09889f6%22]\" + { + "added_index": 1, + "myind": 0, + "partialsig": "5da4c1ec828cd1563bc6554aa74c90c29fcd38b2aea26f7fa92e0d007aa9463f", + "result": "success" + } + + ./c cclib nonce 18 \"[%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,0,%2203bf28874f5e5dccf55170406d58ded84ac6ca713011d718c6048400d700cb879a%22]\" + { + "added_index": 0, + "myind": 1, + "partialsig": "7e55fd564fe26b1054208bc47786d6e1ce30a2fd0045bbbf0e6915adcf4b0ce1", + "result": "success" + } + + Almost there! final step is to exchange the partial sigs between signers + ./c cclib partialsig 18 \"[%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,1,%227e55fd564fe26b1054208bc47786d6e1ce30a2fd0045bbbf0e6915adcf4b0ce1%22]\" + { + "added_index": 1, + "result": "success", + "combinedsig": "bc0062cd3233433e098fbf4f3c333946779c3dccfaefc423243e3f90edfdf9a6dbfabf42d26f3c668fe6e10f1ed367a46dfddbafaee82b3eb79722ae49f45320" + } + + ./c cclib partialsig 18 \"[%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,0,%225da4c1ec828cd1563bc6554aa74c90c29fcd38b2aea26f7fa92e0d007aa9463f%22]\" + + { + "added_index": 0, + "result": "success", + "combinedsig": "bc0062cd3233433e098fbf4f3c333946779c3dccfaefc423243e3f90edfdf9a6dbfabf42d26f3c668fe6e10f1ed367a46dfddbafaee82b3eb79722ae49f45320" + } + + Notice both nodes generated the same combined signature! + + Now for a sanity test, we can use the verify call to make sure this sig will work with the msg needed for the spend: + + xxxx + + + and finally the spend: + + */ @@ -497,7 +555,6 @@ UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { if ( secp256k1_musig_partial_signature_serialize(ctx,psig,&MUSIG->partial_sig[MUSIG->myind]) > 0 ) { - result.push_back(Pair("myind",ind)); for (i=0; i<32; i++) sprintf(&str[i<<1],"%02x",psig[i]); str[64] = 0; From 925eaa285162afaeed9396aced6413ed38c61a62 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 23:57:30 -1100 Subject: [PATCH 296/390] Test --- src/cc/musig.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 4f08dd4cf..6b2e7abca 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -139,9 +139,9 @@ the "msg" is what needs to be signed to create a valid spend xxxx - and finally the spend: - + and finally the spend: sendtxid, scriptPubKey, musig +./c cclib spend 18 \"[%22cb5309ed249da95e2b5696eb763a8736e2fff1d14922ada737b931494ca3d2be%22,%222102aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848ac%22,%22bc0062cd3233433e098fbf4f3c333946779c3dccfaefc423243e3f90edfdf9a6dbfabf42d26f3c668fe6e10f1ed367a46dfddbafaee82b3eb79722ae49f45320%22]\" */ @@ -696,6 +696,7 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) prevhash = juint256(jitem(params,0)); scriptstr = jstr(jitem(params,1),0); musigstr = jstr(jitem(params,2),0); + printf("script.(%s) musig.(%s) %d\n",scriptstr,musigstr,(int32_t)strlen(musigstr)); if ( is_hexstr(scriptstr,0) != 0 && is_hexstr(musigstr,0) != 128 ) { if ( txfee == 0 ) @@ -723,7 +724,7 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) } else return(cclib_error(result,"couldnt decode send opret")); } else return(cclib_error(result,"couldnt find vin0")); } else return(cclib_error(result,"script or musig is not hex")); - } else return(cclib_error(result,"need to have exactly 3 params prevhash, scriptPubKey, musig")); + } else return(cclib_error(result,"need to have exactly 3 params sendtxid, scriptPubKey, musig")); } else return(cclib_error(result,"params parse error")); } From 748ab667e2d36b71c29d943b855d7dbbc07abd86 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 23:59:42 -1100 Subject: [PATCH 297/390] Test --- src/cc/musig.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 6b2e7abca..172958fba 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -696,7 +696,7 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) prevhash = juint256(jitem(params,0)); scriptstr = jstr(jitem(params,1),0); musigstr = jstr(jitem(params,2),0); - printf("script.(%s) musig.(%s) %d\n",scriptstr,musigstr,(int32_t)strlen(musigstr)); + printf("script.(%s) %d musig.(%s) %d\n",scriptstr,is_hexstr(scriptstr,0),musigstr,is_hexstr(musigstr,0)); if ( is_hexstr(scriptstr,0) != 0 && is_hexstr(musigstr,0) != 128 ) { if ( txfee == 0 ) From 3bea6f84e4c353df73316e8079e516a903461516 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 22 Feb 2019 00:00:55 -1100 Subject: [PATCH 298/390] Fix --- src/cc/musig.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 172958fba..a690e4d01 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -696,8 +696,7 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) prevhash = juint256(jitem(params,0)); scriptstr = jstr(jitem(params,1),0); musigstr = jstr(jitem(params,2),0); - printf("script.(%s) %d musig.(%s) %d\n",scriptstr,is_hexstr(scriptstr,0),musigstr,is_hexstr(musigstr,0)); - if ( is_hexstr(scriptstr,0) != 0 && is_hexstr(musigstr,0) != 128 ) + if ( is_hexstr(scriptstr,0) != 0 && is_hexstr(musigstr,0) == 128 ) { if ( txfee == 0 ) txfee = MUSIG_TXFEE; From 33811cce5f78616998d2b7fe1a75714d028fae23 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 22 Feb 2019 00:16:26 -1100 Subject: [PATCH 299/390] +print --- src/cc/musig.cpp | 64 ++++++++++++++++++++++++++++++------------------ 1 file changed, 40 insertions(+), 24 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index a690e4d01..be4ff278e 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -26,8 +26,8 @@ /* second, send 0.777 coins to the combined_pk ./c cclib send 18 \"[%22032ddac56613cd0667b589bd7f32b665e2d2ce0247e337a5a0bca6c72e3d9d057b%22,0.777]\" { - "hex": "0400008085202f8901bf7afcbbab7a5e1ba20c8010325e199305afa7d15b4bc86a589a512201d39924000000004847304402203e0cff8aaa831dd990afd979bbc0a648316f77407cb5e02780d18e0670f5172a0220283d5c52d0406b10c508cc2b19dd6dbe2420e7c5cf431a1d41072d0eec28edb901ffffffff03b0c2a10400000000302ea22c8020c71ddb3aac7f9b9e4bdacf032aaa8b8e4433c4ff9f8a43cebb9c1f5da96928a48103120c008203000401cca91e223700000000232102aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848ac0000000000000000266a24127821032ddac56613cd0667b589bd7f32b665e2d2ce0247e337a5a0bca6c72e3d9d057b00000000900000000000000000000000000000", - "txid": "cb5309ed249da95e2b5696eb763a8736e2fff1d14922ada737b931494ca3d2be", + "hex": "0400008085202f8908018bbc4a0acf0f896680b84cc1000ec5530042fa3cf7471ab5c11cde56f6d0e60000000048473044022041a900fa57e54f939b797d09f0cee81ab9a79d978cd473ef3fc9f09c7678ad6b02206386bd15ee7ee8224a984fdd1d2a094738d082aec06028a5846d7bc61ddf16ca01ffffffff0b969f0e1ea787f0cc4e81d128353bd1cb670ab89bd1db4b47fbb7e872cd39fb00000000494830450221008c5de4b196e57b0dd94aa415950adf274e3e6859b82cf218729af84c1f15e76c022024aeab7eda63e6a652ef488bf26a8dc4ef8d2d4aa5746726085bfe5f169a5db701ffffffff0b36b70b43457fab377f28fb22da5a3e9d8186a37daae18cf0f710a221ab26250000000048473044022004ec20ae7490e7adabf9a3f78e4a58df84a3245485bfdd40f421cafe61d19c340220456d2b6f3c6e88632027c02606a0af1c21208d05f2de0826fbf4dfe7391ec83901ffffffff0aaff3cfe4ca22b97b6179a6f7cfac91945e5440e9438b89d1ec09500167176a0000000048473044022074dcad30c8ab9ed79a3ac69169611fc9e5f4b76a561b183461d968249316997f022063b25decaa285f494d277b9c8c2bcf6445b7929a304542e89c0645828d30a1a901ffffffff090e1bb92e9bf404a0d6455701b21af3dbf6765e61a1dc28b7c0f608ec4f12da000000004847304402202f9182c532c66138a6bdfcbb85a06cf1bf1532f2bf8f63170ef20843e4a81d0202207612a4353eb9606e84621c444ec7db1b683ff29c56127bda2d5e9c0eb13dbbc001ffffffff08a57005c7a40a923b1a510820b07f7318d760fe2a233b077d918cce357ad3af00000000484730440220643d60c68634fb2e0f6656389fc70c9f84c7086fc6e35b0fa26297e844f6c5fc02201d79669e073efe738d47de0130fdcba875e284e18fd478c0e6834d46632d8b8101ffffffff068cfd0ea6c0f5d401c67ec38f92425a9e59b0d5ade55bb2971ea955675a17bd00000000484730440220747139724248da4bcc1e5e3828e0ea811756e1fad0ebc40aeb006fd8079d46e402200d8f1c229c79494b5617e4373a3e083966dcd74571323f9d334be901d53871fa01ffffffff0200382fb6984b6128bb75115346242809c6555274e0cacef822825a2b4d231700000000484730440220454fcac398f6913fb4d8ed330f110f9cf62eec6c8cdb67d5df1effd2cf8222d5022017f6323630669777573e342e870c88727a917cc06c33611ebbd9d1fccc1dcd3701ffffffff03b0c2a10400000000302ea22c8020c71ddb3aac7f9b9e4bdacf032aaa8b8e4433c4ff9f8a43cebb9c1f5da96928a48103120c008203000401cc40ca220000000000232102aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848ac0000000000000000266a24127821032ddac56613cd0667b589bd7f32b665e2d2ce0247e337a5a0bca6c72e3d9d057b00000000460100000000000000000000000000", + "txid": "2c4159bb19212dcaa412ae37de7d72398f063194053e04a65b0facf767ebcc68", "result": "success" } @@ -46,92 +46,94 @@ } change script: 2102aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848ac - sendtxid: cb5309ed249da95e2b5696eb763a8736e2fff1d14922ada737b931494ca3d2be + sendtxid: 2c4159bb19212dcaa412ae37de7d72398f063194053e04a65b0facf767ebcc68 broadcast sendtxid and wait for it to be confirmed. then get the msg we need to sign: - ./c cclib calcmsg 18 \"[%22cb5309ed249da95e2b5696eb763a8736e2fff1d14922ada737b931494ca3d2be%22,%222102aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848ac%22]\" + ./c cclib calcmsg 18 \"[%222c4159bb19212dcaa412ae37de7d72398f063194053e04a65b0facf767ebcc68%22,%222102aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848ac%22]\" { "result": "success", - "msg": "63b799913d4c9487f321b32d6ae8614f653f38e0b50d4df4bc1d36339ea18485" + "msg": "caa64ba398ddfe5c33d8c70a61e556caa0e69b19d93110c5a458a1b37ad44cb0" } + the "msg" is what needs to be signed to create a valid spend now on each signing node, a session needs to be created: 5 args: ind, numsigners, combined_pk, pkhash, message to be signed on node with pubkey: 02aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848 - ./c cclib session 18 \"[0,2,%22032ddac56613cd0667b589bd7f32b665e2d2ce0247e337a5a0bca6c72e3d9d057b%22,%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,%2263b799913d4c9487f321b32d6ae8614f653f38e0b50d4df4bc1d36339ea18485%22]\" + ./c cclib session 18 \"[0,2,%22032ddac56613cd0667b589bd7f32b665e2d2ce0247e337a5a0bca6c72e3d9d057b%22,%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,%22caa64ba398ddfe5c33d8c70a61e556caa0e69b19d93110c5a458a1b37ad44cb0%22]\" { "myind": 0, "numsigners": 2, - "commitment": "89af8f6db69fc3d4b95480a914dceba9933039e9823151a82677c3ca4e961fcc", + "commitment": "e82228c10d0e100477630349150dea744d3b2790dcd347511a1a98199840cda4", "result": "success" } on node with pubkey: 039433dc3749aece1bd568f374a45da3b0bc6856990d7da3cd175399577940a775 - ./c cclib session 18 \"[1,2,%22032ddac56613cd0667b589bd7f32b665e2d2ce0247e337a5a0bca6c72e3d9d057b%22,%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,%2263b799913d4c9487f321b32d6ae8614f653f38e0b50d4df4bc1d36339ea18485%22]\" + ./c cclib session 18 \"[1,2,%22032ddac56613cd0667b589bd7f32b665e2d2ce0247e337a5a0bca6c72e3d9d057b%22,%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,%22caa64ba398ddfe5c33d8c70a61e556caa0e69b19d93110c5a458a1b37ad44cb0%22]\" { "myind": 1, "numsigners": 2, - "commitment": "a43da5ef8322abb43b9fddadef7b6479baf7853e860f915e01521e3060e5342b", + "commitment": "6e426e850ddc45e7742cfb6321781c00ee69a995ab12fa1f9ded7fe43658babf", "result": "success" } now we need to get the commitment from each node to the other one. the session already put the commitment for each node into the global struct. Keep in mind there is a single global struct with session unique to each cclib session call. that means no restarting any deamon in the middle of the process on any of the nodes and only call cclib session a single time. this is an artificial restriction just to simplify the initial implementation of musig - ./c cclib commit 18 \"[%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,1,%22a43da5ef8322abb43b9fddadef7b6479baf7853e860f915e01521e3060e5342b%22]\" + ./c cclib commit 18 \"[%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,1,%226e426e850ddc45e7742cfb6321781c00ee69a995ab12fa1f9ded7fe43658babf%22]\" { "added_index": 1, "myind": 0, - "nonce": "03bf28874f5e5dccf55170406d58ded84ac6ca713011d718c6048400d700cb879a", + "nonce": "0261671b0a6de416938cf035c98f8af37c6ca88bbbd1bcce693d709d4919b010e1", "result": "success" } - ./c cclib commit 18 \"[%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,0,%2289af8f6db69fc3d4b95480a914dceba9933039e9823151a82677c3ca4e961fcc%22]\" + ./c cclib commit 18 \"[%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,0,%22e82228c10d0e100477630349150dea744d3b2790dcd347511a1a98199840cda4%22]\" { "added_index": 0, "myind": 1, - "nonce": "039ae1f542e8f0f6d03d734dc2295651973e1b7fa99508e2f36dad5d21f09889f6", + "nonce": "02570f62a625ceb19a754a053152b162810c3e403df63f3d443e85bdacc74bfdfe", "result": "success" } Now exchange the revealed nonces to each node: - ./c cclib nonce 18 \"[%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,1,%22039ae1f542e8f0f6d03d734dc2295651973e1b7fa99508e2f36dad5d21f09889f6%22]\" + ./c cclib nonce 18 \"[%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,1,%2202570f62a625ceb19a754a053152b162810c3e403df63f3d443e85bdacc74bfdfe%22]\" { "added_index": 1, "myind": 0, - "partialsig": "5da4c1ec828cd1563bc6554aa74c90c29fcd38b2aea26f7fa92e0d007aa9463f", + "partialsig": "3f21885e6d2d020e1473435ccd148a61cdcb1d1105867fed45913185dc0acf59", "result": "success" } - ./c cclib nonce 18 \"[%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,0,%2203bf28874f5e5dccf55170406d58ded84ac6ca713011d718c6048400d700cb879a%22]\" + ./c cclib nonce 18 \"[%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,0,%220261671b0a6de416938cf035c98f8af37c6ca88bbbd1bcce693d709d4919b010e1%22]\" { "added_index": 0, + "myind": 0, "myind": 1, - "partialsig": "7e55fd564fe26b1054208bc47786d6e1ce30a2fd0045bbbf0e6915adcf4b0ce1", + "partialsig": "af7f28455fb2e988d81068cd9d800879cd334036a8300118dc307b777a38c1ed", "result": "success" } Almost there! final step is to exchange the partial sigs between signers - ./c cclib partialsig 18 \"[%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,1,%227e55fd564fe26b1054208bc47786d6e1ce30a2fd0045bbbf0e6915adcf4b0ce1%22]\" + ./c cclib partialsig 18 \"[%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,1,%22af7f28455fb2e988d81068cd9d800879cd334036a8300118dc307b777a38c1ed%22]\" { "added_index": 1, "result": "success", - "combinedsig": "bc0062cd3233433e098fbf4f3c333946779c3dccfaefc423243e3f90edfdf9a6dbfabf42d26f3c668fe6e10f1ed367a46dfddbafaee82b3eb79722ae49f45320" + "combinedsig": "5e64dc5dda93b2d3f25fe44b2aaca69b8f15d21f70e2bc1c2c53e17262d941bbeea0b0a3ccdfeb96ec83ac2a6a9492db9afe5d47adb6810621c1acfd56439146" } + - ./c cclib partialsig 18 \"[%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,0,%225da4c1ec828cd1563bc6554aa74c90c29fcd38b2aea26f7fa92e0d007aa9463f%22]\" + ./c cclib partialsig 18 \"[%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,0,%223f21885e6d2d020e1473435ccd148a61cdcb1d1105867fed45913185dc0acf59%22]\" { "added_index": 0, "result": "success", - "combinedsig": "bc0062cd3233433e098fbf4f3c333946779c3dccfaefc423243e3f90edfdf9a6dbfabf42d26f3c668fe6e10f1ed367a46dfddbafaee82b3eb79722ae49f45320" + "combinedsig": "5e64dc5dda93b2d3f25fe44b2aaca69b8f15d21f70e2bc1c2c53e17262d941bbeea0b0a3ccdfeb96ec83ac2a6a9492db9afe5d47adb6810621c1acfd56439146" } - Notice both nodes generated the same combined signature! Now for a sanity test, we can use the verify call to make sure this sig will work with the msg needed for the spend: @@ -141,7 +143,7 @@ the "msg" is what needs to be signed to create a valid spend and finally the spend: sendtxid, scriptPubKey, musig -./c cclib spend 18 \"[%22cb5309ed249da95e2b5696eb763a8736e2fff1d14922ada737b931494ca3d2be%22,%222102aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848ac%22,%22bc0062cd3233433e098fbf4f3c333946779c3dccfaefc423243e3f90edfdf9a6dbfabf42d26f3c668fe6e10f1ed367a46dfddbafaee82b3eb79722ae49f45320%22]\" +./c cclib spend 18 \"[%222c4159bb19212dcaa412ae37de7d72398f063194053e04a65b0facf767ebcc68%22,%222102aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848ac%22,%225e64dc5dda93b2d3f25fe44b2aaca69b8f15d21f70e2bc1c2c53e17262d941bbeea0b0a3ccdfeb96ec83ac2a6a9492db9afe5d47adb6810621c1acfd56439146%22]\" */ @@ -686,7 +688,7 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { static secp256k1_context *ctx; CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); std::string rawtx; CPubKey mypk,pk; secp256k1_pubkey combined_pk; char *scriptstr,*musigstr; uint8_t msg[32]; CTransaction vintx; uint256 prevhash,hashBlock; int32_t n,numvouts; CTxOut vout; secp256k1_schnorrsig musig; + UniValue result(UniValue::VOBJ); std::string rawtx; CPubKey mypk,pk; secp256k1_pubkey combined_pk; char *scriptstr,*musigstr; uint8_t msg[32]; CTransaction vintx; uint256 prevhash,hashBlock; int32_t i,n,numvouts; char str[129]; CTxOut vout; secp256k1_schnorrsig musig; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) @@ -713,6 +715,20 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) secp256k1_ec_pubkey_parse(ctx,&combined_pk,pk.begin(),33) > 0 ) { musig_prevoutmsg(msg,prevhash,vout.scriptPubKey); + { + for (i=0; i<32; i++) + sprintf(&str[i*2],"%02x",msg[i]); + str[64] = 0; + result.push_back(Pair("msg",str)); + for (i=0; i<33; i++) + sprintf(&str[i*2],"%02x",((uint8_t *)pk.begin)[i]); + str[66] = 0; + result.push_back(Pair("combined_pk",str)); + for (i=0; i<64; i++) + sprintf(&str[i*2],"%02x",musig64[i]); + str[128] = 0; + result.push_back(Pair("combinedsig",str)); + } if ( !secp256k1_schnorrsig_verify((const secp256k1_context *)ctx,&musig,(const uint8_t *)msg,(const secp256k1_pubkey *)&combined_pk) ) return(cclib_error(result,"musig didnt validate")); mtx.vin.push_back(CTxIn(prevhash,MUSIG_PREVN)); From 8b8339b5b941963c6ea6331cf57af5c5edc2facc Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 22 Feb 2019 00:17:05 -1100 Subject: [PATCH 300/390] () --- src/cc/musig.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index be4ff278e..88bf62449 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -721,7 +721,7 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) str[64] = 0; result.push_back(Pair("msg",str)); for (i=0; i<33; i++) - sprintf(&str[i*2],"%02x",((uint8_t *)pk.begin)[i]); + sprintf(&str[i*2],"%02x",((uint8_t *)pk.begin())[i]); str[66] = 0; result.push_back(Pair("combined_pk",str)); for (i=0; i<64; i++) From 6eaac8547a3ddb506e70896e3251daf07524395c Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 22 Feb 2019 00:23:02 -1100 Subject: [PATCH 301/390] Skip test --- src/cc/musig.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 88bf62449..63d7e5291 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -730,7 +730,9 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) result.push_back(Pair("combinedsig",str)); } if ( !secp256k1_schnorrsig_verify((const secp256k1_context *)ctx,&musig,(const uint8_t *)msg,(const secp256k1_pubkey *)&combined_pk) ) - return(cclib_error(result,"musig didnt validate")); + { + //return(cclib_error(result,"musig didnt validate")); + } mtx.vin.push_back(CTxIn(prevhash,MUSIG_PREVN)); mtx.vout.push_back(vout); rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,musig_spendopret('y',pk,musig64)); From baef592f94e608d939f4bf627d1ae34e785f1187 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 22 Feb 2019 00:26:39 -1100 Subject: [PATCH 302/390] Fix script parsing --- src/cc/musig.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 63d7e5291..28795d95c 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -704,7 +704,9 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) txfee = MUSIG_TXFEE; mypk = pubkey2pk(Mypubkey()); std::vector musig64(ParseHex(musigstr)); - CScript scriptPubKey(ParseHex(scriptstr)); + CScript scriptPubKey; + scriptPubKey.resize(strlen(scriptstr)/2); + decode_hex((uint8_t *)scriptPubKey.data(),strlen(scriptstr)/2,scriptstr); if ( myGetTransaction(prevhash,vintx,hashBlock) != 0 && (numvouts= vintx.vout.size()) > 1 ) { vout.nValue = vintx.vout[0].nValue - txfee; From 3de50a250b2d1ad2321d67c2336dfe061fb6d2da Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 22 Feb 2019 00:29:48 -1100 Subject: [PATCH 303/390] Test --- src/cc/musig.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 28795d95c..fdb24f7a0 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -706,7 +706,7 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) std::vector musig64(ParseHex(musigstr)); CScript scriptPubKey; scriptPubKey.resize(strlen(scriptstr)/2); - decode_hex((uint8_t *)scriptPubKey.data(),strlen(scriptstr)/2,scriptstr); + decode_hex(&scriptPubKey[0],strlen(scriptstr)/2,scriptstr); if ( myGetTransaction(prevhash,vintx,hashBlock) != 0 && (numvouts= vintx.vout.size()) > 1 ) { vout.nValue = vintx.vout[0].nValue - txfee; From a687d695af02abc60505583027971cfc2373c446 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 22 Feb 2019 00:41:51 -1100 Subject: [PATCH 304/390] Verify roc --- src/cc/musig.cpp | 44 +++++++++++++++++++++++++++----------------- 1 file changed, 27 insertions(+), 17 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index fdb24f7a0..9eaec4404 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -620,25 +620,35 @@ UniValue musig_partialsig(uint64_t txfee,struct CCcontract_info *cp,cJSON *param UniValue musig_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { static secp256k1_context *ctx; - UniValue result(UniValue::VOBJ); int32_t n; + UniValue result(UniValue::VOBJ); int32_t i,n; uint8_t msg[32],musig64[64]; secp256k1_pubkey combined_pk; secp256k1_schnorrsig musig; char str[129]; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); - if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) + if ( params != 0 && (n= cJSON_GetArraySize(params)) != 3 ) { - // can code this out of order - } - result.push_back(Pair("result","success")); - /** Verify a Schnorr signature. - * - * Returns: 1: correct signature - * 0: incorrect or unparseable signature - * Args: ctx: a secp256k1 context object, initialized for verification. - * In: sig: the signature being verified (cannot be NULL) - * msg32: the 32-byte message hash being verified (cannot be NULL) - * pubkey: pointer to a public key to verify with (cannot be NULL) - */ - // if (!secp256k1_schnorrsig_verify(ctx, &sig, msg, &combined_pk)) { - return(result); + if ( musig_parsehash32(msg,jitem(params,0)) < 0 ) + return(cclib_error(result,"error parsing pkhash")); + else if ( musig_parsepubkey(ctx,combined_pk,jitem(params,1)) < 0 ) + return(cclib_error(result,"error parsing combined_pk")); + else if ( musig_parsehash64(musig64,jitem(params,2)) < 0 ) + return(cclib_error(result,"error parsing musig64")); + for (i=0; i<32; i++) + sprintf(&str[i*2],"%02x",msg[i]); + str[64] = 0; + result.push_back(Pair("msg",str)); + result.push_back(Pair("combined_pk",jstr(jitem(params,1),0))); + for (i=0; i<64; i++) + sprintf(&str[i*2],"%02x",musig64[i]); + str[128] = 0; + result.push_back(Pair("combinedsig",str)); + if ( secp256k1_schnorrsig_parse(ctx,&musig,&musig64[0]) > 0 ) + { + if ( secp256k1_schnorrsig_verify(ctx,&musig,msg,&combined_pk) > 0 ) + { + result.push_back(Pair("result","success")); + return(result); + } else return(cclib_error(result,"musig didnt verify")); + } else return(cclib_error(result,"couldnt parse musig64")); + } else return(cclib_error(result,"wrong number of params, need 3: msg, combined_pk, combinedsig")); } // helpers for rpc calls that generate/validate onchain tx @@ -733,7 +743,7 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) } if ( !secp256k1_schnorrsig_verify((const secp256k1_context *)ctx,&musig,(const uint8_t *)msg,(const secp256k1_pubkey *)&combined_pk) ) { - //return(cclib_error(result,"musig didnt validate")); + return(cclib_error(result,"musig didnt validate")); } mtx.vin.push_back(CTxIn(prevhash,MUSIG_PREVN)); mtx.vout.push_back(vout); From 317fa937b3ca5010daa59cfdb58725c7bc2b7d45 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 22 Feb 2019 00:43:44 -1100 Subject: [PATCH 305/390] parsehash --- src/cc/musig.cpp | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 9eaec4404..c5cf5fc4e 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -331,12 +331,12 @@ int32_t musig_parsepubkey(secp256k1_context *ctx,secp256k1_pubkey &spk,cJSON *it } else return(-1); } -int32_t musig_parsehash32(uint8_t *hash32,cJSON *item) +int32_t musig_parsehash(uint8_t *hash32,cJSON *item,int32_t len) { char *hexstr; - if ( (hexstr= jstr(item,0)) != 0 && is_hexstr(hexstr,0) == 64 ) + if ( (hexstr= jstr(item,0)) != 0 && is_hexstr(hexstr,0) == len*2 ) { - decode_hex(hash32,32,hexstr); + decode_hex(hash32,len,hexstr); return(0); } else return(-1); } @@ -394,9 +394,9 @@ UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) MUSIG = musig_infocreate(myind,num); if ( musig_parsepubkey(ctx,MUSIG->combined_pk,jitem(params,2)) < 0 ) return(cclib_error(result,"error parsing combined_pubkey")); - else if ( musig_parsehash32(MUSIG->pkhash,jitem(params,3)) < 0 ) + else if ( musig_parsehash(MUSIG->pkhash,jitem(params,3),32) < 0 ) return(cclib_error(result,"error parsing pkhash")); - else if ( musig_parsehash32(MUSIG->msg,jitem(params,4)) < 0 ) + else if ( musig_parsehash(MUSIG->msg,jitem(params,4),32) < 0 ) return(cclib_error(result,"error parsing msg")); Myprivkey(privkey); GetRandBytes(session,32); @@ -455,13 +455,13 @@ UniValue musig_commit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) { - if ( musig_parsehash32(pkhash,jitem(params,0)) < 0 ) + if ( musig_parsehash(pkhash,jitem(params,0),32) < 0 ) return(cclib_error(result,"error parsing pkhash")); else if ( memcmp(MUSIG->pkhash,pkhash,32) != 0 ) return(cclib_error(result,"pkhash doesnt match session pkhash")); else if ( (ind= juint(jitem(params,1),0)) < 0 || ind >= MUSIG->num ) return(cclib_error(result,"illegal ind for session")); - else if ( musig_parsehash32(&MUSIG->nonce_commitments[ind*32],jitem(params,2)) < 0 ) + else if ( musig_parsehash(&MUSIG->nonce_commitments[ind*32],jitem(params,2),32) < 0 ) return(cclib_error(result,"error parsing commitment")); /** Gets the signer's public nonce given a list of all signers' data with commitments * @@ -508,7 +508,7 @@ UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) { - if ( musig_parsehash32(pkhash,jitem(params,0)) < 0 ) + if ( musig_parsehash(pkhash,jitem(params,0),32) < 0 ) return(cclib_error(result,"error parsing pkhash")); else if ( memcmp(MUSIG->pkhash,pkhash,32) != 0 ) return(cclib_error(result,"pkhash doesnt match session pkhash")); @@ -578,13 +578,13 @@ UniValue musig_partialsig(uint64_t txfee,struct CCcontract_info *cp,cJSON *param ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) { - if ( musig_parsehash32(pkhash,jitem(params,0)) < 0 ) + if ( musig_parsehash(pkhash,jitem(params,0),32) < 0 ) return(cclib_error(result,"error parsing pkhash")); else if ( memcmp(MUSIG->pkhash,pkhash,32) != 0 ) return(cclib_error(result,"pkhash doesnt match session pkhash")); else if ( (ind= juint(jitem(params,1),0)) < 0 || ind >= MUSIG->num ) return(cclib_error(result,"illegal ind for session")); - else if ( musig_parsehash32(psig,jitem(params,2)) < 0 ) + else if ( musig_parsehash(psig,jitem(params,2),32) < 0 ) return(cclib_error(result,"error parsing psig")); else if ( secp256k1_musig_partial_signature_parse(ctx,&MUSIG->partial_sig[ind],psig) == 0 ) return(cclib_error(result,"error parsing partialsig")); @@ -625,11 +625,11 @@ UniValue musig_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); if ( params != 0 && (n= cJSON_GetArraySize(params)) != 3 ) { - if ( musig_parsehash32(msg,jitem(params,0)) < 0 ) + if ( musig_parsehash(msg,jitem(params,0),32) < 0 ) return(cclib_error(result,"error parsing pkhash")); else if ( musig_parsepubkey(ctx,combined_pk,jitem(params,1)) < 0 ) return(cclib_error(result,"error parsing combined_pk")); - else if ( musig_parsehash64(musig64,jitem(params,2)) < 0 ) + else if ( musig_parsehash(musig64,jitem(params,2),64) < 0 ) return(cclib_error(result,"error parsing musig64")); for (i=0; i<32; i++) sprintf(&str[i*2],"%02x",msg[i]); From 6704dd969965d0b938ad2dceab6714a90daca687 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 22 Feb 2019 00:52:37 -1100 Subject: [PATCH 306/390] Fix --- src/cc/musig.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index c5cf5fc4e..8e37a2add 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -138,7 +138,7 @@ the "msg" is what needs to be signed to create a valid spend Now for a sanity test, we can use the verify call to make sure this sig will work with the msg needed for the spend: - xxxx + ./c cclib verify 18 \"[%22caa64ba398ddfe5c33d8c70a61e556caa0e69b19d93110c5a458a1b37ad44cb0%22,%22032ddac56613cd0667b589bd7f32b665e2d2ce0247e337a5a0bca6c72e3d9d057b%22,%225e64dc5dda93b2d3f25fe44b2aaca69b8f15d21f70e2bc1c2c53e17262d941bbeea0b0a3ccdfeb96ec83ac2a6a9492db9afe5d47adb6810621c1acfd56439146%22]\" and finally the spend: sendtxid, scriptPubKey, musig @@ -623,7 +623,7 @@ UniValue musig_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue result(UniValue::VOBJ); int32_t i,n; uint8_t msg[32],musig64[64]; secp256k1_pubkey combined_pk; secp256k1_schnorrsig musig; char str[129]; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); - if ( params != 0 && (n= cJSON_GetArraySize(params)) != 3 ) + if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) { if ( musig_parsehash(msg,jitem(params,0),32) < 0 ) return(cclib_error(result,"error parsing pkhash")); From 3caa4fb350c74d5af61b02770a523272ddc8324d Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 22 Feb 2019 00:59:15 -1100 Subject: [PATCH 307/390] Test check.c --- src/cc/cclib.cpp | 32 +---------------------- src/secp256k1/src/modules/musig/example.c | 6 ++--- 2 files changed, 4 insertions(+), 34 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index ec74877b6..b070ded78 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -580,37 +580,7 @@ uint256 juint256(cJSON *obj) #else #include "sudoku.cpp" - -/* -#include "../secp256k1/src/util.h" -#include "../secp256k1/src/num_impl.h" -#include "../secp256k1/src/field_impl.h" -#include "../secp256k1/src/scalar_impl.h" -#include "../secp256k1/src/group_impl.h" -#include "../secp256k1/src/scratch_impl.h" -#include "../secp256k1/src/ecmult_impl.h" -#include "../secp256k1/src/ecmult_const_impl.h" -#include "../secp256k1/src/ecmult_gen_impl.h" -#include "../secp256k1/src/ecdsa_impl.h" -#include "../secp256k1/src/eckey_impl.h" -#include "../secp256k1/src/hash_impl.h" - - - -typedef int (secp256k1_ecmult_multi_callback)(secp256k1_scalar *sc, secp256k1_ge *pt, size_t idx, void *data); -extern "C" void secp256k1_pubkey_save(secp256k1_pubkey* pubkey, secp256k1_ge* ge); -extern "C" int secp256k1_nonce_function_bipschnorr(unsigned char *nonce32, const unsigned char *msg32, const unsigned char *key32, const unsigned char *algo16, void *data, unsigned int counter); -extern "C" int secp256k1_pubkey_load(const secp256k1_context* ctx, secp256k1_ge* ge, const secp256k1_pubkey* pubkey); -extern "C" void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx); - -#define ARG_CHECK(cond) do { \ -if (EXPECT(!(cond), 0)) { \ -secp256k1_callback_call(&ctx->illegal_callback, #cond); \ -return 0; \ -} \ -} while(0)*/ - -//#include "../secp256k1/src/secp256k1.c" #include "musig.cpp" +#include "../secp256k1/modules/musig/check.c" #endif diff --git a/src/secp256k1/src/modules/musig/example.c b/src/secp256k1/src/modules/musig/example.c index ceae18686..94c9fdef2 100644 --- a/src/secp256k1/src/modules/musig/example.c +++ b/src/secp256k1/src/modules/musig/example.c @@ -9,11 +9,11 @@ * Additionally, see the documentation in include/secp256k1_musig.h. */ -#include +/*#include #include #include #include -#include +#include */ /* Number of public keys involved in creating the aggregate signature */ #define N_SIGNERS 3 @@ -122,7 +122,7 @@ int sign(const secp256k1_context* ctx, unsigned char seckeys[][32], const secp25 return secp256k1_musig_partial_sig_combine(ctx, &musig_session[0], sig, partial_sig, N_SIGNERS); } - int main(void) { + int testmain(void) { secp256k1_context* ctx; int i; unsigned char seckeys[N_SIGNERS][32]; From fe60cfbf6eb486ac08a5b3906854ab1c82d1d1c3 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 22 Feb 2019 00:59:44 -1100 Subject: [PATCH 308/390] Src --- src/cc/cclib.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index b070ded78..9cd947efc 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -581,6 +581,6 @@ uint256 juint256(cJSON *obj) #else #include "sudoku.cpp" #include "musig.cpp" -#include "../secp256k1/modules/musig/check.c" +#include "../secp256k1/src/modules/musig/check.c" #endif From 1a34721c44c35815f90b739c30eb4d28ef3e6783 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 22 Feb 2019 01:01:00 -1100 Subject: [PATCH 309/390] example.c --- src/cc/cclib.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 9cd947efc..c770917ea 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -581,6 +581,6 @@ uint256 juint256(cJSON *obj) #else #include "sudoku.cpp" #include "musig.cpp" -#include "../secp256k1/src/modules/musig/check.c" +#include "../secp256k1/src/modules/musig/example.c" #endif From 93acda143f271f0e08b07393f958dc194bb352ba Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 22 Feb 2019 01:03:17 -1100 Subject: [PATCH 310/390] fprintf(stderr, --- src/cc/musig.cpp | 2 ++ src/secp256k1/src/modules/musig/example.c | 26 +++++++++++------------ 2 files changed, 15 insertions(+), 13 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 8e37a2add..446f9333d 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -617,10 +617,12 @@ UniValue musig_partialsig(uint64_t txfee,struct CCcontract_info *cp,cJSON *param } else return(cclib_error(result,"wrong number of params, need 3: pkhash, ind, partialsig")); } +int testmain(void); UniValue musig_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { static secp256k1_context *ctx; UniValue result(UniValue::VOBJ); int32_t i,n; uint8_t msg[32],musig64[64]; secp256k1_pubkey combined_pk; secp256k1_schnorrsig musig; char str[129]; + testmain(); if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) diff --git a/src/secp256k1/src/modules/musig/example.c b/src/secp256k1/src/modules/musig/example.c index 94c9fdef2..70d183e7d 100644 --- a/src/secp256k1/src/modules/musig/example.c +++ b/src/secp256k1/src/modules/musig/example.c @@ -128,37 +128,37 @@ int sign(const secp256k1_context* ctx, unsigned char seckeys[][32], const secp25 unsigned char seckeys[N_SIGNERS][32]; secp256k1_pubkey pubkeys[N_SIGNERS]; secp256k1_pubkey combined_pk; - unsigned char msg[32] = "this_could_be_the_hash_of_a_msg!"; + unsigned char msg[32] = "this_could_be_the_hash_of_a_msg"; secp256k1_schnorrsig sig; /* Create a context for signing and verification */ ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); - printf("Creating key pairs......"); + fprintf(stderr,"Creating key pairs......"); for (i = 0; i < N_SIGNERS; i++) { if (!create_key(ctx, seckeys[i], &pubkeys[i])) { - printf("FAILED\n"); + fprintf(stderr,"FAILED\n"); return 1; } } - printf("ok\n"); - printf("Combining public keys..."); + fprintf(stderr,"ok\n"); + fprintf(stderr,"Combining public keys..."); if (!secp256k1_musig_pubkey_combine(ctx, NULL, &combined_pk, NULL, pubkeys, N_SIGNERS)) { - printf("FAILED\n"); + fprintf(stderr,"FAILED\n"); return 1; } - printf("ok\n"); - printf("Signing message........."); + fprintf(stderr,"ok\n"); + fprintf(stderr,"Signing message........."); if (!sign(ctx, seckeys, pubkeys, msg, &sig)) { - printf("FAILED\n"); + fprintf(stderr,"FAILED\n"); return 1; } - printf("ok\n"); - printf("Verifying signature....."); + fprintf(stderr,"ok\n"); + fprintf(stderr,"Verifying signature....."); if (!secp256k1_schnorrsig_verify(ctx, &sig, msg, &combined_pk)) { - printf("FAILED\n"); + fprintf(stderr,"FAILED\n"); return 1; } - printf("ok\n"); + fprintf(stderr,"ok\n"); secp256k1_context_destroy(ctx); return 0; } From a0b7227e007bcfa96ad6e99c54a85875652eed63 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 22 Feb 2019 09:29:09 -1100 Subject: [PATCH 311/390] Dont create rogue files on validation --- src/cc/rogue_rpc.cpp | 33 ++++++++++++++++++--------------- 1 file changed, 18 insertions(+), 15 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 57ce1e14b..213e382a1 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -833,7 +833,7 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param } else return(cclib_error(result,"couldnt reparse params")); } -char *rogue_extractgame(char *str,int32_t *numkeysp,std::vector &newdata,uint64_t &seed,uint256 &playertxid,struct CCcontract_info *cp,uint256 gametxid,char *rogueaddr) +char *rogue_extractgame(int32_t makefiles,char *str,int32_t *numkeysp,std::vector &newdata,uint64_t &seed,uint256 &playertxid,struct CCcontract_info *cp,uint256 gametxid,char *rogueaddr) { CPubKey roguepk; int32_t i,num,maxplayers,gameheight,batonht,batonvout,numplayers,regslot,numkeys,err; std::string symbol,pname; CTransaction gametx; int64_t buyin,batonvalue; char fname[64],*keystrokes = 0; std::vector playerdata; uint256 batontxid; FILE *fp; uint8_t newplayer[10000]; struct rogue_player P,endP; roguepk = GetUnspendable(cp,0); @@ -854,19 +854,22 @@ char *rogue_extractgame(char *str,int32_t *numkeysp,std::vector &newdat } if ( keystrokes != 0 ) { - sprintf(fname,"rogue.%llu.0",(long long)seed); - if ( (fp= fopen(fname,"wb")) != 0 ) + if ( makefiles != 0 ) { - if ( fwrite(keystrokes,1,numkeys,fp) != numkeys ) - fprintf(stderr,"error writing %s\n",fname); - fclose(fp); - } - sprintf(fname,"rogue.%llu.player",(long long)seed); - if ( (fp= fopen(fname,"wb")) != 0 ) - { - if ( fwrite(&playerdata[0],1,(int32_t)playerdata.size(),fp) != playerdata.size() ) - fprintf(stderr,"error writing %s\n",fname); - fclose(fp); + sprintf(fname,"rogue.%llu.0",(long long)seed); + if ( (fp= fopen(fname,"wb")) != 0 ) + { + if ( fwrite(keystrokes,1,numkeys,fp) != numkeys ) + fprintf(stderr,"error writing %s\n",fname); + fclose(fp); + } + sprintf(fname,"rogue.%llu.player",(long long)seed); + if ( (fp= fopen(fname,"wb")) != 0 ) + { + if ( fwrite(&playerdata[0],1,(int32_t)playerdata.size(),fp) != playerdata.size() ) + fprintf(stderr,"error writing %s\n",fname); + fclose(fp); + } } num = rogue_replay2(newplayer,seed,keystrokes,numkeys,playerdata.size()==0?0:&P,0); newdata.resize(num); @@ -914,7 +917,7 @@ UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) GetCCaddress1of2(cp,rogueaddr,roguepk,pk); result.push_back(Pair("rogueaddr",rogueaddr)); str[0] = 0; - if ( (keystrokes= rogue_extractgame(str,&numkeys,newdata,seed,playertxid,cp,gametxid,rogueaddr)) != 0 ) + if ( (keystrokes= rogue_extractgame(1,str,&numkeys,newdata,seed,playertxid,cp,gametxid,rogueaddr)) != 0 ) { result.push_back(Pair("status","success")); flag = 1; @@ -1240,7 +1243,7 @@ int32_t rogue_playerdata_validate(uint256 &playertxid,struct CCcontract_info *cp roguepk = GetUnspendable(cp,0); GetCCaddress1of2(cp,rogueaddr,roguepk,pk); //fprintf(stderr,"call extractgame\n"); - if ( (keystrokes= rogue_extractgame(str,&numkeys,newdata,seed,playertxid,cp,gametxid,rogueaddr)) != 0 ) + if ( (keystrokes= rogue_extractgame(0,str,&numkeys,newdata,seed,playertxid,cp,gametxid,rogueaddr)) != 0 ) { free(keystrokes); //fprintf(stderr,"extracted.(%s)\n",str); From fa3b624d512d7476ea3a3927a810c1f426b98b14 Mon Sep 17 00:00:00 2001 From: blackjok3r Date: Sat, 23 Feb 2019 15:12:00 +0800 Subject: [PATCH 312/390] fix musig and working example added --- src/cc/musig.cpp | 236 ++++++++++++++++++++++++++++------------------- 1 file changed, 139 insertions(+), 97 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 446f9333d..bd3d74a95 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -14,47 +14,67 @@ ******************************************************************************/ /* first make a combined pk: -./c cclib combine 18 \"[%2202aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848%22,%22039433dc3749aece1bd568f374a45da3b0bc6856990d7da3cd175399577940a775%22]\" -{ - "pkhash": "5be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba", - "combined_pk": "032ddac56613cd0667b589bd7f32b665e2d2ce0247e337a5a0bca6c72e3d9d057b", - "result": "success" -} - the combined_pk and pkhash will be needed for various other rpc calls -*/ -/* second, send 0.777 coins to the combined_pk - ./c cclib send 18 \"[%22032ddac56613cd0667b589bd7f32b665e2d2ce0247e337a5a0bca6c72e3d9d057b%22,0.777]\" +./komodo-cli -ac_name=MUSIG cclib combine 18 '["02fb6aa0b96cad24d46b5da93eba3864c45ce07a73bba12da530ae841e140fcf28","0255c46dbce584e3751081b39d7fc054fc807100557e73fc444481618b5706afb4"]' +{ + "pkhash": "5cb5a225064ca6ffc1438cb2a6ac2ac65fe2d5055dc7f6c7ebffb9a231f8912b", + "combined_pk": "03f016c348437c7422eed92d865aa9789614f75327cada463eefc566126b54785b", + "result": "success" +} + + the combined_pk and pkhash will be needed for various other rpc calls + + second, send 1 coin to the combined_pk + ./komodo-cli -ac_name=MUSIG cclib send 18 '["03f016c348437c7422eed92d865aa9789614f75327cada463eefc566126b54785b",1]' { - "hex": "0400008085202f8908018bbc4a0acf0f896680b84cc1000ec5530042fa3cf7471ab5c11cde56f6d0e60000000048473044022041a900fa57e54f939b797d09f0cee81ab9a79d978cd473ef3fc9f09c7678ad6b02206386bd15ee7ee8224a984fdd1d2a094738d082aec06028a5846d7bc61ddf16ca01ffffffff0b969f0e1ea787f0cc4e81d128353bd1cb670ab89bd1db4b47fbb7e872cd39fb00000000494830450221008c5de4b196e57b0dd94aa415950adf274e3e6859b82cf218729af84c1f15e76c022024aeab7eda63e6a652ef488bf26a8dc4ef8d2d4aa5746726085bfe5f169a5db701ffffffff0b36b70b43457fab377f28fb22da5a3e9d8186a37daae18cf0f710a221ab26250000000048473044022004ec20ae7490e7adabf9a3f78e4a58df84a3245485bfdd40f421cafe61d19c340220456d2b6f3c6e88632027c02606a0af1c21208d05f2de0826fbf4dfe7391ec83901ffffffff0aaff3cfe4ca22b97b6179a6f7cfac91945e5440e9438b89d1ec09500167176a0000000048473044022074dcad30c8ab9ed79a3ac69169611fc9e5f4b76a561b183461d968249316997f022063b25decaa285f494d277b9c8c2bcf6445b7929a304542e89c0645828d30a1a901ffffffff090e1bb92e9bf404a0d6455701b21af3dbf6765e61a1dc28b7c0f608ec4f12da000000004847304402202f9182c532c66138a6bdfcbb85a06cf1bf1532f2bf8f63170ef20843e4a81d0202207612a4353eb9606e84621c444ec7db1b683ff29c56127bda2d5e9c0eb13dbbc001ffffffff08a57005c7a40a923b1a510820b07f7318d760fe2a233b077d918cce357ad3af00000000484730440220643d60c68634fb2e0f6656389fc70c9f84c7086fc6e35b0fa26297e844f6c5fc02201d79669e073efe738d47de0130fdcba875e284e18fd478c0e6834d46632d8b8101ffffffff068cfd0ea6c0f5d401c67ec38f92425a9e59b0d5ade55bb2971ea955675a17bd00000000484730440220747139724248da4bcc1e5e3828e0ea811756e1fad0ebc40aeb006fd8079d46e402200d8f1c229c79494b5617e4373a3e083966dcd74571323f9d334be901d53871fa01ffffffff0200382fb6984b6128bb75115346242809c6555274e0cacef822825a2b4d231700000000484730440220454fcac398f6913fb4d8ed330f110f9cf62eec6c8cdb67d5df1effd2cf8222d5022017f6323630669777573e342e870c88727a917cc06c33611ebbd9d1fccc1dcd3701ffffffff03b0c2a10400000000302ea22c8020c71ddb3aac7f9b9e4bdacf032aaa8b8e4433c4ff9f8a43cebb9c1f5da96928a48103120c008203000401cc40ca220000000000232102aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848ac0000000000000000266a24127821032ddac56613cd0667b589bd7f32b665e2d2ce0247e337a5a0bca6c72e3d9d057b00000000460100000000000000000000000000", - "txid": "2c4159bb19212dcaa412ae37de7d72398f063194053e04a65b0facf767ebcc68", - "result": "success" + "hex": "0400008085202f8901a980664dffc810725a79ffb89ac48be4c7b6bade9b789732fcf871acf8e81a2e010000006a47304402207e52763661ecd2c34a65d6623950be11794825db71576dc11894c606ddc317800220028fef46dc20630d0fdf22647b5d4ff0f1c47cf75f48702d0a91d5589eff99d001210255c46dbce584e3751081b39d7fc054fc807100557e73fc444481618b5706afb4ffffffff031008f60500000000302ea22c8020c71ddb3aac7f9b9e4bdacf032aaa8b8e4433c4ff9f8a43cebb9c1f5da96928a48103120c008203000401cce09aa4350000000023210255c46dbce584e3751081b39d7fc054fc807100557e73fc444481618b5706afb4ac0000000000000000266a2412782103f016c348437c7422eed92d865aa9789614f75327cada463eefc566126b54785b00000000920500000000000000000000000000", + "txid": "5ce74037a153ee210413b48d4e88638b99825a2de1a1f1aa0d36ebf93019824c", + "result": "success" } - { - "value": 0.77710000, - "valueZat": 77710000, - "n": 0, - "scriptPubKey": { - "asm": "a22c8020c71ddb3aac7f9b9e4bdacf032aaa8b8e4433c4ff9f8a43cebb9c1f5da96928a48103120c008203000401 OP_CHECKCRYPTOCONDITION", - "hex": "2ea22c8020c71ddb3aac7f9b9e4bdacf032aaa8b8e4433c4ff9f8a43cebb9c1f5da96928a48103120c008203000401cc", - "reqSigs": 1, - "type": "cryptocondition", - "addresses": [ - "RKWS7jxyjPX9iaJttk8iMKf1AumanKypez" - ] - } - change script: 2102aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848ac + sendrawtransaction of the above hex. - sendtxid: 2c4159bb19212dcaa412ae37de7d72398f063194053e04a65b0facf767ebcc68 + ./komodo-cli -ac_name=MUSIG getrawtransaction 5ce74037a153ee210413b48d4e88638b99825a2de1a1f1aa0d36ebf93019824c 1 + "vout": [ + { + "value": 1.00010000, + "valueSat": 100010000, + "n": 0, + "scriptPubKey": { + "asm": "a22c8020c71ddb3aac7f9b9e4bdacf032aaa8b8e4433c4ff9f8a43cebb9c1f5da96928a48103120c008203000401 OP_CHECKCRYPTOCONDITION", + "hex": "2ea22c8020c71ddb3aac7f9b9e4bdacf032aaa8b8e4433c4ff9f8a43cebb9c1f5da96928a48103120c008203000401cc", + "reqSigs": 1, + "type": "cryptocondition", + "addresses": [ + "RKWS7jxyjPX9iaJttk8iMKf1AumanKypez" + ] + } + }, + { + "value": 8.99980000, + "valueSat": 899980000, + "n": 1, + "scriptPubKey": { + "asm": "0255c46dbce584e3751081b39d7fc054fc807100557e73fc444481618b5706afb4 OP_CHECKSIG", + "hex": "210255c46dbce584e3751081b39d7fc054fc807100557e73fc444481618b5706afb4ac", + "reqSigs": 1, + "type": "pubkey", + "addresses": [ + "RVQjvGdRbYLJ49bfH4SAFseipvwE3UdoDw" + ] + } - broadcast sendtxid and wait for it to be confirmed. then get the msg we need to sign: + script: 210255c46dbce584e3751081b39d7fc054fc807100557e73fc444481618b5706afb4ac - ./c cclib calcmsg 18 \"[%222c4159bb19212dcaa412ae37de7d72398f063194053e04a65b0facf767ebcc68%22,%222102aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848ac%22]\" + sendtxid: 5ce74037a153ee210413b48d4e88638b99825a2de1a1f1aa0d36ebf93019824c + + get the msg we need to sign: + + ./komodo-cli -ac_name=MUSIG cclib calcmsg 18 '["5ce74037a153ee210413b48d4e88638b99825a2de1a1f1aa0d36ebf93019824c","210255c46dbce584e3751081b39d7fc054fc807100557e73fc444481618b5706afb4ac"]' { - "result": "success", - "msg": "caa64ba398ddfe5c33d8c70a61e556caa0e69b19d93110c5a458a1b37ad44cb0" + "msg": "f7fb85d1412814e3c2f98b990802af6ee33dad368c6ba05c2050e9e5506fcd75", + "result": "success" } the "msg" is what needs to be signed to create a valid spend @@ -62,88 +82,101 @@ the "msg" is what needs to be signed to create a valid spend now on each signing node, a session needs to be created: 5 args: ind, numsigners, combined_pk, pkhash, message to be signed - on node with pubkey: 02aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848 - ./c cclib session 18 \"[0,2,%22032ddac56613cd0667b589bd7f32b665e2d2ce0247e337a5a0bca6c72e3d9d057b%22,%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,%22caa64ba398ddfe5c33d8c70a61e556caa0e69b19d93110c5a458a1b37ad44cb0%22]\" + on node with pubkey: 02fb6aa0b96cad24d46b5da93eba3864c45ce07a73bba12da530ae841e140fcf28 + ./komodo-cli -ac_name=MUSIG cclib session 18 '[0,2,"03f016c348437c7422eed92d865aa9789614f75327cada463eefc566126b54785b","c1b34139744f3b54b652dc741ebd0f9d5b53ad28795cc6614dd8ad3aaabf15ae","f5d91999b23b85630a4cbd0baea3736529411b052cf5f1f4345c5d181af12825"]' { - "myind": 0, - "numsigners": 2, - "commitment": "e82228c10d0e100477630349150dea744d3b2790dcd347511a1a98199840cda4", - "result": "success" + "myind": 0, + "numsigners": 2, + "commitment": "bbea1f2562eca01b9a1393c5dc188bdd44551aebf684f4459930f59dde01f7ae", + "result": "success" } - - on node with pubkey: 039433dc3749aece1bd568f374a45da3b0bc6856990d7da3cd175399577940a775 - ./c cclib session 18 \"[1,2,%22032ddac56613cd0667b589bd7f32b665e2d2ce0247e337a5a0bca6c72e3d9d057b%22,%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,%22caa64ba398ddfe5c33d8c70a61e556caa0e69b19d93110c5a458a1b37ad44cb0%22]\" - { - "myind": 1, - "numsigners": 2, - "commitment": "6e426e850ddc45e7742cfb6321781c00ee69a995ab12fa1f9ded7fe43658babf", - "result": "success" - } - - now we need to get the commitment from each node to the other one. the session already put the commitment for each node into the global struct. Keep in mind there is a single global struct with session unique to each cclib session call. that means no restarting any deamon in the middle of the process on any of the nodes and only call cclib session a single time. this is an artificial restriction just to simplify the initial implementation of musig - - ./c cclib commit 18 \"[%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,1,%226e426e850ddc45e7742cfb6321781c00ee69a995ab12fa1f9ded7fe43658babf%22]\" - { - "added_index": 1, - "myind": 0, - "nonce": "0261671b0a6de416938cf035c98f8af37c6ca88bbbd1bcce693d709d4919b010e1", - "result": "success" - } - - ./c cclib commit 18 \"[%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,0,%22e82228c10d0e100477630349150dea744d3b2790dcd347511a1a98199840cda4%22]\" - { - "added_index": 0, - "myind": 1, - "nonce": "02570f62a625ceb19a754a053152b162810c3e403df63f3d443e85bdacc74bfdfe", - "result": "success" - } - - Now exchange the revealed nonces to each node: - - ./c cclib nonce 18 \"[%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,1,%2202570f62a625ceb19a754a053152b162810c3e403df63f3d443e85bdacc74bfdfe%22]\" + on node with pubkey: 0255c46dbce584e3751081b39d7fc054fc807100557e73fc444481618b5706afb4 + ./komodo-cli -ac_name=MUSIG cclib session 18 '[1,2,"03f016c348437c7422eed92d865aa9789614f75327cada463eefc566126b54785b","5cb5a225064ca6ffc1438cb2a6ac2ac65fe2d5055dc7f6c7ebffb9a231f8912b","f7fb85d1412814e3c2f98b990802af6ee33dad368c6ba05c2050e9e5506fcd75"]' { - "added_index": 1, - "myind": 0, - "partialsig": "3f21885e6d2d020e1473435ccd148a61cdcb1d1105867fed45913185dc0acf59", - "result": "success" + "myind": 1, + "numsigners": 2, + "commitment": "c2291acb747a75b1a40014d8eb0cc90a1360f74d413f65f78e20a7de45eda851", + "result": "success" + } + + now we need to get the commitment from each node to the other one. the session already put the commitment for each node into the global struct. Keep in mind there is a single global struct with session unique to each cclib session call. that means no restarting any deamon in the middle of the process on any of the nodes and only call cclib session a single time. this is an artificial restriction just to simplify the initial implementation of musig + ./komodo-cli -ac_name=MUSIG cclib commit 18 '["5cb5a225064ca6ffc1438cb2a6ac2ac65fe2d5055dc7f6c7ebffb9a231f8912b","1","c2291acb747a75b1a40014d8eb0cc90a1360f74d413f65f78e20a7de45eda851"]' + { + "added_index": 1, + "myind": 0, + "nonce": "02fec7a9310c959a0a97b86bc3f8c30d392d1fb51793915898c568f73f1f70476b", + "result": "success" } - ./c cclib nonce 18 \"[%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,0,%220261671b0a6de416938cf035c98f8af37c6ca88bbbd1bcce693d709d4919b010e1%22]\" + ./komodo-cli -ac_name=MUSIG cclib commit 18 '["5cb5a225064ca6ffc1438cb2a6ac2ac65fe2d5055dc7f6c7ebffb9a231f8912b",0,"d242cff13fa8c9b83248e4219fda459ada146b885f2171481f1b0f66c66d94ad"]' { - "added_index": 0, - "myind": 0, - "myind": 1, - "partialsig": "af7f28455fb2e988d81068cd9d800879cd334036a8300118dc307b777a38c1ed", - "result": "success" + "added_index": 0, + "myind": 1, + "nonce": "039365deaaaea089d509ba4c9f846de2baf4aa04cf6b26fa2c1cd818553e47f80c", + "result": "success" } + + Now exchange the revealed nonces to each node: + ./komodo-cli -ac_name=MUSIG cclib nonce 18 '["5cb5a225064ca6ffc1438cb2a6ac2ac65fe2d5055dc7f6c7ebffb9a231f8912b","1","039365deaaaea089d509ba4c9f846de2baf4aa04cf6b26fa2c1cd818553e47f80c"]' +{ + "added_index": 1, + "myind": 0, + "partialsig": "1d65c09cd9bffe4f0604227e66cd7cd221480bbb08262fe885563a9df7cf8f5b", + "result": "success" +} + +./komodo-cli -ac_name=MUSIG cclib nonce 18 '["5cb5a225064ca6ffc1438cb2a6ac2ac65fe2d5055dc7f6c7ebffb9a231f8912b",0,"02fec7a9310c959a0a97b86bc3f8c30d392d1fb51793915898c568f73f1f70476b"]' +{ + "added_index": 0, + "myind": 1, + "partialsig": "4a3795e6801b355102c617390cf5a462061e082e35dc2ed8f8b1fab54cc0769e", + "result": "success" +} Almost there! final step is to exchange the partial sigs between signers - ./c cclib partialsig 18 \"[%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,1,%22af7f28455fb2e988d81068cd9d800879cd334036a8300118dc307b777a38c1ed%22]\" + ./komodo-cli -ac_name=MUSIG cclib partialsig 18 '["5cb5a225064ca6ffc1438cb2a6ac2ac65fe2d5055dc7f6c7ebffb9a231f8912b","1","4a3795e6801b355102c617390cf5a462061e082e35dc2ed8f8b1fab54cc0769e"]' { - "added_index": 1, - "result": "success", - "combinedsig": "5e64dc5dda93b2d3f25fe44b2aaca69b8f15d21f70e2bc1c2c53e17262d941bbeea0b0a3ccdfeb96ec83ac2a6a9492db9afe5d47adb6810621c1acfd56439146" + "added_index": 1, + "result": "success", + "combinedsig": "a76f2790747ed2436a281f2660bdbee21bad9ee130b9cab6e542fa618fba1512679d568359db33a008ca39b773c32134276613e93e025ec17e083553449005f9" } - - ./c cclib partialsig 18 \"[%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,0,%223f21885e6d2d020e1473435ccd148a61cdcb1d1105867fed45913185dc0acf59%22]\" - + ./komodo-cli -ac_name=MUSIG cclib partialsig 18 '["5cb5a225064ca6ffc1438cb2a6ac2ac65fe2d5055dc7f6c7ebffb9a231f8912b",0,"1d65c09cd9bffe4f0604227e66cd7cd221480bbb08262fe885563a9df7cf8f5b"]' { - "added_index": 0, - "result": "success", - "combinedsig": "5e64dc5dda93b2d3f25fe44b2aaca69b8f15d21f70e2bc1c2c53e17262d941bbeea0b0a3ccdfeb96ec83ac2a6a9492db9afe5d47adb6810621c1acfd56439146" + "added_index": 0, + "result": "success", + "combinedsig": "a76f2790747ed2436a281f2660bdbee21bad9ee130b9cab6e542fa618fba1512679d568359db33a008ca39b773c32134276613e93e025ec17e083553449005f9" } + Notice both nodes generated the same combined signature! Now for a sanity test, we can use the verify call to make sure this sig will work with the msg needed for the spend: - ./c cclib verify 18 \"[%22caa64ba398ddfe5c33d8c70a61e556caa0e69b19d93110c5a458a1b37ad44cb0%22,%22032ddac56613cd0667b589bd7f32b665e2d2ce0247e337a5a0bca6c72e3d9d057b%22,%225e64dc5dda93b2d3f25fe44b2aaca69b8f15d21f70e2bc1c2c53e17262d941bbeea0b0a3ccdfeb96ec83ac2a6a9492db9afe5d47adb6810621c1acfd56439146%22]\" - + ./komodo-cli -ac_name=MUSIG cclib verify 18 '["f7fb85d1412814e3c2f98b990802af6ee33dad368c6ba05c2050e9e5506fcd75","03f016c348437c7422eed92d865aa9789614f75327cada463eefc566126b54785b","a76f2790747ed2436a281f2660bdbee21bad9ee130b9cab6e542fa618fba1512679d568359db33a008ca39b773c32134276613e93e025ec17e083553449005f9"]' + { + "msg": "f7fb85d1412814e3c2f98b990802af6ee33dad368c6ba05c2050e9e5506fcd75", + "combined_pk": "03f016c348437c7422eed92d865aa9789614f75327cada463eefc566126b54785b", + "combinedsig": "a76f2790747ed2436a281f2660bdbee21bad9ee130b9cab6e542fa618fba1512679d568359db33a008ca39b773c32134276613e93e025ec17e083553449005f9", + "result": "success" + } and finally the spend: sendtxid, scriptPubKey, musig -./c cclib spend 18 \"[%222c4159bb19212dcaa412ae37de7d72398f063194053e04a65b0facf767ebcc68%22,%222102aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848ac%22,%225e64dc5dda93b2d3f25fe44b2aaca69b8f15d21f70e2bc1c2c53e17262d941bbeea0b0a3ccdfeb96ec83ac2a6a9492db9afe5d47adb6810621c1acfd56439146%22]\" + ./komodo-cli -ac_name=MUSIG cclib spend 18 '["5ce74037a153ee210413b48d4e88638b99825a2de1a1f1aa0d36ebf93019824c","210255c46dbce584e3751081b39d7fc054fc807100557e73fc444481618b5706afb4ac","a76f2790747ed2436a281f2660bdbee21bad9ee130b9cab6e542fa618fba1512679d568359db33a008ca39b773c32134276613e93e025ec17e083553449005f9"]' +{ + "scriptpubkey": "210255c46dbce584e3751081b39d7fc054fc807100557e73fc444481618b5706afb4ac", + "msg": "f7fb85d1412814e3c2f98b990802af6ee33dad368c6ba05c2050e9e5506fcd75", + "combined_pk": "03f016c348437c7422eed92d865aa9789614f75327cada463eefc566126b54785b", + "combinedsig": "a76f2790747ed2436a281f2660bdbee21bad9ee130b9cab6e542fa618fba1512679d568359db33a008ca39b773c32134276613e93e025ec17e083553449005f9", + "hex": "0400008085202f89014c821930f9eb360daaf1a1e12d5a82998b63884e8db4130421ee53a13740e75c000000007b4c79a276a072a26ba067a5658021032d29d6545a2aafad795d9cf50912ecade549137 +163934dfb2895ebc0e211ce8a81409671a60db89b3bc58966f3acc80194479b1a43d868e95a11ebc5609646d18710341a8ff92a7817571980307f5d660cc00a2735ac6333e0a7191243f1263f1959a100af03800112 +a10001ffffffff0200e1f5050000000023210255c46dbce584e3751081b39d7fc054fc807100557e73fc444481618b5706afb4ac0000000000000000686a4c6512792103f016c348437c7422eed92d865aa9789614f +75327cada463eefc566126b54785b40a76f2790747ed2436a281f2660bdbee21bad9ee130b9cab6e542fa618fba1512679d568359db33a008ca39b773c32134276613e93e025ec17e083553449005f900000000a805 +00000000000000000000000000", + "txid": "910635bf69a047fc90567a83ff12e47b753f470658b6d0855ec96e07e7349a8a", + "result": "success" +} */ @@ -298,7 +331,7 @@ int32_t musig_prevoutmsg(uint8_t *msg,uint256 sendtxid,CScript scriptPubKey) UniValue musig_calcmsg(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); uint256 sendtxid; int32_t i; uint8_t msg[32]; char *scriptstr,str[65]; int32_t n; + UniValue result(UniValue::VOBJ); uint256 sendtxid; int32_t i,zeros=0; uint8_t msg[32]; char *scriptstr,str[65]; int32_t n; if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) { if ( n == 2 ) @@ -307,14 +340,23 @@ UniValue musig_calcmsg(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) scriptstr = jstr(jitem(params,1),0); if ( is_hexstr(scriptstr,0) != 0 ) { - CScript scriptPubKey(ParseHex(scriptstr)); + CScript scriptPubKey; + scriptPubKey.resize(strlen(scriptstr)/2); + decode_hex(&scriptPubKey[0],strlen(scriptstr)/2,scriptstr); musig_prevoutmsg(msg,sendtxid,scriptPubKey); - result.push_back(Pair("result","success")); for (i=0; i<32; i++) + { sprintf(&str[i<<1],"%02x",msg[i]); + if ( msg[i] == 0 ) + zeros++; + } str[64] = 0; - result.push_back(Pair("msg",str)); - return(result); + if ( zeros != 32 ) + { + result.push_back(Pair("msg",str)); + result.push_back(Pair("result","success")); + return(result); + } else return(cclib_error(result,"null result, make sure params are sendtxid, scriptPubKey")); } else return(cclib_error(result,"script is not hex")); } else return(cclib_error(result,"need exactly 2 parameters: sendtxid, scriptPubKey")); } else return(cclib_error(result,"couldnt parse params")); From ebc07912fdb319358e162ec5be149f8e03bd5c0f Mon Sep 17 00:00:00 2001 From: blackjok3r Date: Sat, 23 Feb 2019 15:18:18 +0800 Subject: [PATCH 313/390] fix rogue ipaddress thing for Alright. Needs to be tested! --- depends/packages/boost.mk | 6 +-- src/cc/rogue/main.c | 2 + src/musigtest.py | 91 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 96 insertions(+), 3 deletions(-) create mode 100755 src/musigtest.py diff --git a/depends/packages/boost.mk b/depends/packages/boost.mk index 7a0439ba7..3c180b0ce 100644 --- a/depends/packages/boost.mk +++ b/depends/packages/boost.mk @@ -1,8 +1,8 @@ package=boost -$(package)_version=1_69_0 -$(package)_download_path=https://dl.bintray.com/boostorg/release/1.69.0/source +$(package)_version=1_66_0 +$(package)_download_path=https://dl.bintray.com/boostorg/release/1.66.0/source $(package)_file_name=$(package)_$($(package)_version).tar.bz2 -$(package)_sha256_hash=8f32d4617390d1c2d16f26a27ab60d97807b35440d45891fa340fc2648b04406 +$(package)_sha256_hash=5721818253e6a0989583192f96782c4a98eb6204965316df9f5ad75819225ca9 define $(package)_set_vars $(package)_config_opts_release=variant=release diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index 3461445ee..6fc3d36c8 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -802,6 +802,8 @@ int main(int argc, char **argv, char **envp) } ASSETCHAINS_SYMBOL[j++] = 0; ROGUE_PORT = komodo_userpass(userpass,ASSETCHAINS_SYMBOL,IPADDRESS); + if ( IPADDRESS[0] == 0 ) + strcopy("127.0.0.1",IPADDRESS); printf("ASSETCHAINS_SYMBOL.(%s) port.%u (%s)\n",ASSETCHAINS_SYMBOL,ROGUE_PORT,USERPASS); sleep(1); if ( argc == 2 && (fp=fopen(argv[1],"rb")) == 0 ) { diff --git a/src/musigtest.py b/src/musigtest.py new file mode 100755 index 000000000..f5f25d250 --- /dev/null +++ b/src/musigtest.py @@ -0,0 +1,91 @@ +#!/usr/bin/env python3 +import platform +import os +import re +import json +import random +import base58 +import binascii +import hashlib +import sys +from slickrpc import Proxy + +# fucntion to define rpc_connection +def def_credentials(chain): + rpcport = ''; + operating_system = platform.system() + if operating_system == 'Darwin': + ac_dir = os.environ['HOME'] + '/Library/Application Support/Komodo' + elif operating_system == 'Linux': + ac_dir = os.environ['HOME'] + '/.komodo' + elif operating_system == 'Windows': + ac_dir = '%s/komodo/' % os.environ['APPDATA'] + if chain == 'KMD': + coin_config_file = str(ac_dir + '/komodo.conf') + else: + coin_config_file = str(ac_dir + '/' + chain + '/' + chain + '.conf') + with open(coin_config_file, 'r') as f: + for line in f: + l = line.rstrip() + if re.search('rpcuser', l): + rpcuser = l.replace('rpcuser=', '') + elif re.search('rpcpassword', l): + rpcpassword = l.replace('rpcpassword=', '') + elif re.search('rpcport', l): + rpcport = l.replace('rpcport=', '') + if len(rpcport) == 0: + if chain == 'KMD': + rpcport = 7771 + else: + print("rpcport not in conf file, exiting") + print("check " + coin_config_file) + exit(1) + return (Proxy("http://%s:%s@127.0.0.1:%d" % (rpcuser, rpcpassword, int(rpcport)))) + + +# generate address, validate address, dump private key +def genvaldump(rpc_connection): + # get new address + address = rpc_connection.getnewaddress() + # validate address + validateaddress_result = rpc_connection.validateaddress(address) + pubkey = validateaddress_result['pubkey'] + address = validateaddress_result['address'] + # dump private key for the address + privkey = rpc_connection.dumpprivkey(address) + # function output + output = [pubkey, privkey, address] + return(output) + +CHAIN = 'MUSIG' #sys.argv[1] + +rpc = def_credentials(CHAIN) + +pubkeys = [] +address_info = [] +ret = input('Do you want to generate new pubkeys? ').lower() + +if ret.startswith('y'): + numpks = int(input('Enter number of pubkeys to combine: ')) + if os.path.isfile("list.json"): + print('Already have list.json, move it if you would like to generate a new set.') + sys.exit(0) + while len(address_info) < numpks: + addressinfo = genvaldump(rpc) + address_info.append(addressinfo) + f = open("list.json", "w+") + f.write(json.dumps(address_info)) +else: + if os.path.isfile("list.json"): + with open('list.json') as list: + address_info = json.load(list) + else: + sys.exit('No list.json you need to create new pubkeys!') + +for addressinfo in address_info: + pubkeys.append(addressinfo[0]) + +ret = rpc.setpubkey(pubkeys[0]) +combinedpk = rpc.cclib("combine", "18", str(pubkeys))['combined_pk'] + +print('Your combined pubkey is: ' + combinedpk) From fb82fc82aaae27fc885a0ad156747bbfbde0b78a Mon Sep 17 00:00:00 2001 From: blackjok3r Date: Sat, 23 Feb 2019 15:23:08 +0800 Subject: [PATCH 314/390] fix --- src/cc/rogue/main.c | 2 +- src/musigtest.py | 91 --------------------------------------------- 2 files changed, 1 insertion(+), 92 deletions(-) delete mode 100755 src/musigtest.py diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index 6fc3d36c8..4dfc0a70a 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -803,7 +803,7 @@ int main(int argc, char **argv, char **envp) ASSETCHAINS_SYMBOL[j++] = 0; ROGUE_PORT = komodo_userpass(userpass,ASSETCHAINS_SYMBOL,IPADDRESS); if ( IPADDRESS[0] == 0 ) - strcopy("127.0.0.1",IPADDRESS); + strcpy("127.0.0.1",IPADDRESS); printf("ASSETCHAINS_SYMBOL.(%s) port.%u (%s)\n",ASSETCHAINS_SYMBOL,ROGUE_PORT,USERPASS); sleep(1); if ( argc == 2 && (fp=fopen(argv[1],"rb")) == 0 ) { diff --git a/src/musigtest.py b/src/musigtest.py deleted file mode 100755 index f5f25d250..000000000 --- a/src/musigtest.py +++ /dev/null @@ -1,91 +0,0 @@ -#!/usr/bin/env python3 -import platform -import os -import re -import json -import random -import base58 -import binascii -import hashlib -import sys -from slickrpc import Proxy - -# fucntion to define rpc_connection -def def_credentials(chain): - rpcport = ''; - operating_system = platform.system() - if operating_system == 'Darwin': - ac_dir = os.environ['HOME'] + '/Library/Application Support/Komodo' - elif operating_system == 'Linux': - ac_dir = os.environ['HOME'] + '/.komodo' - elif operating_system == 'Windows': - ac_dir = '%s/komodo/' % os.environ['APPDATA'] - if chain == 'KMD': - coin_config_file = str(ac_dir + '/komodo.conf') - else: - coin_config_file = str(ac_dir + '/' + chain + '/' + chain + '.conf') - with open(coin_config_file, 'r') as f: - for line in f: - l = line.rstrip() - if re.search('rpcuser', l): - rpcuser = l.replace('rpcuser=', '') - elif re.search('rpcpassword', l): - rpcpassword = l.replace('rpcpassword=', '') - elif re.search('rpcport', l): - rpcport = l.replace('rpcport=', '') - if len(rpcport) == 0: - if chain == 'KMD': - rpcport = 7771 - else: - print("rpcport not in conf file, exiting") - print("check " + coin_config_file) - exit(1) - return (Proxy("http://%s:%s@127.0.0.1:%d" % (rpcuser, rpcpassword, int(rpcport)))) - - -# generate address, validate address, dump private key -def genvaldump(rpc_connection): - # get new address - address = rpc_connection.getnewaddress() - # validate address - validateaddress_result = rpc_connection.validateaddress(address) - pubkey = validateaddress_result['pubkey'] - address = validateaddress_result['address'] - # dump private key for the address - privkey = rpc_connection.dumpprivkey(address) - # function output - output = [pubkey, privkey, address] - return(output) - -CHAIN = 'MUSIG' #sys.argv[1] - -rpc = def_credentials(CHAIN) - -pubkeys = [] -address_info = [] -ret = input('Do you want to generate new pubkeys? ').lower() - -if ret.startswith('y'): - numpks = int(input('Enter number of pubkeys to combine: ')) - if os.path.isfile("list.json"): - print('Already have list.json, move it if you would like to generate a new set.') - sys.exit(0) - while len(address_info) < numpks: - addressinfo = genvaldump(rpc) - address_info.append(addressinfo) - f = open("list.json", "w+") - f.write(json.dumps(address_info)) -else: - if os.path.isfile("list.json"): - with open('list.json') as list: - address_info = json.load(list) - else: - sys.exit('No list.json you need to create new pubkeys!') - -for addressinfo in address_info: - pubkeys.append(addressinfo[0]) - -ret = rpc.setpubkey(pubkeys[0]) -combinedpk = rpc.cclib("combine", "18", str(pubkeys))['combined_pk'] - -print('Your combined pubkey is: ' + combinedpk) From 9ed121b9477012c42e16acb4ec4cebf38b39cb6d Mon Sep 17 00:00:00 2001 From: blackjok3r Date: Sat, 23 Feb 2019 15:24:23 +0800 Subject: [PATCH 315/390] undo --- depends/packages/boost.mk | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/depends/packages/boost.mk b/depends/packages/boost.mk index 3c180b0ce..7a0439ba7 100644 --- a/depends/packages/boost.mk +++ b/depends/packages/boost.mk @@ -1,8 +1,8 @@ package=boost -$(package)_version=1_66_0 -$(package)_download_path=https://dl.bintray.com/boostorg/release/1.66.0/source +$(package)_version=1_69_0 +$(package)_download_path=https://dl.bintray.com/boostorg/release/1.69.0/source $(package)_file_name=$(package)_$($(package)_version).tar.bz2 -$(package)_sha256_hash=5721818253e6a0989583192f96782c4a98eb6204965316df9f5ad75819225ca9 +$(package)_sha256_hash=8f32d4617390d1c2d16f26a27ab60d97807b35440d45891fa340fc2648b04406 define $(package)_set_vars $(package)_config_opts_release=variant=release From aa6b693feecac75cf90c4dd3657499f13818d220 Mon Sep 17 00:00:00 2001 From: blackjok3r Date: Sat, 23 Feb 2019 15:26:18 +0800 Subject: [PATCH 316/390] fix strcpy --- src/cc/rogue/main.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index 4dfc0a70a..165f01dfd 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -803,7 +803,7 @@ int main(int argc, char **argv, char **envp) ASSETCHAINS_SYMBOL[j++] = 0; ROGUE_PORT = komodo_userpass(userpass,ASSETCHAINS_SYMBOL,IPADDRESS); if ( IPADDRESS[0] == 0 ) - strcpy("127.0.0.1",IPADDRESS); + strcpy(IPADDRESS,"127.0.0.1"); printf("ASSETCHAINS_SYMBOL.(%s) port.%u (%s)\n",ASSETCHAINS_SYMBOL,ROGUE_PORT,USERPASS); sleep(1); if ( argc == 2 && (fp=fopen(argv[1],"rb")) == 0 ) { From 9df722e1b6a5f82254bcf7281e3a4f365f200023 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 22 Feb 2019 21:04:55 -1100 Subject: [PATCH 317/390] Dilithium lib --- src/cc/cclib.cpp | 3 +- src/cc/dilithium.c | 2837 ++++++++++++++++++++++++++++++++++++++++++++ src/cc/dilithium.h | 474 ++++++++ src/cc/makecclib | 2 +- src/cc/musig.cpp | 4 +- 5 files changed, 3316 insertions(+), 4 deletions(-) create mode 100644 src/cc/dilithium.c create mode 100644 src/cc/dilithium.h diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index c770917ea..84f229069 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -581,6 +581,7 @@ uint256 juint256(cJSON *obj) #else #include "sudoku.cpp" #include "musig.cpp" -#include "../secp256k1/src/modules/musig/example.c" +#inclide "dilithium.c" +//#include "../secp256k1/src/modules/musig/example.c" #endif diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c new file mode 100644 index 000000000..b6624353e --- /dev/null +++ b/src/cc/dilithium.c @@ -0,0 +1,2837 @@ +/* Based on the public domain implementation in + * crypto_hash/keccakc512/simple/ from http://bench.cr.yp.to/supercop.html + * by Ronny Van Keer + * and the public domain "TweetFips202" implementation + * from https://twitter.com/tweetfips202 + * by Gilles Van Assche, Daniel J. Bernstein, and Peter Schwabe */ + +#include +#include "dilithium.h" + + +#define NROUNDS 24 +#define ROL(a, offset) ((a << offset) ^ (a >> (64-offset))) + +/************************************************* +* Name: load64 +* +* Description: Load 8 bytes into uint64_t in little-endian order +* +* Arguments: - const uint8_t *x: pointer to input byte array +* +* Returns the loaded 64-bit unsigned integer +**************************************************/ +static uint64_t load64(const uint8_t *x) { + uint32_t i; + uint64_t r = 0; + + for (i = 0; i < 8; ++i) + r |= (uint64_t)x[i] << 8*i; + + return r; +} + +/************************************************* +* Name: store64 +* +* Description: Store a 64-bit integer to array of 8 bytes in little-endian order +* +* Arguments: - uint8_t *x: pointer to the output byte array (allocated) +* - uint64_t u: input 64-bit unsigned integer +**************************************************/ +static void store64(uint8_t *x, uint64_t u) { + uint32_t i; + + for(i = 0; i < 8; ++i) + x[i] = u >> 8*i; +} + +/* Keccak round constants */ +static const uint64_t KeccakF_RoundConstants[NROUNDS] = { + (uint64_t)0x0000000000000001ULL, + (uint64_t)0x0000000000008082ULL, + (uint64_t)0x800000000000808aULL, + (uint64_t)0x8000000080008000ULL, + (uint64_t)0x000000000000808bULL, + (uint64_t)0x0000000080000001ULL, + (uint64_t)0x8000000080008081ULL, + (uint64_t)0x8000000000008009ULL, + (uint64_t)0x000000000000008aULL, + (uint64_t)0x0000000000000088ULL, + (uint64_t)0x0000000080008009ULL, + (uint64_t)0x000000008000000aULL, + (uint64_t)0x000000008000808bULL, + (uint64_t)0x800000000000008bULL, + (uint64_t)0x8000000000008089ULL, + (uint64_t)0x8000000000008003ULL, + (uint64_t)0x8000000000008002ULL, + (uint64_t)0x8000000000000080ULL, + (uint64_t)0x000000000000800aULL, + (uint64_t)0x800000008000000aULL, + (uint64_t)0x8000000080008081ULL, + (uint64_t)0x8000000000008080ULL, + (uint64_t)0x0000000080000001ULL, + (uint64_t)0x8000000080008008ULL +}; + +/************************************************* +* Name: KeccakF1600_StatePermute +* +* Description: The Keccak F1600 Permutation +* +* Arguments: - uint64_t *state: pointer to input/output Keccak state +**************************************************/ +static void KeccakF1600_StatePermute(uint64_t *state) +{ + int round; + + uint64_t Aba, Abe, Abi, Abo, Abu; + uint64_t Aga, Age, Agi, Ago, Agu; + uint64_t Aka, Ake, Aki, Ako, Aku; + uint64_t Ama, Ame, Ami, Amo, Amu; + uint64_t Asa, Ase, Asi, Aso, Asu; + uint64_t BCa, BCe, BCi, BCo, BCu; + uint64_t Da, De, Di, Do, Du; + uint64_t Eba, Ebe, Ebi, Ebo, Ebu; + uint64_t Ega, Ege, Egi, Ego, Egu; + uint64_t Eka, Eke, Eki, Eko, Eku; + uint64_t Ema, Eme, Emi, Emo, Emu; + uint64_t Esa, Ese, Esi, Eso, Esu; + + //copyFromState(A, state) + Aba = state[ 0]; + Abe = state[ 1]; + Abi = state[ 2]; + Abo = state[ 3]; + Abu = state[ 4]; + Aga = state[ 5]; + Age = state[ 6]; + Agi = state[ 7]; + Ago = state[ 8]; + Agu = state[ 9]; + Aka = state[10]; + Ake = state[11]; + Aki = state[12]; + Ako = state[13]; + Aku = state[14]; + Ama = state[15]; + Ame = state[16]; + Ami = state[17]; + Amo = state[18]; + Amu = state[19]; + Asa = state[20]; + Ase = state[21]; + Asi = state[22]; + Aso = state[23]; + Asu = state[24]; + + for( round = 0; round < NROUNDS; round += 2 ) + { + // prepareTheta + BCa = Aba^Aga^Aka^Ama^Asa; + BCe = Abe^Age^Ake^Ame^Ase; + BCi = Abi^Agi^Aki^Ami^Asi; + BCo = Abo^Ago^Ako^Amo^Aso; + BCu = Abu^Agu^Aku^Amu^Asu; + + //thetaRhoPiChiIotaPrepareTheta(round , A, E) + Da = BCu^ROL(BCe, 1); + De = BCa^ROL(BCi, 1); + Di = BCe^ROL(BCo, 1); + Do = BCi^ROL(BCu, 1); + Du = BCo^ROL(BCa, 1); + + Aba ^= Da; + BCa = Aba; + Age ^= De; + BCe = ROL(Age, 44); + Aki ^= Di; + BCi = ROL(Aki, 43); + Amo ^= Do; + BCo = ROL(Amo, 21); + Asu ^= Du; + BCu = ROL(Asu, 14); + Eba = BCa ^((~BCe)& BCi ); + Eba ^= (uint64_t)KeccakF_RoundConstants[round]; + Ebe = BCe ^((~BCi)& BCo ); + Ebi = BCi ^((~BCo)& BCu ); + Ebo = BCo ^((~BCu)& BCa ); + Ebu = BCu ^((~BCa)& BCe ); + + Abo ^= Do; + BCa = ROL(Abo, 28); + Agu ^= Du; + BCe = ROL(Agu, 20); + Aka ^= Da; + BCi = ROL(Aka, 3); + Ame ^= De; + BCo = ROL(Ame, 45); + Asi ^= Di; + BCu = ROL(Asi, 61); + Ega = BCa ^((~BCe)& BCi ); + Ege = BCe ^((~BCi)& BCo ); + Egi = BCi ^((~BCo)& BCu ); + Ego = BCo ^((~BCu)& BCa ); + Egu = BCu ^((~BCa)& BCe ); + + Abe ^= De; + BCa = ROL(Abe, 1); + Agi ^= Di; + BCe = ROL(Agi, 6); + Ako ^= Do; + BCi = ROL(Ako, 25); + Amu ^= Du; + BCo = ROL(Amu, 8); + Asa ^= Da; + BCu = ROL(Asa, 18); + Eka = BCa ^((~BCe)& BCi ); + Eke = BCe ^((~BCi)& BCo ); + Eki = BCi ^((~BCo)& BCu ); + Eko = BCo ^((~BCu)& BCa ); + Eku = BCu ^((~BCa)& BCe ); + + Abu ^= Du; + BCa = ROL(Abu, 27); + Aga ^= Da; + BCe = ROL(Aga, 36); + Ake ^= De; + BCi = ROL(Ake, 10); + Ami ^= Di; + BCo = ROL(Ami, 15); + Aso ^= Do; + BCu = ROL(Aso, 56); + Ema = BCa ^((~BCe)& BCi ); + Eme = BCe ^((~BCi)& BCo ); + Emi = BCi ^((~BCo)& BCu ); + Emo = BCo ^((~BCu)& BCa ); + Emu = BCu ^((~BCa)& BCe ); + + Abi ^= Di; + BCa = ROL(Abi, 62); + Ago ^= Do; + BCe = ROL(Ago, 55); + Aku ^= Du; + BCi = ROL(Aku, 39); + Ama ^= Da; + BCo = ROL(Ama, 41); + Ase ^= De; + BCu = ROL(Ase, 2); + Esa = BCa ^((~BCe)& BCi ); + Ese = BCe ^((~BCi)& BCo ); + Esi = BCi ^((~BCo)& BCu ); + Eso = BCo ^((~BCu)& BCa ); + Esu = BCu ^((~BCa)& BCe ); + + // prepareTheta + BCa = Eba^Ega^Eka^Ema^Esa; + BCe = Ebe^Ege^Eke^Eme^Ese; + BCi = Ebi^Egi^Eki^Emi^Esi; + BCo = Ebo^Ego^Eko^Emo^Eso; + BCu = Ebu^Egu^Eku^Emu^Esu; + + //thetaRhoPiChiIotaPrepareTheta(round+1, E, A) + Da = BCu^ROL(BCe, 1); + De = BCa^ROL(BCi, 1); + Di = BCe^ROL(BCo, 1); + Do = BCi^ROL(BCu, 1); + Du = BCo^ROL(BCa, 1); + + Eba ^= Da; + BCa = Eba; + Ege ^= De; + BCe = ROL(Ege, 44); + Eki ^= Di; + BCi = ROL(Eki, 43); + Emo ^= Do; + BCo = ROL(Emo, 21); + Esu ^= Du; + BCu = ROL(Esu, 14); + Aba = BCa ^((~BCe)& BCi ); + Aba ^= (uint64_t)KeccakF_RoundConstants[round+1]; + Abe = BCe ^((~BCi)& BCo ); + Abi = BCi ^((~BCo)& BCu ); + Abo = BCo ^((~BCu)& BCa ); + Abu = BCu ^((~BCa)& BCe ); + + Ebo ^= Do; + BCa = ROL(Ebo, 28); + Egu ^= Du; + BCe = ROL(Egu, 20); + Eka ^= Da; + BCi = ROL(Eka, 3); + Eme ^= De; + BCo = ROL(Eme, 45); + Esi ^= Di; + BCu = ROL(Esi, 61); + Aga = BCa ^((~BCe)& BCi ); + Age = BCe ^((~BCi)& BCo ); + Agi = BCi ^((~BCo)& BCu ); + Ago = BCo ^((~BCu)& BCa ); + Agu = BCu ^((~BCa)& BCe ); + + Ebe ^= De; + BCa = ROL(Ebe, 1); + Egi ^= Di; + BCe = ROL(Egi, 6); + Eko ^= Do; + BCi = ROL(Eko, 25); + Emu ^= Du; + BCo = ROL(Emu, 8); + Esa ^= Da; + BCu = ROL(Esa, 18); + Aka = BCa ^((~BCe)& BCi ); + Ake = BCe ^((~BCi)& BCo ); + Aki = BCi ^((~BCo)& BCu ); + Ako = BCo ^((~BCu)& BCa ); + Aku = BCu ^((~BCa)& BCe ); + + Ebu ^= Du; + BCa = ROL(Ebu, 27); + Ega ^= Da; + BCe = ROL(Ega, 36); + Eke ^= De; + BCi = ROL(Eke, 10); + Emi ^= Di; + BCo = ROL(Emi, 15); + Eso ^= Do; + BCu = ROL(Eso, 56); + Ama = BCa ^((~BCe)& BCi ); + Ame = BCe ^((~BCi)& BCo ); + Ami = BCi ^((~BCo)& BCu ); + Amo = BCo ^((~BCu)& BCa ); + Amu = BCu ^((~BCa)& BCe ); + + Ebi ^= Di; + BCa = ROL(Ebi, 62); + Ego ^= Do; + BCe = ROL(Ego, 55); + Eku ^= Du; + BCi = ROL(Eku, 39); + Ema ^= Da; + BCo = ROL(Ema, 41); + Ese ^= De; + BCu = ROL(Ese, 2); + Asa = BCa ^((~BCe)& BCi ); + Ase = BCe ^((~BCi)& BCo ); + Asi = BCi ^((~BCo)& BCu ); + Aso = BCo ^((~BCu)& BCa ); + Asu = BCu ^((~BCa)& BCe ); + } + + //copyToState(state, A) + state[ 0] = Aba; + state[ 1] = Abe; + state[ 2] = Abi; + state[ 3] = Abo; + state[ 4] = Abu; + state[ 5] = Aga; + state[ 6] = Age; + state[ 7] = Agi; + state[ 8] = Ago; + state[ 9] = Agu; + state[10] = Aka; + state[11] = Ake; + state[12] = Aki; + state[13] = Ako; + state[14] = Aku; + state[15] = Ama; + state[16] = Ame; + state[17] = Ami; + state[18] = Amo; + state[19] = Amu; + state[20] = Asa; + state[21] = Ase; + state[22] = Asi; + state[23] = Aso; + state[24] = Asu; +} + +/************************************************* +* Name: keccak_absorb +* +* Description: Absorb step of Keccak; +* non-incremental, starts by zeroeing the state. +* +* Arguments: - uint64_t *s: pointer to (uninitialized) output Keccak state +* - unsigned int r: rate in bytes (e.g., 168 for SHAKE128) +* - const uint8_t *m: pointer to input to be absorbed into s +* - int32_t mlen: length of input in bytes +* - uint8_t p: domain-separation byte for different +* Keccak-derived functions +**************************************************/ +static void keccak_absorb(uint64_t *s, + uint32_t r, + const uint8_t *m, + int32_t mlen, + uint8_t p) +{ + uint32_t i; + uint8_t t[200]; + DBENCH_START(); + + /* Zero state */ + for(i = 0; i < 25; ++i) + s[i] = 0; + + while(mlen >= r) { + for(i = 0; i < r/8; ++i) + s[i] ^= load64(m + 8*i); + + KeccakF1600_StatePermute(s); + mlen -= r; + m += r; + } + + for(i = 0; i < r; ++i) + t[i] = 0; + for(i = 0; i < mlen; ++i) + t[i] = m[i]; + t[i] = p; + t[r-1] |= 128; + for(i = 0; i < r/8; ++i) + s[i] ^= load64(t + 8*i); + + DBENCH_STOP(*tshake); +} + +/************************************************* +* Name: keccak_squeezeblocks +* +* Description: Squeeze step of Keccak. Squeezes full blocks of r bytes each. +* Modifies the state. Can be called multiple times to keep +* squeezing, i.e., is incremental. +* +* Arguments: - uint8_t *h: pointer to output blocks +* - int32_t int nblocks: number of blocks to be +* squeezed (written to h) +* - uint64_t *s: pointer to input/output Keccak state +* - uint32_t r: rate in bytes (e.g., 168 for SHAKE128) +**************************************************/ +static void keccak_squeezeblocks(uint8_t *h, + int32_t nblocks, + uint64_t *s, + uint32_t r) +{ + uint32_t i; + DBENCH_START(); + + while(nblocks > 0) { + KeccakF1600_StatePermute(s); + for(i=0; i < (r >> 3); i++) { + store64(h + 8*i, s[i]); + } + h += r; + --nblocks; + } + + DBENCH_STOP(*tshake); +} + +/************************************************* +* Name: shake128_absorb +* +* Description: Absorb step of the SHAKE128 XOF. +* non-incremental, starts by zeroeing the state. +* +* Arguments: - uint64_t *s: pointer to (uninitialized) output Keccak state +* - const uint8_t *input: pointer to input to be absorbed +* into s +* - int32_t inlen: length of input in bytes +**************************************************/ +void shake128_absorb(uint64_t *s, + const uint8_t *input, + int32_t inlen) +{ + keccak_absorb(s, SHAKE128_RATE, input, inlen, 0x1F); +} + +/************************************************* +* Name: shake128_squeezeblocks +* +* Description: Squeeze step of SHAKE128 XOF. Squeezes full blocks of +* SHAKE128_RATE bytes each. Modifies the state. Can be called +* multiple times to keep squeezing, i.e., is incremental. +* +* Arguments: - uint8_t *output: pointer to output blocks +* - int32_t nblocks: number of blocks to be squeezed +* (written to output) +* - uint64_t *s: pointer to input/output Keccak state +**************************************************/ +void shake128_squeezeblocks(uint8_t *output, + int32_t nblocks, + uint64_t *s) +{ + keccak_squeezeblocks(output, nblocks, s, SHAKE128_RATE); +} + +/************************************************* +* Name: shake256_absorb +* +* Description: Absorb step of the SHAKE256 XOF. +* non-incremental, starts by zeroeing the state. +* +* Arguments: - uint64_t *s: pointer to (uninitialized) output Keccak state +* - const uint8_t *input: pointer to input to be absorbed +* into s +* - int32_t inlen: length of input in bytes +**************************************************/ +void shake256_absorb(uint64_t *s, + const uint8_t *input, + int32_t inlen) +{ + keccak_absorb(s, SHAKE256_RATE, input, inlen, 0x1F); +} + +/************************************************* +* Name: shake256_squeezeblocks +* +* Description: Squeeze step of SHAKE256 XOF. Squeezes full blocks of +* SHAKE256_RATE bytes each. Modifies the state. Can be called +* multiple times to keep squeezing, i.e., is incremental. +* +* Arguments: - uint8_t *output: pointer to output blocks +* - int32_t nblocks: number of blocks to be squeezed +* (written to output) +* - uint64_t *s: pointer to input/output Keccak state +**************************************************/ +void shake256_squeezeblocks(uint8_t *output, + int32_t nblocks, + uint64_t *s) +{ + keccak_squeezeblocks(output, nblocks, s, SHAKE256_RATE); +} + +/************************************************* +* Name: shake128 +* +* Description: SHAKE128 XOF with non-incremental API +* +* Arguments: - uint8_t *output: pointer to output +* - int32_t outlen: requested output length in bytes +* - const uint8_t *input: pointer to input +* - int32_t inlen: length of input in bytes +**************************************************/ +void shake128(uint8_t *output, + int32_t outlen, + const uint8_t *input, + int32_t inlen) +{ + uint32_t i,nblocks = outlen/SHAKE128_RATE; + uint8_t t[SHAKE128_RATE]; + uint64_t s[25]; + + shake128_absorb(s, input, inlen); + shake128_squeezeblocks(output, nblocks, s); + + output += nblocks*SHAKE128_RATE; + outlen -= nblocks*SHAKE128_RATE; + + if(outlen) { + shake128_squeezeblocks(t, 1, s); + for(i = 0; i < outlen; ++i) + output[i] = t[i]; + } +} + +/************************************************* +* Name: shake256 +* +* Description: SHAKE256 XOF with non-incremental API +* +* Arguments: - uint8_t *output: pointer to output +* - int32_t outlen: requested output length in bytes +* - const uint8_t *input: pointer to input +* - int32_t inlen: length of input in bytes +**************************************************/ +void shake256(uint8_t *output, + int32_t outlen, + const uint8_t *input, + int32_t inlen) +{ + uint32_t i,nblocks = outlen/SHAKE256_RATE; + uint8_t t[SHAKE256_RATE]; + uint64_t s[25]; + + shake256_absorb(s, input, inlen); + shake256_squeezeblocks(output, nblocks, s); + + output += nblocks*SHAKE256_RATE; + outlen -= nblocks*SHAKE256_RATE; + + if(outlen) { + shake256_squeezeblocks(t, 1, s); + for(i = 0; i < outlen; ++i) + output[i] = t[i]; + } +} +//#include "params.h" +//#include "reduce.h" +//#include "ntt.h" +//#include "poly.h" + +/* Roots of unity in order needed by forward ntt */ +static const uint32_t zetas[N] = {0, 25847, 5771523, 7861508, 237124, 7602457, 7504169, 466468, 1826347, 2353451, 8021166, 6288512, 3119733, 5495562, 3111497, 2680103, 2725464, 1024112, 7300517, 3585928, 7830929, 7260833, 2619752, 6271868, 6262231, 4520680, 6980856, 5102745, 1757237, 8360995, 4010497, 280005, 2706023, 95776, 3077325, 3530437, 6718724, 4788269, 5842901, 3915439, 4519302, 5336701, 3574422, 5512770, 3539968, 8079950, 2348700, 7841118, 6681150, 6736599, 3505694, 4558682, 3507263, 6239768, 6779997, 3699596, 811944, 531354, 954230, 3881043, 3900724, 5823537, 2071892, 5582638, 4450022, 6851714, 4702672, 5339162, 6927966, 3475950, 2176455, 6795196, 7122806, 1939314, 4296819, 7380215, 5190273, 5223087, 4747489, 126922, 3412210, 7396998, 2147896, 2715295, 5412772, 4686924, 7969390, 5903370, 7709315, 7151892, 8357436, 7072248, 7998430, 1349076, 1852771, 6949987, 5037034, 264944, 508951, 3097992, 44288, 7280319, 904516, 3958618, 4656075, 8371839, 1653064, 5130689, 2389356, 8169440, 759969, 7063561, 189548, 4827145, 3159746, 6529015, 5971092, 8202977, 1315589, 1341330, 1285669, 6795489, 7567685, 6940675, 5361315, 4499357, 4751448, 3839961, 2091667, 3407706, 2316500, 3817976, 5037939, 2244091, 5933984, 4817955, 266997, 2434439, 7144689, 3513181, 4860065, 4621053, 7183191, 5187039, 900702, 1859098, 909542, 819034, 495491, 6767243, 8337157, 7857917, 7725090, 5257975, 2031748, 3207046, 4823422, 7855319, 7611795, 4784579, 342297, 286988, 5942594, 4108315, 3437287, 5038140, 1735879, 203044, 2842341, 2691481, 5790267, 1265009, 4055324, 1247620, 2486353, 1595974, 4613401, 1250494, 2635921, 4832145, 5386378, 1869119, 1903435, 7329447, 7047359, 1237275, 5062207, 6950192, 7929317, 1312455, 3306115, 6417775, 7100756, 1917081, 5834105, 7005614, 1500165, 777191, 2235880, 3406031, 7838005, 5548557, 6709241, 6533464, 5796124, 4656147, 594136, 4603424, 6366809, 2432395, 2454455, 8215696, 1957272, 3369112, 185531, 7173032, 5196991, 162844, 1616392, 3014001, 810149, 1652634, 4686184, 6581310, 5341501, 3523897, 3866901, 269760, 2213111, 7404533, 1717735, 472078, 7953734, 1723600, 6577327, 1910376, 6712985, 7276084, 8119771, 4546524, 5441381, 6144432, 7959518, 6094090, 183443, 7403526, 1612842, 4834730, 7826001, 3919660, 8332111, 7018208, 3937738, 1400424, 7534263, 1976782}; + +/* Roots of unity in order needed by inverse ntt */ +static const uint32_t zetas_inv[N] = {6403635, 846154, 6979993, 4442679, 1362209, 48306, 4460757, 554416, 3545687, 6767575, 976891, 8196974, 2286327, 420899, 2235985, 2939036, 3833893, 260646, 1104333, 1667432, 6470041, 1803090, 6656817, 426683, 7908339, 6662682, 975884, 6167306, 8110657, 4513516, 4856520, 3038916, 1799107, 3694233, 6727783, 7570268, 5366416, 6764025, 8217573, 3183426, 1207385, 8194886, 5011305, 6423145, 164721, 5925962, 5948022, 2013608, 3776993, 7786281, 3724270, 2584293, 1846953, 1671176, 2831860, 542412, 4974386, 6144537, 7603226, 6880252, 1374803, 2546312, 6463336, 1279661, 1962642, 5074302, 7067962, 451100, 1430225, 3318210, 7143142, 1333058, 1050970, 6476982, 6511298, 2994039, 3548272, 5744496, 7129923, 3767016, 6784443, 5894064, 7132797, 4325093, 7115408, 2590150, 5688936, 5538076, 8177373, 6644538, 3342277, 4943130, 4272102, 2437823, 8093429, 8038120, 3595838, 768622, 525098, 3556995, 5173371, 6348669, 3122442, 655327, 522500, 43260, 1613174, 7884926, 7561383, 7470875, 6521319, 7479715, 3193378, 1197226, 3759364, 3520352, 4867236, 1235728, 5945978, 8113420, 3562462, 2446433, 6136326, 3342478, 4562441, 6063917, 4972711, 6288750, 4540456, 3628969, 3881060, 3019102, 1439742, 812732, 1584928, 7094748, 7039087, 7064828, 177440, 2409325, 1851402, 5220671, 3553272, 8190869, 1316856, 7620448, 210977, 5991061, 3249728, 6727353, 8578, 3724342, 4421799, 7475901, 1100098, 8336129, 5282425, 7871466, 8115473, 3343383, 1430430, 6527646, 7031341, 381987, 1308169, 22981, 1228525, 671102, 2477047, 411027, 3693493, 2967645, 5665122, 6232521, 983419, 4968207, 8253495, 3632928, 3157330, 3190144, 1000202, 4083598, 6441103, 1257611, 1585221, 6203962, 4904467, 1452451, 3041255, 3677745, 1528703, 3930395, 2797779, 6308525, 2556880, 4479693, 4499374, 7426187, 7849063, 7568473, 4680821, 1600420, 2140649, 4873154, 3821735, 4874723, 1643818, 1699267, 539299, 6031717, 300467, 4840449, 2867647, 4805995, 3043716, 3861115, 4464978, 2537516, 3592148, 1661693, 4849980, 5303092, 8284641, 5674394, 8100412, 4369920, 19422, 6623180, 3277672, 1399561, 3859737, 2118186, 2108549, 5760665, 1119584, 549488, 4794489, 1079900, 7356305, 5654953, 5700314, 5268920, 2884855, 5260684, 2091905, 359251, 6026966, 6554070, 7913949, 876248, 777960, 8143293, 518909, 2608894, 8354570}; + +/************************************************* +* Name: ntt +* +* Description: Forward NTT, in-place. No modular reduction is performed after +* additions or subtractions. Hence output coefficients can be up +* to 16*Q larger than the coefficients of the input polynomial. +* Output vector is in bitreversed order. +* +* Arguments: - uint32_t p[N]: input/output coefficient array +**************************************************/ +void ntt(uint32_t p[N]) { + uint32_t len, start, j, k; + uint32_t zeta, t; + + k = 1; + for(len = 128; len > 0; len >>= 1) { + for(start = 0; start < N; start = j + len) { + zeta = zetas[k++]; + for(j = start; j < start + len; ++j) { + t = montgomery_reduce((uint64_t)zeta * p[j + len]); + p[j + len] = p[j] + 2*Q - t; + p[j] = p[j] + t; + } + } + } +} + +/************************************************* +* Name: invntt_frominvmont +* +* Description: Inverse NTT and multiplication by Montgomery factor 2^32. +* In-place. No modular reductions after additions or +* subtractions. Input coefficient need to be smaller than 2*Q. +* Output coefficient are smaller than 2*Q. +* +* Arguments: - uint32_t p[N]: input/output coefficient array +**************************************************/ +void invntt_frominvmont(uint32_t p[N]) { + uint32_t start, len, j, k; + uint32_t t, zeta; + const uint32_t f = (((uint64_t)MONT*MONT % Q) * (Q-1) % Q) * ((Q-1) >> 8) % Q; + + k = 0; + for(len = 1; len < N; len <<= 1) { + for(start = 0; start < N; start = j + len) { + zeta = zetas_inv[k++]; + for(j = start; j < start + len; ++j) { + t = p[j]; + p[j] = t + p[j + len]; + p[j + len] = t + 256*Q - p[j + len]; + p[j + len] = montgomery_reduce((uint64_t)zeta * p[j + len]); + } + } + } + + for(j = 0; j < N; ++j) { + p[j] = montgomery_reduce((uint64_t)f * p[j]); + } +} +//#include "params.h" +//#include "poly.h" +//#include "polyvec.h" +//#include "packing.h" + +/************************************************* +* Name: pack_pk +* +* Description: Bit-pack public key pk = (rho, t1). +* +* Arguments: - uint8_t pk[]: output byte array +* - const uint8_t rho[]: byte array containing rho +* - const polyveck *t1: pointer to vector t1 +**************************************************/ +void pack_pk(uint8_t pk[CRYPTO_PUBLICKEYBYTES], + const uint8_t rho[SEEDBYTES], + const polyveck *t1) +{ + uint32_t i; + + for(i = 0; i < SEEDBYTES; ++i) + pk[i] = rho[i]; + pk += SEEDBYTES; + + for(i = 0; i < K; ++i) + polyt1_pack(pk + i*POLT1_SIZE_PACKED, t1->vec+i); +} + +/************************************************* +* Name: unpack_pk +* +* Description: Unpack public key pk = (rho, t1). +* +* Arguments: - const uint8_t rho[]: output byte array for rho +* - const polyveck *t1: pointer to output vector t1 +* - uint8_t pk[]: byte array containing bit-packed pk +**************************************************/ +void unpack_pk(uint8_t rho[SEEDBYTES], + polyveck *t1, + const uint8_t pk[CRYPTO_PUBLICKEYBYTES]) +{ + uint32_t i; + + for(i = 0; i < SEEDBYTES; ++i) + rho[i] = pk[i]; + pk += SEEDBYTES; + + for(i = 0; i < K; ++i) + polyt1_unpack(t1->vec+i, pk + i*POLT1_SIZE_PACKED); +} + +/************************************************* +* Name: pack_sk +* +* Description: Bit-pack secret key sk = (rho, key, tr, s1, s2, t0). +* +* Arguments: - uint8_t sk[]: output byte array +* - const uint8_t rho[]: byte array containing rho +* - const uint8_t key[]: byte array containing key +* - const uint8_t tr[]: byte array containing tr +* - const polyvecl *s1: pointer to vector s1 +* - const polyveck *s2: pointer to vector s2 +* - const polyveck *t0: pointer to vector t0 +**************************************************/ +void pack_sk(uint8_t sk[CRYPTO_SECRETKEYBYTES], + const uint8_t rho[SEEDBYTES], + const uint8_t key[SEEDBYTES], + const uint8_t tr[CRHBYTES], + const polyvecl *s1, + const polyveck *s2, + const polyveck *t0) +{ + uint32_t i; + + for(i = 0; i < SEEDBYTES; ++i) + sk[i] = rho[i]; + sk += SEEDBYTES; + + for(i = 0; i < SEEDBYTES; ++i) + sk[i] = key[i]; + sk += SEEDBYTES; + + for(i = 0; i < CRHBYTES; ++i) + sk[i] = tr[i]; + sk += CRHBYTES; + + for(i = 0; i < L; ++i) + polyeta_pack(sk + i*POLETA_SIZE_PACKED, s1->vec+i); + sk += L*POLETA_SIZE_PACKED; + + for(i = 0; i < K; ++i) + polyeta_pack(sk + i*POLETA_SIZE_PACKED, s2->vec+i); + sk += K*POLETA_SIZE_PACKED; + + for(i = 0; i < K; ++i) + polyt0_pack(sk + i*POLT0_SIZE_PACKED, t0->vec+i); +} + +/************************************************* +* Name: unpack_sk +* +* Description: Unpack secret key sk = (rho, key, tr, s1, s2, t0). +* +* Arguments: - const uint8_t rho[]: output byte array for rho +* - const uint8_t key[]: output byte array for key +* - const uint8_t tr[]: output byte array for tr +* - const polyvecl *s1: pointer to output vector s1 +* - const polyveck *s2: pointer to output vector s2 +* - const polyveck *r0: pointer to output vector t0 +* - uint8_t sk[]: byte array containing bit-packed sk +**************************************************/ +void unpack_sk(uint8_t rho[SEEDBYTES], + uint8_t key[SEEDBYTES], + uint8_t tr[CRHBYTES], + polyvecl *s1, + polyveck *s2, + polyveck *t0, + const uint8_t sk[CRYPTO_SECRETKEYBYTES]) +{ + uint32_t i; + + for(i = 0; i < SEEDBYTES; ++i) + rho[i] = sk[i]; + sk += SEEDBYTES; + + for(i = 0; i < SEEDBYTES; ++i) + key[i] = sk[i]; + sk += SEEDBYTES; + + for(i = 0; i < CRHBYTES; ++i) + tr[i] = sk[i]; + sk += CRHBYTES; + + for(i=0; i < L; ++i) + polyeta_unpack(s1->vec+i, sk + i*POLETA_SIZE_PACKED); + sk += L*POLETA_SIZE_PACKED; + + for(i=0; i < K; ++i) + polyeta_unpack(s2->vec+i, sk + i*POLETA_SIZE_PACKED); + sk += K*POLETA_SIZE_PACKED; + + for(i=0; i < K; ++i) + polyt0_unpack(t0->vec+i, sk + i*POLT0_SIZE_PACKED); +} + +/************************************************* +* Name: pack_sig +* +* Description: Bit-pack signature sig = (z, h, c). +* +* Arguments: - uint8_t sig[]: output byte array +* - const polyvecl *z: pointer to vector z +* - const polyveck *h: pointer to hint vector h +* - const poly *c: pointer to challenge polynomial +**************************************************/ +void pack_sig(uint8_t sig[CRYPTO_BYTES], + const polyvecl *z, + const polyveck *h, + const poly *c) +{ + uint32_t i, j, k; + uint64_t signs, mask; + + for(i = 0; i < L; ++i) + polyz_pack(sig + i*POLZ_SIZE_PACKED, z->vec+i); + sig += L*POLZ_SIZE_PACKED; + + /* Encode h */ + k = 0; + for(i = 0; i < K; ++i) { + for(j = 0; j < N; ++j) + if(h->vec[i].coeffs[j] != 0) + sig[k++] = j; + + sig[OMEGA + i] = k; + } + while(k < OMEGA) sig[k++] = 0; + sig += OMEGA + K; + + /* Encode c */ + signs = 0; + mask = 1; + for(i = 0; i < N/8; ++i) { + sig[i] = 0; + for(j = 0; j < 8; ++j) { + if(c->coeffs[8*i+j] != 0) { + sig[i] |= (1U << j); + if(c->coeffs[8*i+j] == (Q - 1)) signs |= mask; + mask <<= 1; + } + } + } + sig += N/8; + for(i = 0; i < 8; ++i) + sig[i] = signs >> 8*i; +} + +/************************************************* +* Name: unpack_sig +* +* Description: Unpack signature sig = (z, h, c). +* +* Arguments: - polyvecl *z: pointer to output vector z +* - polyveck *h: pointer to output hint vector h +* - poly *c: pointer to output challenge polynomial +* - const uint8_t sig[]: byte array containing +* bit-packed signature +* +* Returns 1 in case of malformed signature; otherwise 0. +**************************************************/ +int unpack_sig(polyvecl *z, + polyveck *h, + poly *c, + const uint8_t sig[CRYPTO_BYTES]) +{ + uint32_t i, j, k; + uint64_t signs, mask; + + for(i = 0; i < L; ++i) + polyz_unpack(z->vec+i, sig + i*POLZ_SIZE_PACKED); + sig += L*POLZ_SIZE_PACKED; + + /* Decode h */ + k = 0; + for(i = 0; i < K; ++i) { + for(j = 0; j < N; ++j) + h->vec[i].coeffs[j] = 0; + + if(sig[OMEGA + i] < k || sig[OMEGA + i] > OMEGA) + return 1; + + for(j = k; j < sig[OMEGA + i]; ++j) { + /* Coefficients are ordered for strong unforgeability */ + if(j > k && sig[j] <= sig[j-1]) return 1; + h->vec[i].coeffs[sig[j]] = 1; + } + + k = sig[OMEGA + i]; + } + + /* Extra indices are zero for strong unforgeability */ + for(j = k; j < OMEGA; ++j) + if(sig[j]) + return 1; + + sig += OMEGA + K; + + /* Decode c */ + for(i = 0; i < N; ++i) + c->coeffs[i] = 0; + + signs = 0; + for(i = 0; i < 8; ++i) + signs |= (uint64_t)sig[N/8+i] << 8*i; + + /* Extra sign bits are zero for strong unforgeability */ + if(signs >> 60) + return 1; + + mask = 1; + for(i = 0; i < N/8; ++i) { + for(j = 0; j < 8; ++j) { + if((sig[i] >> j) & 0x01) { + c->coeffs[8*i+j] = (signs & mask) ? Q - 1 : 1; + mask <<= 1; + } + } + } + + return 0; +} +//#include +//#include "test/cpucycles.h" +//#include "fips202.h" +//#include "params.h" +//#include "reduce.h" +//#include "rounding.h" +//#include "ntt.h" +//#include "poly.h" + +#ifdef DBENCH +extern const uint64_t timing_overhead; +extern uint64_t *tred, *tadd, *tmul, *tround, *tsample, *tpack; +#endif + +/************************************************* +* Name: poly_reduce +* +* Description: Reduce all coefficients of input polynomial to representative +* in [0,2*Q[. +* +* Arguments: - poly *a: pointer to input/output polynomial +**************************************************/ +void poly_reduce(poly *a) { + uint32_t i; + DBENCH_START(); + + for(i = 0; i < N; ++i) + a->coeffs[i] = reduce32(a->coeffs[i]); + + DBENCH_STOP(*tred); +} + +/************************************************* +* Name: poly_csubq +* +* Description: For all coefficients of input polynomial subtract Q if +* coefficient is bigger than Q. +* +* Arguments: - poly *a: pointer to input/output polynomial +**************************************************/ +void poly_csubq(poly *a) { + uint32_t i; + DBENCH_START(); + + for(i = 0; i < N; ++i) + a->coeffs[i] = csubq(a->coeffs[i]); + + DBENCH_STOP(*tred); +} + +/************************************************* +* Name: poly_freeze +* +* Description: Reduce all coefficients of the polynomial to standard +* representatives. +* +* Arguments: - poly *a: pointer to input/output polynomial +**************************************************/ +void poly_freeze(poly *a) { + uint32_t i; + DBENCH_START(); + + for(i = 0; i < N; ++i) + a->coeffs[i] = freeze(a->coeffs[i]); + + DBENCH_STOP(*tred); +} + +/************************************************* +* Name: poly_add +* +* Description: Add polynomials. No modular reduction is performed. +* +* Arguments: - poly *c: pointer to output polynomial +* - const poly *a: pointer to first summand +* - const poly *b: pointer to second summand +**************************************************/ +void poly_add(poly *c, const poly *a, const poly *b) { + uint32_t i; + DBENCH_START(); + + for(i = 0; i < N; ++i) + c->coeffs[i] = a->coeffs[i] + b->coeffs[i]; + + DBENCH_STOP(*tadd); +} + +/************************************************* +* Name: poly_sub +* +* Description: Subtract polynomials. Assumes coefficients of second input +* polynomial to be less than 2*Q. No modular reduction is +* performed. +* +* Arguments: - poly *c: pointer to output polynomial +* - const poly *a: pointer to first input polynomial +* - const poly *b: pointer to second input polynomial to be +* subtraced from first input polynomial +**************************************************/ +void poly_sub(poly *c, const poly *a, const poly *b) { + uint32_t i; + DBENCH_START(); + + for(i = 0; i < N; ++i) + c->coeffs[i] = a->coeffs[i] + 2*Q - b->coeffs[i]; + + DBENCH_STOP(*tadd); +} + +/************************************************* +* Name: poly_neg +* +* Description: Negate polynomial. Assumes input coefficients to be standard +* representatives. +* +* Arguments: - poly *a: pointer to input/output polynomial +**************************************************/ +void poly_neg(poly *a) { + uint32_t i; + DBENCH_START(); + + for(i = 0; i < N; ++i) + a->coeffs[i] = Q - a->coeffs[i]; + + DBENCH_STOP(*tadd); +} + +/************************************************* +* Name: poly_shiftl +* +* Description: Multiply polynomial by 2^k without modular reduction. Assumes +* input coefficients to be less than 2^{32-k}. +* +* Arguments: - poly *a: pointer to input/output polynomial +* - uint32_t k: exponent +**************************************************/ +void poly_shiftl(poly *a, uint32_t k) { + uint32_t i; + DBENCH_START(); + + for(i = 0; i < N; ++i) + a->coeffs[i] <<= k; + + DBENCH_STOP(*tmul); +} + +/************************************************* +* Name: poly_ntt +* +* Description: Forward NTT. Output coefficients can be up to 16*Q larger than +* input coefficients. +* +* Arguments: - poly *a: pointer to input/output polynomial +**************************************************/ +void poly_ntt(poly *a) { + DBENCH_START(); + + ntt(a->coeffs); + + DBENCH_STOP(*tmul); +} + +/************************************************* +* Name: poly_invntt_montgomery +* +* Description: Inverse NTT and multiplication with 2^{32}. Input coefficients +* need to be less than 2*Q. Output coefficients are less than 2*Q. +* +* Arguments: - poly *a: pointer to input/output polynomial +**************************************************/ +void poly_invntt_montgomery(poly *a) { + DBENCH_START(); + + invntt_frominvmont(a->coeffs); + + DBENCH_STOP(*tmul); +} + +/************************************************* +* Name: poly_pointwise_invmontgomery +* +* Description: Pointwise multiplication of polynomials in NTT domain +* representation and multiplication of resulting polynomial +* with 2^{-32}. Output coefficients are less than 2*Q if input +* coefficient are less than 22*Q. +* +* Arguments: - poly *c: pointer to output polynomial +* - const poly *a: pointer to first input polynomial +* - const poly *b: pointer to second input polynomial +**************************************************/ +void poly_pointwise_invmontgomery(poly *c, const poly *a, const poly *b) { + uint32_t i; + DBENCH_START(); + + for(i = 0; i < N; ++i) + c->coeffs[i] = montgomery_reduce((uint64_t)a->coeffs[i] * b->coeffs[i]); + + DBENCH_STOP(*tmul); +} + +/************************************************* +* Name: poly_power2round +* +* Description: For all coefficients c of the input polynomial, +* compute c0, c1 such that c mod Q = c1*2^D + c0 +* with -2^{D-1} < c0 <= 2^{D-1}. Assumes coefficients to be +* standard representatives. +* +* Arguments: - poly *a1: pointer to output polynomial with coefficients c1 +* - poly *a0: pointer to output polynomial with coefficients Q + a0 +* - const poly *v: pointer to input polynomial +**************************************************/ +void poly_power2round(poly *a1, poly *a0, const poly *a) { + uint32_t i; + DBENCH_START(); + + for(i = 0; i < N; ++i) + a1->coeffs[i] = power2round(a->coeffs[i], a0->coeffs+i); + + DBENCH_STOP(*tround); +} + +/************************************************* +* Name: poly_decompose +* +* Description: For all coefficients c of the input polynomial, +* compute high and low bits c0, c1 such c mod Q = c1*ALPHA + c0 +* with -ALPHA/2 < c0 <= ALPHA/2 except c1 = (Q-1)/ALPHA where we +* set c1 = 0 and -ALPHA/2 <= c0 = c mod Q - Q < 0. +* Assumes coefficients to be standard representatives. +* +* Arguments: - poly *a1: pointer to output polynomial with coefficients c1 +* - poly *a0: pointer to output polynomial with coefficients Q + a0 +* - const poly *c: pointer to input polynomial +**************************************************/ +void poly_decompose(poly *a1, poly *a0, const poly *a) { + uint32_t i; + DBENCH_START(); + + for(i = 0; i < N; ++i) + a1->coeffs[i] = decompose(a->coeffs[i], a0->coeffs+i); + + DBENCH_STOP(*tround); +} + +/************************************************* +* Name: poly_make_hint +* +* Description: Compute hint polynomial. The coefficients of which indicate +* whether the high bits of the corresponding coefficients +* of the first input polynomial and of the sum of the input +* polynomials differ. +* +* Arguments: - poly *h: pointer to output hint polynomial +* - const poly *a: pointer to first input polynomial +* - const poly *b: pointer to second input polynomial +* +* Returns number of 1 bits. +**************************************************/ +uint32_t poly_make_hint(poly *h, const poly *a, const poly *b) { + uint32_t i, s = 0; + DBENCH_START(); + + for(i = 0; i < N; ++i) { + h->coeffs[i] = make_hint(a->coeffs[i], b->coeffs[i]); + s += h->coeffs[i]; + } + + DBENCH_STOP(*tround); + return s; +} + +/************************************************* +* Name: poly_use_hint +* +* Description: Use hint polynomial to correct the high bits of a polynomial. +* +* Arguments: - poly *a: pointer to output polynomial with corrected high bits +* - const poly *b: pointer to input polynomial +* - const poly *h: pointer to input hint polynomial +**************************************************/ +void poly_use_hint(poly *a, const poly *b, const poly *h) { + uint32_t i; + DBENCH_START(); + + for(i = 0; i < N; ++i) + a->coeffs[i] = use_hint(b->coeffs[i], h->coeffs[i]); + + DBENCH_STOP(*tround); +} + +/************************************************* +* Name: poly_chknorm +* +* Description: Check infinity norm of polynomial against given bound. +* Assumes input coefficients to be standard representatives. +* +* Arguments: - const poly *a: pointer to polynomial +* - uint32_t B: norm bound +* +* Returns 0 if norm is strictly smaller than B and 1 otherwise. +**************************************************/ +int poly_chknorm(const poly *a, uint32_t B) { + uint32_t i; + int32_t t; + DBENCH_START(); + + /* It is ok to leak which coefficient violates the bound since + the probability for each coefficient is independent of secret + data but we must not leak the sign of the centralized representative. */ + for(i = 0; i < N; ++i) { + /* Absolute value of centralized representative */ + t = (Q-1)/2 - a->coeffs[i]; + t ^= (t >> 31); + t = (Q-1)/2 - t; + + if((uint32_t)t >= B) { + DBENCH_STOP(*tsample); + return 1; + } + } + + DBENCH_STOP(*tsample); + return 0; +} + +/************************************************* +* Name: poly_uniform +* +* Description: Sample uniformly random polynomial using stream of random bytes. +* Assumes that enough random bytes are given (e.g. +* 5*SHAKE128_RATE bytes). +* +* Arguments: - poly *a: pointer to output polynomial +* - const uint8_t *buf: array of random bytes +**************************************************/ +void poly_uniform(poly *a, const uint8_t *buf) { + uint32_t ctr, pos; + uint32_t t; + DBENCH_START(); + + ctr = pos = 0; + while(ctr < N) { + t = buf[pos++]; + t |= (uint32_t)buf[pos++] << 8; + t |= (uint32_t)buf[pos++] << 16; + t &= 0x7FFFFF; + + if(t < Q) + a->coeffs[ctr++] = t; + } + + DBENCH_STOP(*tsample); +} + +/************************************************* +* Name: rej_eta +* +* Description: Sample uniformly random coefficients in [-ETA, ETA] by +* performing rejection sampling using array of random bytes. +* +* Arguments: - uint32_t *a: pointer to output array (allocated) +* - uint32_t len: number of coefficients to be sampled +* - const uint8_t *buf: array of random bytes +* - uint32_t buflen: length of array of random bytes +* +* Returns number of sampled coefficients. Can be smaller than len if not enough +* random bytes were given. +**************************************************/ +static uint32_t rej_eta(uint32_t *a, + uint32_t len, + const uint8_t *buf, + uint32_t buflen) +{ +#if ETA > 7 +#error "rej_eta() assumes ETA <= 7" +#endif + uint32_t ctr, pos; + uint8_t t0, t1; + DBENCH_START(); + + ctr = pos = 0; + while(ctr < len && pos < buflen) { +#if ETA <= 3 + t0 = buf[pos] & 0x07; + t1 = buf[pos++] >> 5; +#else + t0 = buf[pos] & 0x0F; + t1 = buf[pos++] >> 4; +#endif + + if(t0 <= 2*ETA) + a[ctr++] = Q + ETA - t0; + if(t1 <= 2*ETA && ctr < len) + a[ctr++] = Q + ETA - t1; + } + + DBENCH_STOP(*tsample); + return ctr; +} + +/************************************************* +* Name: poly_uniform_eta +* +* Description: Sample polynomial with uniformly random coefficients +* in [-ETA,ETA] by performing rejection sampling using the +* output stream from SHAKE256(seed|nonce). +* +* Arguments: - poly *a: pointer to output polynomial +* - const uint8_t seed[]: byte array with seed of length +* SEEDBYTES +* - uint8_t nonce: nonce byte +**************************************************/ +void poly_uniform_eta(poly *a, + const uint8_t seed[SEEDBYTES], + uint8_t nonce) +{ + uint32_t i, ctr; + uint8_t inbuf[SEEDBYTES + 1]; + /* Probability that we need more than 2 blocks: < 2^{-84} + Probability that we need more than 3 blocks: < 2^{-352} */ + uint8_t outbuf[2*SHAKE256_RATE]; + uint64_t state[25]; + + for(i= 0; i < SEEDBYTES; ++i) + inbuf[i] = seed[i]; + inbuf[SEEDBYTES] = nonce; + + shake256_absorb(state, inbuf, SEEDBYTES + 1); + shake256_squeezeblocks(outbuf, 2, state); + + ctr = rej_eta(a->coeffs, N, outbuf, 2*SHAKE256_RATE); + if(ctr < N) { + shake256_squeezeblocks(outbuf, 1, state); + rej_eta(a->coeffs + ctr, N - ctr, outbuf, SHAKE256_RATE); + } +} + +/************************************************* +* Name: rej_gamma1m1 +* +* Description: Sample uniformly random coefficients +* in [-(GAMMA1 - 1), GAMMA1 - 1] by performing rejection sampling +* using array of random bytes. +* +* Arguments: - uint32_t *a: pointer to output array (allocated) +* - uint32_t len: number of coefficients to be sampled +* - const uint8_t *buf: array of random bytes +* - uint32_t buflen: length of array of random bytes +* +* Returns number of sampled coefficients. Can be smaller than len if not enough +* random bytes were given. +**************************************************/ +static uint32_t rej_gamma1m1(uint32_t *a, + uint32_t len, + const uint8_t *buf, + uint32_t buflen) +{ +#if GAMMA1 > (1 << 19) +#error "rej_gamma1m1() assumes GAMMA1 - 1 fits in 19 bits" +#endif + uint32_t ctr, pos; + uint32_t t0, t1; + DBENCH_START(); + + ctr = pos = 0; + while(ctr < len && pos + 5 <= buflen) { + t0 = buf[pos]; + t0 |= (uint32_t)buf[pos + 1] << 8; + t0 |= (uint32_t)buf[pos + 2] << 16; + t0 &= 0xFFFFF; + + t1 = buf[pos + 2] >> 4; + t1 |= (uint32_t)buf[pos + 3] << 4; + t1 |= (uint32_t)buf[pos + 4] << 12; + + pos += 5; + + if(t0 <= 2*GAMMA1 - 2) + a[ctr++] = Q + GAMMA1 - 1 - t0; + if(t1 <= 2*GAMMA1 - 2 && ctr < len) + a[ctr++] = Q + GAMMA1 - 1 - t1; + } + + DBENCH_STOP(*tsample); + return ctr; +} + +/************************************************* +* Name: poly_uniform_gamma1m1 +* +* Description: Sample polynomial with uniformly random coefficients +* in [-(GAMMA1 - 1), GAMMA1 - 1] by performing rejection +* sampling on output stream of SHAKE256(seed|nonce). +* +* Arguments: - poly *a: pointer to output polynomial +* - const uint8_t seed[]: byte array with seed of length +* SEEDBYTES + CRHBYTES +* - uint16_t nonce: 16-bit nonce +**************************************************/ +void poly_uniform_gamma1m1(poly *a, + const uint8_t seed[SEEDBYTES + CRHBYTES], + uint16_t nonce) +{ + uint32_t i, ctr; + uint8_t inbuf[SEEDBYTES + CRHBYTES + 2]; + /* Probability that we need more than 5 blocks: < 2^{-81} + Probability that we need more than 6 blocks: < 2^{-467} */ + uint8_t outbuf[5*SHAKE256_RATE]; + uint64_t state[25]; + + for(i = 0; i < SEEDBYTES + CRHBYTES; ++i) + inbuf[i] = seed[i]; + inbuf[SEEDBYTES + CRHBYTES] = nonce & 0xFF; + inbuf[SEEDBYTES + CRHBYTES + 1] = nonce >> 8; + + shake256_absorb(state, inbuf, SEEDBYTES + CRHBYTES + 2); + shake256_squeezeblocks(outbuf, 5, state); + + ctr = rej_gamma1m1(a->coeffs, N, outbuf, 5*SHAKE256_RATE); + if(ctr < N) { + /* There are no bytes left in outbuf + since 5*SHAKE256_RATE is divisible by 5 */ + shake256_squeezeblocks(outbuf, 1, state); + rej_gamma1m1(a->coeffs + ctr, N - ctr, outbuf, SHAKE256_RATE); + } +} + +/************************************************* +* Name: polyeta_pack +* +* Description: Bit-pack polynomial with coefficients in [-ETA,ETA]. +* Input coefficients are assumed to lie in [Q-ETA,Q+ETA]. +* +* Arguments: - uint8_t *r: pointer to output byte array with at least +* POLETA_SIZE_PACKED bytes +* - const poly *a: pointer to input polynomial +**************************************************/ +void polyeta_pack(uint8_t *r, const poly *a) { +#if ETA > 7 +#error "polyeta_pack() assumes ETA <= 7" +#endif + uint32_t i; + uint8_t t[8]; + DBENCH_START(); + +#if ETA <= 3 + for(i = 0; i < N/8; ++i) { + t[0] = Q + ETA - a->coeffs[8*i+0]; + t[1] = Q + ETA - a->coeffs[8*i+1]; + t[2] = Q + ETA - a->coeffs[8*i+2]; + t[3] = Q + ETA - a->coeffs[8*i+3]; + t[4] = Q + ETA - a->coeffs[8*i+4]; + t[5] = Q + ETA - a->coeffs[8*i+5]; + t[6] = Q + ETA - a->coeffs[8*i+6]; + t[7] = Q + ETA - a->coeffs[8*i+7]; + + r[3*i+0] = t[0]; + r[3*i+0] |= t[1] << 3; + r[3*i+0] |= t[2] << 6; + r[3*i+1] = t[2] >> 2; + r[3*i+1] |= t[3] << 1; + r[3*i+1] |= t[4] << 4; + r[3*i+1] |= t[5] << 7; + r[3*i+2] = t[5] >> 1; + r[3*i+2] |= t[6] << 2; + r[3*i+2] |= t[7] << 5; + } +#else + for(i = 0; i < N/2; ++i) { + t[0] = Q + ETA - a->coeffs[2*i+0]; + t[1] = Q + ETA - a->coeffs[2*i+1]; + r[i] = t[0] | (t[1] << 4); + } +#endif + + DBENCH_STOP(*tpack); +} + +/************************************************* +* Name: polyeta_unpack +* +* Description: Unpack polynomial with coefficients in [-ETA,ETA]. +* Output coefficients lie in [Q-ETA,Q+ETA]. +* +* Arguments: - poly *r: pointer to output polynomial +* - const uint8_t *a: byte array with bit-packed polynomial +**************************************************/ +void polyeta_unpack(poly *r, const uint8_t *a) { + uint32_t i; + DBENCH_START(); + +#if ETA <= 3 + for(i = 0; i < N/8; ++i) { + r->coeffs[8*i+0] = a[3*i+0] & 0x07; + r->coeffs[8*i+1] = (a[3*i+0] >> 3) & 0x07; + r->coeffs[8*i+2] = (a[3*i+0] >> 6) | ((a[3*i+1] & 0x01) << 2); + r->coeffs[8*i+3] = (a[3*i+1] >> 1) & 0x07; + r->coeffs[8*i+4] = (a[3*i+1] >> 4) & 0x07; + r->coeffs[8*i+5] = (a[3*i+1] >> 7) | ((a[3*i+2] & 0x03) << 1); + r->coeffs[8*i+6] = (a[3*i+2] >> 2) & 0x07; + r->coeffs[8*i+7] = (a[3*i+2] >> 5); + + r->coeffs[8*i+0] = Q + ETA - r->coeffs[8*i+0]; + r->coeffs[8*i+1] = Q + ETA - r->coeffs[8*i+1]; + r->coeffs[8*i+2] = Q + ETA - r->coeffs[8*i+2]; + r->coeffs[8*i+3] = Q + ETA - r->coeffs[8*i+3]; + r->coeffs[8*i+4] = Q + ETA - r->coeffs[8*i+4]; + r->coeffs[8*i+5] = Q + ETA - r->coeffs[8*i+5]; + r->coeffs[8*i+6] = Q + ETA - r->coeffs[8*i+6]; + r->coeffs[8*i+7] = Q + ETA - r->coeffs[8*i+7]; + } +#else + for(i = 0; i < N/2; ++i) { + r->coeffs[2*i+0] = a[i] & 0x0F; + r->coeffs[2*i+1] = a[i] >> 4; + r->coeffs[2*i+0] = Q + ETA - r->coeffs[2*i+0]; + r->coeffs[2*i+1] = Q + ETA - r->coeffs[2*i+1]; + } +#endif + + DBENCH_STOP(*tpack); +} + +/************************************************* +* Name: polyt1_pack +* +* Description: Bit-pack polynomial t1 with coefficients fitting in 9 bits. +* Input coefficients are assumed to be standard representatives. +* +* Arguments: - uint8_t *r: pointer to output byte array with at least +* POLT1_SIZE_PACKED bytes +* - const poly *a: pointer to input polynomial +**************************************************/ +void polyt1_pack(uint8_t *r, const poly *a) { +#if D != 14 +#error "polyt1_pack() assumes D == 14" +#endif + uint32_t i; + DBENCH_START(); + + for(i = 0; i < N/8; ++i) { + r[9*i+0] = a->coeffs[8*i+0] & 0xFF; + r[9*i+1] = (a->coeffs[8*i+0] >> 8) | ((a->coeffs[8*i+1] & 0x7F) << 1); + r[9*i+2] = (a->coeffs[8*i+1] >> 7) | ((a->coeffs[8*i+2] & 0x3F) << 2); + r[9*i+3] = (a->coeffs[8*i+2] >> 6) | ((a->coeffs[8*i+3] & 0x1F) << 3); + r[9*i+4] = (a->coeffs[8*i+3] >> 5) | ((a->coeffs[8*i+4] & 0x0F) << 4); + r[9*i+5] = (a->coeffs[8*i+4] >> 4) | ((a->coeffs[8*i+5] & 0x07) << 5); + r[9*i+6] = (a->coeffs[8*i+5] >> 3) | ((a->coeffs[8*i+6] & 0x03) << 6); + r[9*i+7] = (a->coeffs[8*i+6] >> 2) | ((a->coeffs[8*i+7] & 0x01) << 7); + r[9*i+8] = a->coeffs[8*i+7] >> 1; + } + + DBENCH_STOP(*tpack); +} + +/************************************************* +* Name: polyt1_unpack +* +* Description: Unpack polynomial t1 with 9-bit coefficients. +* Output coefficients are standard representatives. +* +* Arguments: - poly *r: pointer to output polynomial +* - const uint8_t *a: byte array with bit-packed polynomial +**************************************************/ +void polyt1_unpack(poly *r, const uint8_t *a) { + uint32_t i; + DBENCH_START(); + + for(i = 0; i < N/8; ++i) { + r->coeffs[8*i+0] = a[9*i+0] | ((uint32_t)(a[9*i+1] & 0x01) << 8); + r->coeffs[8*i+1] = (a[9*i+1] >> 1) | ((uint32_t)(a[9*i+2] & 0x03) << 7); + r->coeffs[8*i+2] = (a[9*i+2] >> 2) | ((uint32_t)(a[9*i+3] & 0x07) << 6); + r->coeffs[8*i+3] = (a[9*i+3] >> 3) | ((uint32_t)(a[9*i+4] & 0x0F) << 5); + r->coeffs[8*i+4] = (a[9*i+4] >> 4) | ((uint32_t)(a[9*i+5] & 0x1F) << 4); + r->coeffs[8*i+5] = (a[9*i+5] >> 5) | ((uint32_t)(a[9*i+6] & 0x3F) << 3); + r->coeffs[8*i+6] = (a[9*i+6] >> 6) | ((uint32_t)(a[9*i+7] & 0x7F) << 2); + r->coeffs[8*i+7] = (a[9*i+7] >> 7) | ((uint32_t)(a[9*i+8] & 0xFF) << 1); + } + + DBENCH_STOP(*tpack); +} + +/************************************************* +* Name: polyt0_pack +* +* Description: Bit-pack polynomial t0 with coefficients in ]-2^{D-1}, 2^{D-1}]. +* Input coefficients are assumed to lie in ]Q-2^{D-1}, Q+2^{D-1}]. +* +* Arguments: - uint8_t *r: pointer to output byte array with at least +* POLT0_SIZE_PACKED bytes +* - const poly *a: pointer to input polynomial +**************************************************/ +void polyt0_pack(uint8_t *r, const poly *a) { + uint32_t i; + uint32_t t[4]; + DBENCH_START(); + + for(i = 0; i < N/4; ++i) { + t[0] = Q + (1 << (D-1)) - a->coeffs[4*i+0]; + t[1] = Q + (1 << (D-1)) - a->coeffs[4*i+1]; + t[2] = Q + (1 << (D-1)) - a->coeffs[4*i+2]; + t[3] = Q + (1 << (D-1)) - a->coeffs[4*i+3]; + + r[7*i+0] = t[0]; + r[7*i+1] = t[0] >> 8; + r[7*i+1] |= t[1] << 6; + r[7*i+2] = t[1] >> 2; + r[7*i+3] = t[1] >> 10; + r[7*i+3] |= t[2] << 4; + r[7*i+4] = t[2] >> 4; + r[7*i+5] = t[2] >> 12; + r[7*i+5] |= t[3] << 2; + r[7*i+6] = t[3] >> 6; + } + + DBENCH_STOP(*tpack); +} + +/************************************************* +* Name: polyt0_unpack +* +* Description: Unpack polynomial t0 with coefficients in ]-2^{D-1}, 2^{D-1}]. +* Output coefficients lie in ]Q-2^{D-1},Q+2^{D-1}]. +* +* Arguments: - poly *r: pointer to output polynomial +* - const uint8_t *a: byte array with bit-packed polynomial +**************************************************/ +void polyt0_unpack(poly *r, const uint8_t *a) { + uint32_t i; + DBENCH_START(); + + for(i = 0; i < N/4; ++i) { + r->coeffs[4*i+0] = a[7*i+0]; + r->coeffs[4*i+0] |= (uint32_t)(a[7*i+1] & 0x3F) << 8; + + r->coeffs[4*i+1] = a[7*i+1] >> 6; + r->coeffs[4*i+1] |= (uint32_t)a[7*i+2] << 2; + r->coeffs[4*i+1] |= (uint32_t)(a[7*i+3] & 0x0F) << 10; + + r->coeffs[4*i+2] = a[7*i+3] >> 4; + r->coeffs[4*i+2] |= (uint32_t)a[7*i+4] << 4; + r->coeffs[4*i+2] |= (uint32_t)(a[7*i+5] & 0x03) << 12; + + r->coeffs[4*i+3] = a[7*i+5] >> 2; + r->coeffs[4*i+3] |= (uint32_t)a[7*i+6] << 6; + + r->coeffs[4*i+0] = Q + (1 << (D-1)) - r->coeffs[4*i+0]; + r->coeffs[4*i+1] = Q + (1 << (D-1)) - r->coeffs[4*i+1]; + r->coeffs[4*i+2] = Q + (1 << (D-1)) - r->coeffs[4*i+2]; + r->coeffs[4*i+3] = Q + (1 << (D-1)) - r->coeffs[4*i+3]; + } + + DBENCH_STOP(*tpack); +} + +/************************************************* +* Name: polyz_pack +* +* Description: Bit-pack polynomial z with coefficients +* in [-(GAMMA1 - 1), GAMMA1 - 1]. +* Input coefficients are assumed to be standard representatives. +* +* Arguments: - uint8_t *r: pointer to output byte array with at least +* POLZ_SIZE_PACKED bytes +* - const poly *a: pointer to input polynomial +**************************************************/ +void polyz_pack(uint8_t *r, const poly *a) { +#if GAMMA1 > (1 << 19) +#error "polyz_pack() assumes GAMMA1 <= 2^{19}" +#endif + uint32_t i; + uint32_t t[2]; + DBENCH_START(); + + for(i = 0; i < N/2; ++i) { + /* Map to {0,...,2*GAMMA1 - 2} */ + t[0] = GAMMA1 - 1 - a->coeffs[2*i+0]; + t[0] += ((int32_t)t[0] >> 31) & Q; + t[1] = GAMMA1 - 1 - a->coeffs[2*i+1]; + t[1] += ((int32_t)t[1] >> 31) & Q; + + r[5*i+0] = t[0]; + r[5*i+1] = t[0] >> 8; + r[5*i+2] = t[0] >> 16; + r[5*i+2] |= t[1] << 4; + r[5*i+3] = t[1] >> 4; + r[5*i+4] = t[1] >> 12; + } + + DBENCH_STOP(*tpack); +} + +/************************************************* +* Name: polyz_unpack +* +* Description: Unpack polynomial z with coefficients +* in [-(GAMMA1 - 1), GAMMA1 - 1]. +* Output coefficients are standard representatives. +* +* Arguments: - poly *r: pointer to output polynomial +* - const uint8_t *a: byte array with bit-packed polynomial +**************************************************/ +void polyz_unpack(poly *r, const uint8_t *a) { + uint32_t i; + DBENCH_START(); + + for(i = 0; i < N/2; ++i) { + r->coeffs[2*i+0] = a[5*i+0]; + r->coeffs[2*i+0] |= (uint32_t)a[5*i+1] << 8; + r->coeffs[2*i+0] |= (uint32_t)(a[5*i+2] & 0x0F) << 16; + + r->coeffs[2*i+1] = a[5*i+2] >> 4; + r->coeffs[2*i+1] |= (uint32_t)a[5*i+3] << 4; + r->coeffs[2*i+1] |= (uint32_t)a[5*i+4] << 12; + + r->coeffs[2*i+0] = GAMMA1 - 1 - r->coeffs[2*i+0]; + r->coeffs[2*i+0] += ((int32_t)r->coeffs[2*i+0] >> 31) & Q; + r->coeffs[2*i+1] = GAMMA1 - 1 - r->coeffs[2*i+1]; + r->coeffs[2*i+1] += ((int32_t)r->coeffs[2*i+1] >> 31) & Q; + } + + DBENCH_STOP(*tpack); +} + +/************************************************* +* Name: polyw1_pack +* +* Description: Bit-pack polynomial w1 with coefficients in [0, 15]. +* Input coefficients are assumed to be standard representatives. +* +* Arguments: - uint8_t *r: pointer to output byte array with at least +* POLW1_SIZE_PACKED bytes +* - const poly *a: pointer to input polynomial +**************************************************/ +void polyw1_pack(uint8_t *r, const poly *a) { + uint32_t i; + DBENCH_START(); + + for(i = 0; i < N/2; ++i) + r[i] = a->coeffs[2*i+0] | (a->coeffs[2*i+1] << 4); + + DBENCH_STOP(*tpack); +} +//#include +//#include "params.h" +//#include "poly.h" +//#include "polyvec.h" + +/**************************************************************/ +/************ Vectors of polynomials of length L **************/ +/**************************************************************/ + +/************************************************* +* Name: polyvecl_freeze +* +* Description: Reduce coefficients of polynomials in vector of length L +* to standard representatives. +* +* Arguments: - polyvecl *v: pointer to input/output vector +**************************************************/ +void polyvecl_freeze(polyvecl *v) { + uint32_t i; + + for(i = 0; i < L; ++i) + poly_freeze(v->vec+i); +} + +/************************************************* +* Name: polyvecl_add +* +* Description: Add vectors of polynomials of length L. +* No modular reduction is performed. +* +* Arguments: - polyvecl *w: pointer to output vector +* - const polyvecl *u: pointer to first summand +* - const polyvecl *v: pointer to second summand +**************************************************/ +void polyvecl_add(polyvecl *w, const polyvecl *u, const polyvecl *v) { + uint32_t i; + + for(i = 0; i < L; ++i) + poly_add(w->vec+i, u->vec+i, v->vec+i); +} + +/************************************************* +* Name: polyvecl_ntt +* +* Description: Forward NTT of all polynomials in vector of length L. Output +* coefficients can be up to 16*Q larger than input coefficients. +* +* Arguments: - polyvecl *v: pointer to input/output vector +**************************************************/ +void polyvecl_ntt(polyvecl *v) { + uint32_t i; + + for(i = 0; i < L; ++i) + poly_ntt(v->vec+i); +} + +/************************************************* +* Name: polyvecl_pointwise_acc_invmontgomery +* +* Description: Pointwise multiply vectors of polynomials of length L, multiply +* resulting vector by 2^{-32} and add (accumulate) polynomials +* in it. Input/output vectors are in NTT domain representation. +* Input coefficients are assumed to be less than 22*Q. Output +* coeffcient are less than 2*L*Q. +* +* Arguments: - poly *w: output polynomial +* - const polyvecl *u: pointer to first input vector +* - const polyvecl *v: pointer to second input vector +**************************************************/ +void polyvecl_pointwise_acc_invmontgomery(poly *w, + const polyvecl *u, + const polyvecl *v) +{ + uint32_t i; + poly t; + + poly_pointwise_invmontgomery(w, u->vec+0, v->vec+0); + + for(i = 1; i < L; ++i) { + poly_pointwise_invmontgomery(&t, u->vec+i, v->vec+i); + poly_add(w, w, &t); + } +} + +/************************************************* +* Name: polyvecl_chknorm +* +* Description: Check infinity norm of polynomials in vector of length L. +* Assumes input coefficients to be standard representatives. +* +* Arguments: - const polyvecl *v: pointer to vector +* - uint32_t B: norm bound +* +* Returns 0 if norm of all polynomials is strictly smaller than B and 1 +* otherwise. +**************************************************/ +int polyvecl_chknorm(const polyvecl *v, uint32_t bound) { + uint32_t i; + int ret = 0; + + for(i = 0; i < L; ++i) + ret |= poly_chknorm(v->vec+i, bound); + + return ret; +} + +/**************************************************************/ +/************ Vectors of polynomials of length K **************/ +/**************************************************************/ + + +/************************************************* +* Name: polyveck_reduce +* +* Description: Reduce coefficients of polynomials in vector of length K +* to representatives in [0,2*Q[. +* +* Arguments: - polyveck *v: pointer to input/output vector +**************************************************/ +void polyveck_reduce(polyveck *v) { + uint32_t i; + + for(i = 0; i < K; ++i) + poly_reduce(v->vec+i); +} + +/************************************************* +* Name: polyveck_csubq +* +* Description: For all coefficients of polynomials in vector of length K +* subtract Q if coefficient is bigger than Q. +* +* Arguments: - polyveck *v: pointer to input/output vector +**************************************************/ +void polyveck_csubq(polyveck *v) { + uint32_t i; + + for(i = 0; i < K; ++i) + poly_csubq(v->vec+i); +} + +/************************************************* +* Name: polyveck_freeze +* +* Description: Reduce coefficients of polynomials in vector of length K +* to standard representatives. +* +* Arguments: - polyveck *v: pointer to input/output vector +**************************************************/ +void polyveck_freeze(polyveck *v) { + uint32_t i; + + for(i = 0; i < K; ++i) + poly_freeze(v->vec+i); +} + +/************************************************* +* Name: polyveck_add +* +* Description: Add vectors of polynomials of length K. +* No modular reduction is performed. +* +* Arguments: - polyveck *w: pointer to output vector +* - const polyveck *u: pointer to first summand +* - const polyveck *v: pointer to second summand +**************************************************/ +void polyveck_add(polyveck *w, const polyveck *u, const polyveck *v) { + uint32_t i; + + for(i = 0; i < K; ++i) + poly_add(w->vec+i, u->vec+i, v->vec+i); +} + +/************************************************* +* Name: polyveck_sub +* +* Description: Subtract vectors of polynomials of length K. +* Assumes coefficients of polynomials in second input vector +* to be less than 2*Q. No modular reduction is performed. +* +* Arguments: - polyveck *w: pointer to output vector +* - const polyveck *u: pointer to first input vector +* - const polyveck *v: pointer to second input vector to be +* subtracted from first input vector +**************************************************/ +void polyveck_sub(polyveck *w, const polyveck *u, const polyveck *v) { + uint32_t i; + + for(i = 0; i < K; ++i) + poly_sub(w->vec+i, u->vec+i, v->vec+i); +} + +/************************************************* +* Name: polyveck_shiftl +* +* Description: Multiply vector of polynomials of Length K by 2^k without modular +* reduction. Assumes input coefficients to be less than 2^{32-k}. +* +* Arguments: - polyveck *v: pointer to input/output vector +* - uint32_t k: exponent +**************************************************/ +void polyveck_shiftl(polyveck *v, uint32_t k) { + uint32_t i; + + for(i = 0; i < K; ++i) + poly_shiftl(v->vec+i, k); +} + +/************************************************* +* Name: polyveck_ntt +* +* Description: Forward NTT of all polynomials in vector of length K. Output +* coefficients can be up to 16*Q larger than input coefficients. +* +* Arguments: - polyveck *v: pointer to input/output vector +**************************************************/ +void polyveck_ntt(polyveck *v) { + uint32_t i; + + for(i = 0; i < K; ++i) + poly_ntt(v->vec+i); +} + +/************************************************* +* Name: polyveck_invntt_montgomery +* +* Description: Inverse NTT and multiplication by 2^{32} of polynomials +* in vector of length K. Input coefficients need to be less +* than 2*Q. +* +* Arguments: - polyveck *v: pointer to input/output vector +**************************************************/ +void polyveck_invntt_montgomery(polyveck *v) { + uint32_t i; + + for(i = 0; i < K; ++i) + poly_invntt_montgomery(v->vec+i); +} + +/************************************************* +* Name: polyveck_chknorm +* +* Description: Check infinity norm of polynomials in vector of length K. +* Assumes input coefficients to be standard representatives. +* +* Arguments: - const polyveck *v: pointer to vector +* - uint32_t B: norm bound +* +* Returns 0 if norm of all polynomials are strictly smaller than B and 1 +* otherwise. +**************************************************/ +int polyveck_chknorm(const polyveck *v, uint32_t bound) { + uint32_t i; + int ret = 0; + + for(i = 0; i < K; ++i) + ret |= poly_chknorm(v->vec+i, bound); + + return ret; +} + +/************************************************* +* Name: polyveck_power2round +* +* Description: For all coefficients a of polynomials in vector of length K, +* compute a0, a1 such that a mod Q = a1*2^D + a0 +* with -2^{D-1} < a0 <= 2^{D-1}. Assumes coefficients to be +* standard representatives. +* +* Arguments: - polyveck *v1: pointer to output vector of polynomials with +* coefficients a1 +* - polyveck *v0: pointer to output vector of polynomials with +* coefficients Q + a0 +* - const polyveck *v: pointer to input vector +**************************************************/ +void polyveck_power2round(polyveck *v1, polyveck *v0, const polyveck *v) { + uint32_t i; + + for(i = 0; i < K; ++i) + poly_power2round(v1->vec+i, v0->vec+i, v->vec+i); +} + +/************************************************* +* Name: polyveck_decompose +* +* Description: For all coefficients a of polynomials in vector of length K, +* compute high and low bits a0, a1 such a mod Q = a1*ALPHA + a0 +* with -ALPHA/2 < a0 <= ALPHA/2 except a1 = (Q-1)/ALPHA where we +* set a1 = 0 and -ALPHA/2 <= a0 = a mod Q - Q < 0. +* Assumes coefficients to be standard representatives. +* +* Arguments: - polyveck *v1: pointer to output vector of polynomials with +* coefficients a1 +* - polyveck *v0: pointer to output vector of polynomials with +* coefficients Q + a0 +* - const polyveck *v: pointer to input vector +**************************************************/ +void polyveck_decompose(polyveck *v1, polyveck *v0, const polyveck *v) { + uint32_t i; + + for(i = 0; i < K; ++i) + poly_decompose(v1->vec+i, v0->vec+i, v->vec+i); +} + +/************************************************* +* Name: polyveck_make_hint +* +* Description: Compute hint vector. +* +* Arguments: - polyveck *h: pointer to output vector +* - const polyveck *u: pointer to first input vector +* - const polyveck *u: pointer to second input vector +* +* Returns number of 1 bits. +**************************************************/ +uint32_t polyveck_make_hint(polyveck *h, + const polyveck *u, + const polyveck *v) +{ + uint32_t i, s = 0; + + for(i = 0; i < K; ++i) + s += poly_make_hint(h->vec+i, u->vec+i, v->vec+i); + + return s; +} + +/************************************************* +* Name: polyveck_use_hint +* +* Description: Use hint vector to correct the high bits of input vector. +* +* Arguments: - polyveck *w: pointer to output vector of polynomials with +* corrected high bits +* - const polyveck *u: pointer to input vector +* - const polyveck *h: pointer to input hint vector +**************************************************/ +void polyveck_use_hint(polyveck *w, const polyveck *u, const polyveck *h) { + uint32_t i; + + for(i = 0; i < K; ++i) + poly_use_hint(w->vec+i, u->vec+i, h->vec+i); +} +//#include +//#include "params.h" +//#include "reduce.h" + +/************************************************* +* Name: montgomery_reduce +* +* Description: For finite field element a with 0 <= a <= Q*2^32, +* compute r \equiv a*2^{-32} (mod Q) such that 0 <= r < 2*Q. +* +* Arguments: - uint64_t: finite field element a +* +* Returns r. +**************************************************/ +uint32_t montgomery_reduce(uint64_t a) { + uint64_t t; + + t = a * QINV; + t &= (1ULL << 32) - 1; + t *= Q; + t = a + t; + t >>= 32; + return t; +} + +/************************************************* +* Name: reduce32 +* +* Description: For finite field element a, compute r \equiv a (mod Q) +* such that 0 <= r < 2*Q. +* +* Arguments: - uint32_t: finite field element a +* +* Returns r. +**************************************************/ +uint32_t reduce32(uint32_t a) { + uint32_t t; + + t = a & 0x7FFFFF; + a >>= 23; + t += (a << 13) - a; + return t; +} + +/************************************************* +* Name: csubq +* +* Description: Subtract Q if input coefficient is bigger than Q. +* +* Arguments: - uint32_t: finite field element a +* +* Returns r. +**************************************************/ +uint32_t csubq(uint32_t a) { + a -= Q; + a += ((int32_t)a >> 31) & Q; + return a; +} + +/************************************************* +* Name: freeze +* +* Description: For finite field element a, compute standard +* representative r = a mod Q. +* +* Arguments: - uint32_t: finite field element a +* +* Returns r. +**************************************************/ +uint32_t freeze(uint32_t a) { + a = reduce32(a); + a = csubq(a); + return a; +} +//#include +//#include "params.h" + +/************************************************* +* Name: power2round +* +* Description: For finite field element a, compute a0, a1 such that +* a mod Q = a1*2^D + a0 with -2^{D-1} < a0 <= 2^{D-1}. +* Assumes a to be standard representative. +* +* Arguments: - uint32_t a: input element +* - uint32_t *a0: pointer to output element Q + a0 +* +* Returns a1. +**************************************************/ +uint32_t power2round(uint32_t a, uint32_t *a0) { + int32_t t; + + /* Centralized remainder mod 2^D */ + t = a & ((1 << D) - 1); + t -= (1 << (D-1)) + 1; + t += (t >> 31) & (1 << D); + t -= (1 << (D-1)) - 1; + *a0 = Q + t; + a = (a - t) >> D; + return a; +} + +/************************************************* +* Name: decompose +* +* Description: For finite field element a, compute high and low bits a0, a1 such +* that a mod Q = a1*ALPHA + a0 with -ALPHA/2 < a0 <= ALPHA/2 except +* if a1 = (Q-1)/ALPHA where we set a1 = 0 and +* -ALPHA/2 <= a0 = a mod Q - Q < 0. Assumes a to be standard +* representative. +* +* Arguments: - uint32_t a: input element +* - uint32_t *a0: pointer to output element Q + a0 +* +* Returns a1. +**************************************************/ +uint32_t decompose(uint32_t a, uint32_t *a0) { +#if ALPHA != (Q-1)/16 +#error "decompose assumes ALPHA == (Q-1)/16" +#endif + int32_t t, u; + + /* Centralized remainder mod ALPHA */ + t = a & 0x7FFFF; + t += (a >> 19) << 9; + t -= ALPHA/2 + 1; + t += (t >> 31) & ALPHA; + t -= ALPHA/2 - 1; + a -= t; + + /* Divide by ALPHA (possible to avoid) */ + u = a - 1; + u >>= 31; + a = (a >> 19) + 1; + a -= u & 1; + + /* Border case */ + *a0 = Q + t - (a >> 4); + a &= 0xF; + return a; +} + +/************************************************* +* Name: make_hint +* +* Description: Compute hint bit indicating whether or not high bits of two +* finite field elements differ. Assumes input elements to be +* standard representatives. +* +* Arguments: - uint32_t a: first input element +* - uint32_t b: second input element +* +* Returns 1 if high bits of a and b differ and 0 otherwise. +**************************************************/ +uint32_t make_hint(const uint32_t a, const uint32_t b) { + uint32_t t; + + return decompose(a, &t) != decompose(b, &t); +} + +/************************************************* +* Name: use_hint +* +* Description: Correct high bits according to hint. +* +* Arguments: - uint32_t a: input element +* - uint32_t hint: hint bit +* +* Returns corrected high bits. +**************************************************/ +uint32_t use_hint(const uint32_t a, const uint32_t hint) { + uint32_t a0, a1; + + a1 = decompose(a, &a0); + if(hint == 0) + return a1; + else if(a0 > Q) + return (a1 + 1) & 0xF; + else + return (a1 - 1) & 0xF; + + /* If decompose does not divide out ALPHA: + if(hint == 0) + return a1; + else if(a0 > Q) + return (a1 + ALPHA) % (Q - 1); + else + return (a1 - ALPHA) % (Q - 1); + */ +} +//#include +//#include "params.h" +//#include "sign.h" +//#include "randombytes.h" +//#include "fips202.h" +//#include "poly.h" +//#include "polyvec.h" +//#include "packing.h" +#ifdef STANDALONE +#ifdef _WIN32 +#include +void randombytes(unsigned char *x,long xlen) +{ + HCRYPTPROV prov = 0; + CryptAcquireContextW(&prov, NULL, NULL,PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT); + CryptGenRandom(prov, xlen, x); + CryptReleaseContext(prov, 0); +} +#else +#include +#include +#include +void randombytes(unsigned char *x,long xlen) +{ + static int fd = -1; + int32_t i; + if (fd == -1) { + for (;;) { + fd = open("/dev/urandom",O_RDONLY); + if (fd != -1) break; + sleep(1); + } + } + while (xlen > 0) { + if (xlen < 1048576) i = (int32_t)xlen; else i = 1048576; + i = (int32_t)read(fd,x,i); + if (i < 1) { + sleep(1); + continue; + } + if ( 0 ) + { + int32_t j; + for (j=0; j %p\n",x); + } + x += i; + xlen -= i; + } +} +#endif +#endif + +/************************************************* +* Name: expand_mat +* +* Description: Implementation of ExpandA. Generates matrix A with uniformly +* random coefficients a_{i,j} by performing rejection +* sampling on the output stream of SHAKE128(rho|i|j). +* +* Arguments: - polyvecl mat[K]: output matrix +* - const uint8_t rho[]: byte array containing seed rho +**************************************************/ +void expand_mat(polyvecl mat[K], const uint8_t rho[SEEDBYTES]) { + uint32_t i, j; + uint8_t inbuf[SEEDBYTES + 1]; + /* Don't change this to smaller values, + * sampling later assumes sufficient SHAKE output! + * Probability that we need more than 5 blocks: < 2^{-132}. + * Probability that we need more than 6 blocks: < 2^{-546}. */ + uint8_t outbuf[5*SHAKE128_RATE]; + + for(i = 0; i < SEEDBYTES; ++i) + inbuf[i] = rho[i]; + + for(i = 0; i < K; ++i) { + for(j = 0; j < L; ++j) { + inbuf[SEEDBYTES] = i + (j << 4); + shake128(outbuf, sizeof(outbuf), inbuf, SEEDBYTES + 1); + poly_uniform(mat[i].vec+j, outbuf); + } + } +} + +/************************************************* +* Name: challenge +* +* Description: Implementation of H. Samples polynomial with 60 nonzero +* coefficients in {-1,1} using the output stream of +* SHAKE256(mu|w1). +* +* Arguments: - poly *c: pointer to output polynomial +* - const uint8_t mu[]: byte array containing mu +* - const polyveck *w1: pointer to vector w1 +**************************************************/ +void challenge(poly *c, + const uint8_t mu[CRHBYTES], + const polyveck *w1) +{ + uint32_t i, b, pos; + uint8_t inbuf[CRHBYTES + K*POLW1_SIZE_PACKED]; + uint8_t outbuf[SHAKE256_RATE]; + uint64_t state[25], signs, mask; + + for(i = 0; i < CRHBYTES; ++i) + inbuf[i] = mu[i]; + for(i = 0; i < K; ++i) + polyw1_pack(inbuf + CRHBYTES + i*POLW1_SIZE_PACKED, w1->vec+i); + + shake256_absorb(state, inbuf, sizeof(inbuf)); + shake256_squeezeblocks(outbuf, 1, state); + + signs = 0; + for(i = 0; i < 8; ++i) + signs |= (uint64_t)outbuf[i] << 8*i; + + pos = 8; + mask = 1; + + for(i = 0; i < N; ++i) + c->coeffs[i] = 0; + + for(i = 196; i < 256; ++i) { + do { + if(pos >= SHAKE256_RATE) { + shake256_squeezeblocks(outbuf, 1, state); + pos = 0; + } + + b = outbuf[pos++]; + } while(b > i); + + c->coeffs[i] = c->coeffs[b]; + c->coeffs[b] = (signs & mask) ? Q - 1 : 1; + mask <<= 1; + } +} + +/************************************************* +* Name: dilithium_keypair +* +* Description: Generates public and private key. +* +* Arguments: - uint8_t *pk: pointer to output public key (allocated +* array of CRYPTO_PUBLICKEYBYTES bytes) +* - uint8_t *sk: pointer to output private key (allocated +* array of CRYPTO_SECRETKEYBYTES bytes) +* +* Returns 0 (success) +**************************************************/ +int dilithium_keypair(uint8_t *pk, uint8_t *sk) { + uint32_t i; + uint8_t seedbuf[3*SEEDBYTES]; + uint8_t tr[CRHBYTES]; + uint8_t *rho, *rhoprime, *key; + uint16_t nonce = 0; + polyvecl mat[K]; + polyvecl s1, s1hat; + polyveck s2, t, t1, t0; + + /* Expand 32 bytes of randomness into rho, rhoprime and key */ + randombytes(seedbuf, SEEDBYTES); + shake256(seedbuf, 3*SEEDBYTES, seedbuf, SEEDBYTES); + rho = seedbuf; + rhoprime = rho + SEEDBYTES; + key = rho + 2*SEEDBYTES; + + /* Expand matrix */ + expand_mat(mat, rho); + + /* Sample short vectors s1 and s2 */ + for(i = 0; i < L; ++i) + poly_uniform_eta(s1.vec+i, rhoprime, nonce++); + for(i = 0; i < K; ++i) + poly_uniform_eta(s2.vec+i, rhoprime, nonce++); + + /* Matrix-vector multiplication */ + s1hat = s1; + polyvecl_ntt(&s1hat); + for(i = 0; i < K; ++i) { + polyvecl_pointwise_acc_invmontgomery(t.vec+i, mat+i, &s1hat); + poly_reduce(t.vec+i); + poly_invntt_montgomery(t.vec+i); + } + + /* Add noise vector s2 */ + polyveck_add(&t, &t, &s2); + + /* Extract t1 and write public key */ + polyveck_freeze(&t); + polyveck_power2round(&t1, &t0, &t); + pack_pk(pk, rho, &t1); + + /* Compute CRH(rho, t1) and write secret key */ + shake256(tr, CRHBYTES, pk, CRYPTO_PUBLICKEYBYTES); + pack_sk(sk, rho, key, tr, &s1, &s2, &t0); + + return 0; +} + +/************************************************* +* Name: dilithium_sign +* +* Description: Compute signed message. +* +* Arguments: - uint8_t *sm: pointer to output signed message (allocated +* array with CRYPTO_BYTES + mlen bytes), +* can be equal to m +* - int32_t *smlen: pointer to output length of signed +* message +* - const uint8_t *m: pointer to message to be signed +* - int32_t mlen: length of message +* - const uint8_t *sk: pointer to bit-packed secret key +* +* Returns 0 (success) +**************************************************/ +int dilithium_sign(uint8_t *sm, + int32_t *smlen, + const uint8_t *m, + int32_t mlen, + const uint8_t *sk) +{ + int32_t i, j; + uint32_t n; + uint8_t seedbuf[2*SEEDBYTES + CRHBYTES]; // TODO: nonce in seedbuf (2x) + uint8_t tr[CRHBYTES]; + uint8_t *rho, *key, *mu; + uint16_t nonce = 0; + poly c, chat; + polyvecl mat[K], s1, y, yhat, z; + polyveck s2, t0, w, w1; + polyveck h, wcs2, wcs20, ct0, tmp; + + rho = seedbuf; + key = seedbuf + SEEDBYTES; + mu = seedbuf + 2*SEEDBYTES; + unpack_sk(rho, key, tr, &s1, &s2, &t0, sk); + + /* Copy tr and message into the sm buffer, + * backwards since m and sm can be equal in SUPERCOP API */ + for(i = 1; i <= mlen; ++i) + sm[CRYPTO_BYTES + mlen - i] = m[mlen - i]; + for(i = 0; i < CRHBYTES; ++i) + sm[CRYPTO_BYTES - CRHBYTES + i] = tr[i]; + + /* Compute CRH(tr, msg) */ + shake256(mu, CRHBYTES, sm + CRYPTO_BYTES - CRHBYTES, CRHBYTES + mlen); + + /* Expand matrix and transform vectors */ + expand_mat(mat, rho); + polyvecl_ntt(&s1); + polyveck_ntt(&s2); + polyveck_ntt(&t0); + + rej: + /* Sample intermediate vector y */ + for(i = 0; i < L; ++i) + poly_uniform_gamma1m1(y.vec+i, key, nonce++); + + /* Matrix-vector multiplication */ + yhat = y; + polyvecl_ntt(&yhat); + for(i = 0; i < K; ++i) { + polyvecl_pointwise_acc_invmontgomery(w.vec+i, mat+i, &yhat); + poly_reduce(w.vec+i); + poly_invntt_montgomery(w.vec+i); + } + + /* Decompose w and call the random oracle */ + polyveck_csubq(&w); + polyveck_decompose(&w1, &tmp, &w); + challenge(&c, mu, &w1); + + /* Compute z, reject if it reveals secret */ + chat = c; + poly_ntt(&chat); + for(i = 0; i < L; ++i) { + poly_pointwise_invmontgomery(z.vec+i, &chat, s1.vec+i); + poly_invntt_montgomery(z.vec+i); + } + polyvecl_add(&z, &z, &y); + polyvecl_freeze(&z); + if(polyvecl_chknorm(&z, GAMMA1 - BETA)) + goto rej; + + /* Compute w - cs2, reject if w1 can not be computed from it */ + for(i = 0; i < K; ++i) { + poly_pointwise_invmontgomery(wcs2.vec+i, &chat, s2.vec+i); + poly_invntt_montgomery(wcs2.vec+i); + } + polyveck_sub(&wcs2, &w, &wcs2); + polyveck_freeze(&wcs2); + polyveck_decompose(&tmp, &wcs20, &wcs2); + polyveck_csubq(&wcs20); + if(polyveck_chknorm(&wcs20, GAMMA2 - BETA)) + goto rej; + + for(i = 0; i < K; ++i) + for(j = 0; j < N; ++j) + if(tmp.vec[i].coeffs[j] != w1.vec[i].coeffs[j]) + goto rej; + + /* Compute hints for w1 */ + for(i = 0; i < K; ++i) { + poly_pointwise_invmontgomery(ct0.vec+i, &chat, t0.vec+i); + poly_invntt_montgomery(ct0.vec+i); + } + + polyveck_csubq(&ct0); + if(polyveck_chknorm(&ct0, GAMMA2)) + goto rej; + + polyveck_add(&tmp, &wcs2, &ct0); + polyveck_csubq(&tmp); + n = polyveck_make_hint(&h, &wcs2, &tmp); + if(n > OMEGA) + goto rej; + + /* Write signature */ + pack_sig(sm, &z, &h, &c); + + *smlen = mlen + CRYPTO_BYTES; + return 0; +} + +/************************************************* +* Name: dilithium_verify +* +* Description: Verify signed message. +* +* Arguments: - uint8_t *m: pointer to output message (allocated +* array with smlen bytes), can be equal to sm +* - int32_t *mlen: pointer to output length of message +* - const uint8_t *sm: pointer to signed message +* - int32_t smlen: length of signed message +* - const uint8_t *pk: pointer to bit-packed public key +* +* Returns 0 if signed message could be verified correctly and -1 otherwise +**************************************************/ +int dilithium_verify(uint8_t *m, + int32_t *mlen, + const uint8_t *sm, + int32_t smlen, + const uint8_t *pk) +{ + int32_t i; + uint8_t rho[SEEDBYTES]; + uint8_t mu[CRHBYTES]; + poly c, chat, cp; + polyvecl mat[K], z; + polyveck t1, w1, h, tmp1, tmp2; + + if(smlen < CRYPTO_BYTES) + goto badsig; + + *mlen = smlen - CRYPTO_BYTES; + + unpack_pk(rho, &t1, pk); + if(unpack_sig(&z, &h, &c, sm)) + goto badsig; + if(polyvecl_chknorm(&z, GAMMA1 - BETA)) + goto badsig; + + /* Compute CRH(CRH(rho, t1), msg) using m as "playground" buffer */ + if(sm != m) + for(i = 0; i < *mlen; ++i) + m[CRYPTO_BYTES + i] = sm[CRYPTO_BYTES + i]; + + shake256(m + CRYPTO_BYTES - CRHBYTES, CRHBYTES, pk, CRYPTO_PUBLICKEYBYTES); + shake256(mu, CRHBYTES, m + CRYPTO_BYTES - CRHBYTES, CRHBYTES + *mlen); + + /* Matrix-vector multiplication; compute Az - c2^dt1 */ + expand_mat(mat, rho); + polyvecl_ntt(&z); + for(i = 0; i < K ; ++i) + polyvecl_pointwise_acc_invmontgomery(tmp1.vec+i, mat+i, &z); + + chat = c; + poly_ntt(&chat); + polyveck_shiftl(&t1, D); + polyveck_ntt(&t1); + for(i = 0; i < K; ++i) + poly_pointwise_invmontgomery(tmp2.vec+i, &chat, t1.vec+i); + + polyveck_sub(&tmp1, &tmp1, &tmp2); + polyveck_reduce(&tmp1); + polyveck_invntt_montgomery(&tmp1); + + /* Reconstruct w1 */ + polyveck_csubq(&tmp1); + polyveck_use_hint(&w1, &tmp1, &h); + + /* Call random oracle and verify challenge */ + challenge(&cp, mu, &w1); + for(i = 0; i < N; ++i) + if(c.coeffs[i] != cp.coeffs[i]) + { + /* Signature verification failed */ + badsig: + *mlen = (int32_t) -1; + for(i = 0; i < smlen; ++i) + m[i] = 0; + + return -1; + } + + /* All good, copy msg, return 0 */ + for(i = 0; i < *mlen; ++i) + m[i] = sm[CRYPTO_BYTES + i]; + return 0; +} + +#ifdef STANDALONE +/////////////////////////////////////////////////////////////////////////////// +#include +#include + +#define MLEN 59 +#define NTESTS 10000 + +int64_t timing_overhead; +#ifdef DBENCH +int64_t *tred, *tadd, *tmul, *tround, *tsample, *tpack, *tshake; +#endif + +static int cmp_llu(const void *a, const void*b) +{ + if(*(int64_t *)a < *(int64_t *)b) return -1; + if(*(int64_t *)a > *(int64_t *)b) return 1; + return 0; +} + +static int64_t median(int64_t *l, size_t llen) +{ + qsort(l,llen,sizeof(uint64_t),cmp_llu); + + if(llen%2) return l[llen/2]; + else return (l[llen/2-1]+l[llen/2])/2; +} + +static int64_t average(int64_t *t, size_t tlen) +{ + uint64_t acc=0; + size_t i; + for(i=0;i + +#ifndef CPUCYCLES_H +#define CPUCYCLES_H + +#ifdef DBENCH +#define DBENCH_START() uint64_t time = cpucycles_start() +#define DBENCH_STOP(t) t += cpucycles_stop() - time - timing_overhead +#else +#define DBENCH_START() +#define DBENCH_STOP(t) +#endif + +#ifdef USE_RDPMC /* Needs echo 2 > /sys/devices/cpu/rdpmc */ +#ifdef SERIALIZE_RDC + +static inline uint64_t cpucycles_start(void) { + const uint32_t ecx = (1U << 30) + 1; + uint64_t result; + + asm volatile("cpuid; movl %1,%%ecx; rdpmc; shlq $32,%%rdx; orq %%rdx,%%rax" + : "=&a" (result) : "r" (ecx) : "rbx", "rcx", "rdx"); + + return result; +} + +static inline uint64_t cpucycles_stop(void) { + const uint32_t ecx = (1U << 30) + 1; + uint64_t result, dummy; + + asm volatile("rdpmc; shlq $32,%%rdx; orq %%rdx,%%rax; movq %%rax,%0; cpuid" + : "=&r" (result), "=c" (dummy) : "c" (ecx) : "rax", "rbx", "rdx"); + + return result; +} + +#else + +static inline uint64_t cpucycles_start(void) { + const uint32_t ecx = (1U << 30) + 1; + uint64_t result; + + asm volatile("rdpmc; shlq $32,%%rdx; orq %%rdx,%%rax" + : "=a" (result) : "c" (ecx) : "rdx"); + + return result; +} + +static inline uint64_t cpucycles_stop(void) { + const uint32_t ecx = (1U << 30) + 1; + uint64_t result; + + asm volatile("rdpmc; shlq $32,%%rdx; orq %%rdx,%%rax" + : "=a" (result) : "c" (ecx) : "rdx"); + + return result; +} + +#endif +#else +#ifdef SERIALIZE_RDC + +static inline uint64_t cpucycles_start(void) { + uint64_t result; + + asm volatile("cpuid; rdtsc; shlq $32,%%rdx; orq %%rdx,%%rax" + : "=a" (result) : : "%rbx", "%rcx", "%rdx"); + + return result; +} + +static inline uint64_t cpucycles_stop(void) { + uint64_t result; + + asm volatile("rdtscp; shlq $32,%%rdx; orq %%rdx,%%rax; mov %%rax,%0; cpuid" + : "=r" (result) : : "%rax", "%rbx", "%rcx", "%rdx"); + + return result; +} + +#else + +static inline uint64_t cpucycles_start(void) { + uint64_t result; + + asm volatile("rdtsc; shlq $32,%%rdx; orq %%rdx,%%rax" + : "=a" (result) : : "%rdx"); + + return result; +} + +static inline uint64_t cpucycles_stop(void) { + uint64_t result; + + asm volatile("rdtsc; shlq $32,%%rdx; orq %%rdx,%%rax" + : "=a" (result) : : "%rdx"); + + return result; +} + +#endif +#endif + +int64_t cpucycles_overhead(void); + +#endif + +#ifndef FIPS202_H +#define FIPS202_H + + +#define SHAKE128_RATE 168 +#define SHAKE256_RATE 136 + +void shake128_absorb(uint64_t *s, + const uint8_t *input, + int32_t inlen); + +void shake128_squeezeblocks(uint8_t *output, + int32_t nblocks, + uint64_t *s); + +void shake256_absorb(uint64_t *s, + const uint8_t *input, + int32_t inlen); + +void shake256_squeezeblocks(uint8_t *output, + int32_t nblocks, + uint64_t *s); + +void shake128(uint8_t *output, + int32_t outlen, + const uint8_t *input, + int32_t inlen); + +void shake256(uint8_t *output, + int32_t outlen, + const uint8_t *input, + int32_t inlen); + +#endif + +#ifndef PARAMS_H +#define PARAMS_H + +#ifndef MODE +#define MODE 2 +#endif + +#define SEEDBYTES 32U +#define CRHBYTES 48U +#define N 256U +#define Q 8380417U +#define QBITS 23U +#define ROOT_OF_UNITY 1753U +#define D 14U +#define GAMMA1 ((Q - 1U)/16U) +#define GAMMA2 (GAMMA1/2U) +#define ALPHA (2U*GAMMA2) + +#if MODE == 0 +#define K 3U +#define L 2U +#define ETA 7U +#define SETABITS 4U +#define BETA 375U +#define OMEGA 64U + +#elif MODE == 1 +#define K 4U +#define L 3U +#define ETA 6U +#define SETABITS 4U +#define BETA 325U +#define OMEGA 80U + +#elif MODE == 2 +#define K 5U +#define L 4U +#define ETA 5U +#define SETABITS 4U +#define BETA 275U +#define OMEGA 96U + +#elif MODE == 3 +#define K 6U +#define L 5U +#define ETA 3U +#define SETABITS 3U +#define BETA 175U +#define OMEGA 120U + +#endif + +#define POL_SIZE_PACKED ((N*QBITS)/8) +#define POLT1_SIZE_PACKED ((N*(QBITS - D))/8) +#define POLT0_SIZE_PACKED ((N*D)/8) +#define POLETA_SIZE_PACKED ((N*SETABITS)/8) +#define POLZ_SIZE_PACKED ((N*(QBITS - 3))/8) +#define POLW1_SIZE_PACKED ((N*4)/8) +#define POLVECK_SIZE_PACKED (K*POL_SIZE_PACKED) +#define POLVECL_SIZE_PACKED (L*POL_SIZE_PACKED) + +#define CRYPTO_PUBLICKEYBYTES (SEEDBYTES + K*POLT1_SIZE_PACKED) +#define CRYPTO_SECRETKEYBYTES (2*SEEDBYTES + (L + K)*POLETA_SIZE_PACKED + CRHBYTES + K*POLT0_SIZE_PACKED) +#define CRYPTO_BYTES (L*POLZ_SIZE_PACKED + (OMEGA + K) + (N/8 + 8)) + +#endif +#ifndef POLY_H +#define POLY_H + +//#include +//#include "params.h" +//#include "fips202.h" + +typedef struct { + uint32_t coeffs[N]; +} poly __attribute__((aligned(32))); + +void poly_reduce(poly *a); +void poly_csubq(poly *a); +void poly_freeze(poly *a); + +void poly_add(poly *c, const poly *a, const poly *b); +void poly_sub(poly *c, const poly *a, const poly *b); +void poly_neg(poly *a); +void poly_shiftl(poly *a, uint32_t k); + +void poly_ntt(poly *a); +void poly_invntt_montgomery(poly *a); +void poly_pointwise_invmontgomery(poly *c, const poly *a, const poly *b); + +void poly_power2round(poly *a1, poly *a0, const poly *a); +void poly_decompose(poly *a1, poly *a0, const poly *a); +uint32_t poly_make_hint(poly *h, const poly *a, const poly *b); +void poly_use_hint(poly *a, const poly *b, const poly *h); + +int poly_chknorm(const poly *a, uint32_t B); +void poly_uniform(poly *a, const uint8_t *buf); +void poly_uniform_eta(poly *a, + const uint8_t seed[SEEDBYTES], + uint8_t nonce); +void poly_uniform_gamma1m1(poly *a, + const uint8_t seed[SEEDBYTES + CRHBYTES], + uint16_t nonce); + +void polyeta_pack(uint8_t *r, const poly *a); +void polyeta_unpack(poly *r, const uint8_t *a); + +void polyt1_pack(uint8_t *r, const poly *a); +void polyt1_unpack(poly *r, const uint8_t *a); + +void polyt0_pack(uint8_t *r, const poly *a); +void polyt0_unpack(poly *r, const uint8_t *a); + +void polyz_pack(uint8_t *r, const poly *a); +void polyz_unpack(poly *r, const uint8_t *a); + +void polyw1_pack(uint8_t *r, const poly *a); +#endif +#ifndef POLYVEC_H +#define POLYVEC_H + +//#include +//#include "params.h" +//#include "poly.h" + +/* Vectors of polynomials of length L */ +typedef struct { + poly vec[L]; +} polyvecl; + +void polyvecl_freeze(polyvecl *v); + +void polyvecl_add(polyvecl *w, const polyvecl *u, const polyvecl *v); + +void polyvecl_ntt(polyvecl *v); +void polyvecl_pointwise_acc_invmontgomery(poly *w, + const polyvecl *u, + const polyvecl *v); + +int polyvecl_chknorm(const polyvecl *v, uint32_t B); + + + +/* Vectors of polynomials of length K */ +typedef struct { + poly vec[K]; +} polyveck; + +void polyveck_reduce(polyveck *v); +void polyveck_csubq(polyveck *v); +void polyveck_freeze(polyveck *v); + +void polyveck_add(polyveck *w, const polyveck *u, const polyveck *v); +void polyveck_sub(polyveck *w, const polyveck *u, const polyveck *v); +void polyveck_shiftl(polyveck *v, uint32_t k); + +void polyveck_ntt(polyveck *v); +void polyveck_invntt_montgomery(polyveck *v); + +int polyveck_chknorm(const polyveck *v, uint32_t B); + +void polyveck_power2round(polyveck *v1, polyveck *v0, const polyveck *v); +void polyveck_decompose(polyveck *v1, polyveck *v0, const polyveck *v); +uint32_t polyveck_make_hint(polyveck *h, + const polyveck *u, + const polyveck *v); +void polyveck_use_hint(polyveck *w, const polyveck *v, const polyveck *h); + +#endif + +#ifndef NTT_H +#define NTT_H + +//#include +//#include "params.h" + +void ntt(uint32_t p[N]); +void invntt_frominvmont(uint32_t p[N]); + +#endif +#ifndef PACKING_H +#define PACKING_H + +//#include "params.h" +//#include "polyvec.h" + +void pack_pk(uint8_t pk[CRYPTO_PUBLICKEYBYTES], + const uint8_t rho[SEEDBYTES], const polyveck *t1); +void pack_sk(uint8_t sk[CRYPTO_SECRETKEYBYTES], + const uint8_t rho[SEEDBYTES], + const uint8_t key[SEEDBYTES], + const uint8_t tr[CRHBYTES], + const polyvecl *s1, + const polyveck *s2, + const polyveck *t0); +void pack_sig(uint8_t sig[CRYPTO_BYTES], + const polyvecl *z, const polyveck *h, const poly *c); + +void unpack_pk(uint8_t rho[SEEDBYTES], polyveck *t1, + const uint8_t pk[CRYPTO_PUBLICKEYBYTES]); +void unpack_sk(uint8_t rho[SEEDBYTES], + uint8_t key[SEEDBYTES], + uint8_t tr[CRHBYTES], + polyvecl *s1, + polyveck *s2, + polyveck *t0, + const uint8_t sk[CRYPTO_SECRETKEYBYTES]); +int unpack_sig(polyvecl *z, polyveck *h, poly *c, + const uint8_t sig[CRYPTO_BYTES]); + +#endif +#ifndef REDUCE_H +#define REDUCE_H + +//#include + +#define MONT 4193792U // 2^32 % Q +#define QINV 4236238847U // -q^(-1) mod 2^32 + +/* a <= Q*2^32 => r < 2*Q */ +uint32_t montgomery_reduce(uint64_t a); + +/* r < 2*Q */ +uint32_t reduce32(uint32_t a); + +/* a < 2*Q => r < Q */ +uint32_t csubq(uint32_t a); + +/* r < Q */ +uint32_t freeze(uint32_t a); + +#endif +#ifndef ROUNDING_H +#define ROUNDING_H + +//#include + +uint32_t power2round(const uint32_t a, uint32_t *a0); +uint32_t decompose(uint32_t a, uint32_t *a0); +uint32_t make_hint(const uint32_t a, const uint32_t b); +uint32_t use_hint(const uint32_t a, const uint32_t hint); + +#endif +#ifndef SIGN_H +#define SIGN_H + +//#include "params.h" +//#include "poly.h" +//#include "polyvec.h" + +void expand_mat(polyvecl mat[K], const uint8_t rho[SEEDBYTES]); +void challenge(poly *c, const uint8_t mu[CRHBYTES], + const polyveck *w1); + +int crypto_sign_keypair(uint8_t *pk, uint8_t *sk); + +int crypto_sign(uint8_t *sm, int32_t *smlen, + const uint8_t *msg, int32_t len, + const uint8_t *sk); + +int crypto_sign_open(uint8_t *m, int32_t *mlen, + const uint8_t *sm, int32_t smlen, + const uint8_t *pk); + +#endif + +#ifndef API_H +#define API_H + +#ifndef MODE +#define MODE 2 +#endif + +#if MODE == 0 +#if CRYPTO_PUBLICKEYBYTES -896U +CRYPTO_PUBLICKEYBYTES size error +#endif +#if CRYPTO_SECRETKEYBYTES -2096U +CRYPTO_SECRETKEYBYTES size error +#endif +#if CRYPTO_BYTES -1387U +CRYPTO_BYTES size error +#endif + +#elif MODE == 1 +#if CRYPTO_PUBLICKEYBYTES -1184U +CRYPTO_PUBLICKEYBYTES size error +#endif +#if CRYPTO_SECRETKEYBYTES -2800U +CRYPTO_SECRETKEYBYTES size error +#endif +#if CRYPTO_BYTES -2044U +CRYPTO_BYTES size error +#endif + +#elif MODE == 2 +#if CRYPTO_PUBLICKEYBYTES -1472U +CRYPTO_PUBLICKEYBYTES size error +#endif +#if CRYPTO_SECRETKEYBYTES -3504U +CRYPTO_SECRETKEYBYTES size error +#endif +#if CRYPTO_BYTES -2701U +CRYPTO_BYTES size error +#endif + +#elif MODE == 3 +#if CRYPTO_PUBLICKEYBYTES -1760U +CRYPTO_PUBLICKEYBYTES size error +#endif +#if CRYPTO_SECRETKEYBYTES -3856U +CRYPTO_SECRETKEYBYTES size error +#endif +#if CRYPTO_BYTES -3366U +CRYPTO_BYTES size error +#endif + +#endif + +#define CRYPTO_ALGNAME "Dilithium" + +int crypto_sign_keypair(uint8_t *pk, uint8_t *sk); + +int crypto_sign(uint8_t *sm, int32_t *smlen, + const uint8_t *msg, int32_t len, + const uint8_t *sk); + +int crypto_sign_open(uint8_t *m, int32_t *mlen, + const uint8_t *sm, int32_t smlen, + const uint8_t *pk); + +#endif diff --git a/src/cc/makecclib b/src/cc/makecclib index f4d2bd01b..adac757c3 100755 --- a/src/cc/makecclib +++ b/src/cc/makecclib @@ -1,2 +1,2 @@ #!/bin/sh -gcc -std=c++11 -I../secp256k1/include -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -c -o ../libcc.so cclib.cpp +gcc -O3 -std=c++11 -I../secp256k1/include -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -c -o ../libcc.so cclib.cpp diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index bd3d74a95..6dbab482a 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -659,12 +659,12 @@ UniValue musig_partialsig(uint64_t txfee,struct CCcontract_info *cp,cJSON *param } else return(cclib_error(result,"wrong number of params, need 3: pkhash, ind, partialsig")); } -int testmain(void); +//int testmain(void); UniValue musig_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { static secp256k1_context *ctx; UniValue result(UniValue::VOBJ); int32_t i,n; uint8_t msg[32],musig64[64]; secp256k1_pubkey combined_pk; secp256k1_schnorrsig musig; char str[129]; - testmain(); + //testmain(); if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) From ad439274bd21d003280c35468f937ef152ceac35 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 22 Feb 2019 21:07:37 -1100 Subject: [PATCH 318/390] include --- src/cc/cclib.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 84f229069..c7372907e 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -581,7 +581,7 @@ uint256 juint256(cJSON *obj) #else #include "sudoku.cpp" #include "musig.cpp" -#inclide "dilithium.c" +#include "dilithium.c" //#include "../secp256k1/src/modules/musig/example.c" #endif From fc0b7b15c8f46618794734d27449f031acc8f34c Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 22 Feb 2019 21:16:25 -1100 Subject: [PATCH 319/390] Revert to boost 1.66 --- depends/packages/boost.mk | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/depends/packages/boost.mk b/depends/packages/boost.mk index 7a0439ba7..3c180b0ce 100644 --- a/depends/packages/boost.mk +++ b/depends/packages/boost.mk @@ -1,8 +1,8 @@ package=boost -$(package)_version=1_69_0 -$(package)_download_path=https://dl.bintray.com/boostorg/release/1.69.0/source +$(package)_version=1_66_0 +$(package)_download_path=https://dl.bintray.com/boostorg/release/1.66.0/source $(package)_file_name=$(package)_$($(package)_version).tar.bz2 -$(package)_sha256_hash=8f32d4617390d1c2d16f26a27ab60d97807b35440d45891fa340fc2648b04406 +$(package)_sha256_hash=5721818253e6a0989583192f96782c4a98eb6204965316df9f5ad75819225ca9 define $(package)_set_vars $(package)_config_opts_release=variant=release From 33f126914ed4152f7832c660299980af972b847c Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 22 Feb 2019 21:45:03 -1100 Subject: [PATCH 320/390] Dilithium key pair --- src/cc/cclib.cpp | 33 +++++++++++++++++++++++++++++++++ src/cc/dilithium.c | 39 +++++++++++++++++++++++++++++++++++++++ src/cc/dilithium.h | 9 +++++---- 3 files changed, 77 insertions(+), 4 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index c7372907e..46a5f4736 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -37,6 +37,7 @@ std::string MYCCLIBNAME = (char *)"rogue"; #define EVAL_SUDOKU 17 #define EVAL_MUSIG 18 +#define EVAL_DILITHIUM 19 std::string MYCCLIBNAME = (char *)"sudoku"; #endif @@ -80,6 +81,11 @@ CClib_methods[] = { (char *)"musig", (char *)"verify", (char *)"msg sig pubkey", 3, 3, 'V', EVAL_MUSIG }, { (char *)"musig", (char *)"send", (char *)"combined_pk amount", 2, 2, 'x', EVAL_MUSIG }, { (char *)"musig", (char *)"spend", (char *)"sendtxid sig destpubkey", 3, 3, 'y', EVAL_MUSIG }, + { (char *)"dilithium", (char *)"keypair", (char *)"", 0, 0, 'K', EVAL_DILITHIUM }, + { (char *)"dilithium", (char *)"sign", (char *)"msg privkey", 2, 2, 'S', EVAL_DILITHIUM }, + { (char *)"dilithium", (char *)"verify", (char *)"msg sig pubtxid", 3, 3, 'V', EVAL_DILITHIUM }, + { (char *)"dilithium", (char *)"send", (char *)"pubtxid amount", 2, 2, 'x', EVAL_DILITHIUM }, + { (char *)"dilithium", (char *)"spend", (char *)"sendtxid sig destpubkey", 3, 3, 'y', EVAL_DILITHIUM }, #endif }; @@ -119,6 +125,13 @@ UniValue musig_partialsig(uint64_t txfee,struct CCcontract_info *cp,cJSON *param UniValue musig_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue musig_send(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); + +UniValue dilithium_send(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +UniValue dilithium_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +UniValue dilithium_keypair(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +UniValue dilithium_sign(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +UniValue dilithium_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); + #endif cJSON *cclib_reparse(int32_t *nump,char *jsonstr) // assumes origparams will be freed by caller @@ -243,6 +256,26 @@ UniValue CClib_method(struct CCcontract_info *cp,char *method,char *jsonstr) return(result); } } + else if ( cp->evalcode == EVAL_DILITHIUM ) + { + if ( strcmp(method,"send") == 0 ) + return(dilithium_send(txfee,cp,params)); + else if ( strcmp(method,"spend") == 0 ) + return(dilithium_spend(txfee,cp,params)); + else if ( strcmp(method,"keypair") == 0 ) + return(dilithium_keypair(txfee,cp,params)); + else if ( strcmp(method,"sign") == 0 ) + return(dilithium_sign(txfee,cp,params)); + else if ( strcmp(method,"verify") == 0 ) + return(dilithium_verify(txfee,cp,params)); + else + { + result.push_back(Pair("result","error")); + result.push_back(Pair("error","invalid dilithium method")); + result.push_back(Pair("method",method)); + return(result); + } + } #endif else { diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index b6624353e..902a3ca49 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -2835,3 +2835,42 @@ int32_t main(void) } #endif +UniValue dilithium_keypair(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ); uint8_t pk[CRYPTO_PUBLICKEYBYTES],sk[CRYPTO_SECRETKEYBYTES]; char str[CRYPTO_SECRETKEYBYTES*2+1]; int32_t i; + dilithium_keypair(pk,sk); + for (i=0; i +/* #ifndef CPUCYCLES_H #define CPUCYCLES_H @@ -11,7 +12,7 @@ #define DBENCH_STOP(t) #endif -#ifdef USE_RDPMC /* Needs echo 2 > /sys/devices/cpu/rdpmc */ +#ifdef USE_RDPMC // Needs echo 2 > /sys/devices/cpu/rdpmc #ifdef SERIALIZE_RDC static inline uint64_t cpucycles_start(void) { @@ -103,7 +104,7 @@ static inline uint64_t cpucycles_stop(void) { int64_t cpucycles_overhead(void); -#endif +#endif*/ #ifndef FIPS202_H #define FIPS202_H @@ -144,7 +145,7 @@ void shake256(uint8_t *output, #define PARAMS_H #ifndef MODE -#define MODE 2 +#define MODE 3 #endif #define SEEDBYTES 32U @@ -410,7 +411,7 @@ int crypto_sign_open(uint8_t *m, int32_t *mlen, #define API_H #ifndef MODE -#define MODE 2 +#define MODE 3 #endif #if MODE == 0 From 3846555d1914b38bb95455e3e2143bc1b427252f Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 22 Feb 2019 21:46:51 -1100 Subject: [PATCH 321/390] Dbench start/stop --- src/cc/dilithium.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index 902a3ca49..6a7f90d83 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -6,6 +6,10 @@ * by Gilles Van Assche, Daniel J. Bernstein, and Peter Schwabe */ #include + +#define DBENCH_START() +#define DBENCH_STOP() + #include "dilithium.h" From 54e28a8ebf715800b4d3436a1adf445f07760070 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 22 Feb 2019 21:48:26 -1100 Subject: [PATCH 322/390] Arg --- src/cc/dilithium.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index 6a7f90d83..cfe3b253f 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -8,7 +8,7 @@ #include #define DBENCH_START() -#define DBENCH_STOP() +#define DBENCH_STOP(arg) #include "dilithium.h" From 99f94425ebc6d1b1eedaaf50cb871092f97fc09e Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 23 Feb 2019 03:18:52 -1100 Subject: [PATCH 323/390] +prints --- src/cc/dilithium.c | 22 ++++++++++++---------- src/cc/rogue_rpc.cpp | 9 ++++++--- 2 files changed, 18 insertions(+), 13 deletions(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index cfe3b253f..9103a6037 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -2426,7 +2426,7 @@ void challenge(poly *c, } /************************************************* -* Name: dilithium_keypair +* Name: _dilithium_keypair * * Description: Generates public and private key. * @@ -2437,7 +2437,7 @@ void challenge(poly *c, * * Returns 0 (success) **************************************************/ -int dilithium_keypair(uint8_t *pk, uint8_t *sk) { +int _dilithium_keypair(uint8_t *pk, uint8_t *sk) { uint32_t i; uint8_t seedbuf[3*SEEDBYTES]; uint8_t tr[CRHBYTES]; @@ -2488,7 +2488,7 @@ int dilithium_keypair(uint8_t *pk, uint8_t *sk) { } /************************************************* -* Name: dilithium_sign +* Name: _dilithium_sign * * Description: Compute signed message. * @@ -2503,7 +2503,7 @@ int dilithium_keypair(uint8_t *pk, uint8_t *sk) { * * Returns 0 (success) **************************************************/ -int dilithium_sign(uint8_t *sm, +int _dilithium_sign(uint8_t *sm, int32_t *smlen, const uint8_t *m, int32_t mlen, @@ -2613,7 +2613,7 @@ int dilithium_sign(uint8_t *sm, } /************************************************* -* Name: dilithium_verify +* Name: _dilithium_verify * * Description: Verify signed message. * @@ -2626,7 +2626,7 @@ int dilithium_sign(uint8_t *sm, * * Returns 0 if signed message could be verified correctly and -1 otherwise **************************************************/ -int dilithium_verify(uint8_t *m, +int _dilithium_verify(uint8_t *m, int32_t *mlen, const uint8_t *sm, int32_t smlen, @@ -2785,7 +2785,7 @@ int32_t main(void) tkeygen[i] = cpucycles_start(); #endif - dilithium_keypair(pk, sk); // 1.3 + _dilithium_keypair(pk, sk); // 1.3 #ifdef DBENCH tkeygen[i] = cpucycles_stop() - tkeygen[i] - timing_overhead; // tred = tadd = tmul = tround = tsample = tpack = tshake = &dummy; @@ -2793,13 +2793,13 @@ int32_t main(void) #endif randombytes(m, MLEN); // 1.27 - dilithium_sign(sm, &smlen, m, MLEN, sk); // 7.2 + _dilithium_sign(sm, &smlen, m, MLEN, sk); // 7.2 #ifdef DBENCH tsign[i] = cpucycles_stop() - tsign[i] - timing_overhead; tverify[i] = cpucycles_start(); #endif - ret = dilithium_verify(m2, &mlen, sm, smlen, pk); + ret = _dilithium_verify(m2, &mlen, sm, smlen, pk); #ifdef DBENCH tverify[i] = cpucycles_stop() - tverify[i] - timing_overhead; #endif @@ -2842,7 +2842,7 @@ int32_t main(void) UniValue dilithium_keypair(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { UniValue result(UniValue::VOBJ); uint8_t pk[CRYPTO_PUBLICKEYBYTES],sk[CRYPTO_SECRETKEYBYTES]; char str[CRYPTO_SECRETKEYBYTES*2+1]; int32_t i; - dilithium_keypair(pk,sk); + _dilithium_keypair(pk,sk); for (i=0; i>16,endP.level,endP.experience,endP.dungeonlevel); fprintf(stderr,"%s\n",str); + *numkeysp = numkeys; + return(keystrokes); } else num = 0; } else fprintf(stderr,"extractgame: couldnt find baton\n"); } else fprintf(stderr,"extractgame: invalid game\n"); - *numkeysp = numkeys; - return(keystrokes); + return(0); } UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) From 504fed539e7b2d8759ebf72d13a4e1469affa649 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 23 Feb 2019 03:30:44 -1100 Subject: [PATCH 324/390] +prints --- src/cc/rogue_rpc.cpp | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index edac1d813..fd068aca4 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -890,8 +890,15 @@ char *rogue_extractgame(int32_t makefiles,char *str,int32_t *numkeysp,std::vecto *numkeysp = numkeys; return(keystrokes); } else num = 0; - } else fprintf(stderr,"extractgame: couldnt find baton\n"); + } + else + { + fprintf(stderr,"extractgame: couldnt find baton keystrokes.%p\n",keystrokes); + if ( keystrokes != 0 ) + free(keystrokes), keystrokes = 0; + } } else fprintf(stderr,"extractgame: invalid game\n"); + fprintf(stderr,"extract %s\n",gametxid.GetHex().c_str()); return(0); } @@ -1248,6 +1255,7 @@ int32_t rogue_playerdata_validate(uint256 &playertxid,struct CCcontract_info *cp //fprintf(stderr,"call extractgame\n"); if ( (keystrokes= rogue_extractgame(0,str,&numkeys,newdata,seed,playertxid,cp,gametxid,rogueaddr)) != 0 ) { + fprintf(stderr,"numkeys.%d rogue_extractgame %s\n",numkeys,gametxid.GetHex().c_str()); free(keystrokes); //fprintf(stderr,"extracted.(%s)\n",str); if ( newdata == playerdata ) @@ -1273,6 +1281,7 @@ int32_t rogue_playerdata_validate(uint256 &playertxid,struct CCcontract_info *cp fprintf(stderr,"%s playerdata: gold.%d hp.%d strength.%d/%d level.%d exp.%d dl.%d\n",gametxid.GetHex().c_str(),P.gold,P.hitpoints,P.strength&0xffff,P.strength>>16,P.level,P.experience,P.dungeonlevel); fprintf(stderr,"newdata[%d] != playerdata[%d], numkeys.%d %s pub.%s playertxid.%s good.%d bad.%d\n",(int32_t)newdata.size(),(int32_t)playerdata.size(),numkeys,rogueaddr,pubkey33_str(str2,(uint8_t *)&pk),playertxid.GetHex().c_str(),good,bad); } + fprintf(stderr,"no keys rogue_extractgame %s\n",gametxid.GetHex().c_str()); return(-1); } From 348d6df6a520382ef91be6e94d93e7dd60579865 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 23 Feb 2019 03:40:13 -1100 Subject: [PATCH 325/390] -print --- src/cc/rogue_rpc.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index fd068aca4..5aa5b3a8d 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -898,7 +898,7 @@ char *rogue_extractgame(int32_t makefiles,char *str,int32_t *numkeysp,std::vecto free(keystrokes), keystrokes = 0; } } else fprintf(stderr,"extractgame: invalid game\n"); - fprintf(stderr,"extract %s\n",gametxid.GetHex().c_str()); + //fprintf(stderr,"extract %s\n",gametxid.GetHex().c_str()); return(0); } @@ -1255,7 +1255,7 @@ int32_t rogue_playerdata_validate(uint256 &playertxid,struct CCcontract_info *cp //fprintf(stderr,"call extractgame\n"); if ( (keystrokes= rogue_extractgame(0,str,&numkeys,newdata,seed,playertxid,cp,gametxid,rogueaddr)) != 0 ) { - fprintf(stderr,"numkeys.%d rogue_extractgame %s\n",numkeys,gametxid.GetHex().c_str()); + //fprintf(stderr,"numkeys.%d rogue_extractgame %s\n",numkeys,gametxid.GetHex().c_str()); free(keystrokes); //fprintf(stderr,"extracted.(%s)\n",str); if ( newdata == playerdata ) @@ -1281,7 +1281,7 @@ int32_t rogue_playerdata_validate(uint256 &playertxid,struct CCcontract_info *cp fprintf(stderr,"%s playerdata: gold.%d hp.%d strength.%d/%d level.%d exp.%d dl.%d\n",gametxid.GetHex().c_str(),P.gold,P.hitpoints,P.strength&0xffff,P.strength>>16,P.level,P.experience,P.dungeonlevel); fprintf(stderr,"newdata[%d] != playerdata[%d], numkeys.%d %s pub.%s playertxid.%s good.%d bad.%d\n",(int32_t)newdata.size(),(int32_t)playerdata.size(),numkeys,rogueaddr,pubkey33_str(str2,(uint8_t *)&pk),playertxid.GetHex().c_str(),good,bad); } - fprintf(stderr,"no keys rogue_extractgame %s\n",gametxid.GetHex().c_str()); + //fprintf(stderr,"no keys rogue_extractgame %s\n",gametxid.GetHex().c_str()); return(-1); } From 09b5de739be060ae95474754497e4749adc65cfe Mon Sep 17 00:00:00 2001 From: CHMEX <33424502+CHMEX@users.noreply.github.com> Date: Sat, 23 Feb 2019 16:11:56 +0100 Subject: [PATCH 326/390] OUR OUR is notarized but missing. --- src/assetchains.json | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/src/assetchains.json b/src/assetchains.json index 1b23bc616..91baf9829 100644 --- a/src/assetchains.json +++ b/src/assetchains.json @@ -224,5 +224,21 @@ "addnode": [ "37.187.225.231" ] - } + }, + { + "ac_name": "OUR", + "ac_reward": "1478310502", + "ac_halving": "525600", + "ac_cc": "42", + "ac_supply": "100000000", + "ac_perc": "77700", + "ac_staked": "93", + "ac_pubkey": "02652a3f3e00b3a1875a918314f0bac838d6dd189a346fa623f5efe9541ac0b98c", + "ac_public": "1", + "addnode": [ + "51.255.195.65", + "217.182.129.38", + "95.216.150.177" + ] +} ] From 1b5d9b5032f41422113868eca35d182c07529f7e Mon Sep 17 00:00:00 2001 From: blackjok3r Date: Sat, 23 Feb 2019 23:24:17 +0800 Subject: [PATCH 327/390] show --- src/cc/musig.cpp | 106 +++++++++++++--------- src/musigtest.py | 189 +++++++++++++++++++++++++++++++++++++++ src/wallet/rpcwallet.cpp | 8 +- 3 files changed, 255 insertions(+), 48 deletions(-) create mode 100755 src/musigtest.py diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index bd3d74a95..cdf53be09 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -89,7 +89,7 @@ the "msg" is what needs to be signed to create a valid spend "numsigners": 2, "commitment": "bbea1f2562eca01b9a1393c5dc188bdd44551aebf684f4459930f59dde01f7ae", "result": "success" - } +} on node with pubkey: 0255c46dbce584e3751081b39d7fc054fc807100557e73fc444481618b5706afb4 ./komodo-cli -ac_name=MUSIG cclib session 18 '[1,2,"03f016c348437c7422eed92d865aa9789614f75327cada463eefc566126b54785b","5cb5a225064ca6ffc1438cb2a6ac2ac65fe2d5055dc7f6c7ebffb9a231f8912b","f7fb85d1412814e3c2f98b990802af6ee33dad368c6ba05c2050e9e5506fcd75"]' @@ -221,7 +221,9 @@ struct musig_info secp256k1_musig_partial_signature *partial_sig; //[N_SIGNERS]; int32_t myind,num; uint8_t msg[32],pkhash[32],combpk[33]; -} *MUSIG; +}; + +std::vector MUSIG; struct musig_info *musig_infocreate(int32_t myind,int32_t num) { @@ -431,14 +433,15 @@ UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) num = juint(jitem(params,1),0); if ( myind < 0 || myind >= num || num <= 0 ) return(cclib_error(result,"illegal myindex and numsigners")); - if ( MUSIG != 0 ) - musig_infofree(MUSIG), MUSIG = 0; - MUSIG = musig_infocreate(myind,num); - if ( musig_parsepubkey(ctx,MUSIG->combined_pk,jitem(params,2)) < 0 ) + //if ( MUSIG[myind] != 0 ) + // musig_infofree(MUSIG[myind]), MUSIG[myind] = 0; + struct musig_info *temp_musig = musig_infocreate(myind,num); + MUSIG.push_back(temp_musig); + if ( musig_parsepubkey(ctx,MUSIG[myind]->combined_pk,jitem(params,2)) < 0 ) return(cclib_error(result,"error parsing combined_pubkey")); - else if ( musig_parsehash(MUSIG->pkhash,jitem(params,3),32) < 0 ) + else if ( musig_parsehash(MUSIG[myind]->pkhash,jitem(params,3),32) < 0 ) return(cclib_error(result,"error parsing pkhash")); - else if ( musig_parsehash(MUSIG->msg,jitem(params,4),32) < 0 ) + else if ( musig_parsehash(MUSIG[myind]->msg,jitem(params,4),32) < 0 ) return(cclib_error(result,"error parsing msg")); Myprivkey(privkey); GetRandBytes(session,32); @@ -468,13 +471,13 @@ UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) * my_index: index of this signer in the signers array * seckey: the signer's 32-byte secret key (cannot be NULL) */ - if ( secp256k1_musig_session_initialize(ctx,&MUSIG->session,MUSIG->signer_data, &MUSIG->nonce_commitments[MUSIG->myind * 32],session,MUSIG->msg,&MUSIG->combined_pk,MUSIG->pkhash,MUSIG->num,MUSIG->myind,privkey) > 0 ) + if ( secp256k1_musig_session_initialize(ctx,&MUSIG[myind]->session,MUSIG[myind]->signer_data, &MUSIG[myind]->nonce_commitments[MUSIG[myind]->myind * 32],session,MUSIG[myind]->msg,&MUSIG[myind]->combined_pk,MUSIG[myind]->pkhash,MUSIG[myind]->num,MUSIG[myind]->myind,privkey) > 0 ) { memset(session,0,sizeof(session)); result.push_back(Pair("myind",(int64_t)myind)); result.push_back(Pair("numsigners",(int64_t)num)); for (i=0; i<32; i++) - sprintf(&str[i<<1],"%02x",MUSIG->nonce_commitments[MUSIG->myind*32 + i]); + sprintf(&str[i<<1],"%02x",MUSIG[myind]->nonce_commitments[MUSIG[myind]->myind*32 + i]); str[64] = 0; result.push_back(Pair("commitment",str)); result.push_back(Pair("result","success")); @@ -492,18 +495,20 @@ UniValue musig_commit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { static secp256k1_context *ctx; size_t clen = CPubKey::PUBLIC_KEY_SIZE; - UniValue result(UniValue::VOBJ); int32_t i,n,ind; uint8_t pkhash[32]; CPubKey pk; char str[67]; + UniValue result(UniValue::VOBJ); int32_t i,n,ind,myind; uint8_t pkhash[32]; CPubKey pk; char str[67]; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); - if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) + if ( params != 0 && (n= cJSON_GetArraySize(params)) == 4 ) { - if ( musig_parsehash(pkhash,jitem(params,0),32) < 0 ) + if ( (myind= juint(jitem(params,0),0)) < 0 ) + return(cclib_error(result,"myind is wrong")); + if ( musig_parsehash(pkhash,jitem(params,1),32) < 0 ) return(cclib_error(result,"error parsing pkhash")); - else if ( memcmp(MUSIG->pkhash,pkhash,32) != 0 ) + else if ( memcmp(MUSIG[myind]->pkhash,pkhash,32) != 0 ) return(cclib_error(result,"pkhash doesnt match session pkhash")); - else if ( (ind= juint(jitem(params,1),0)) < 0 || ind >= MUSIG->num ) + else if ( (ind= juint(jitem(params,2),0)) < 0 || ind >= MUSIG[myind]->num ) return(cclib_error(result,"illegal ind for session")); - else if ( musig_parsehash(&MUSIG->nonce_commitments[ind*32],jitem(params,2),32) < 0 ) + else if ( musig_parsehash(&MUSIG[myind]->nonce_commitments[ind*32],jitem(params,3),32) < 0 ) return(cclib_error(result,"error parsing commitment")); /** Gets the signer's public nonce given a list of all signers' data with commitments * @@ -521,14 +526,15 @@ UniValue musig_commit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) * number of signers participating in the MuSig. */ result.push_back(Pair("added_index",ind)); - if ( secp256k1_musig_session_get_public_nonce(ctx,&MUSIG->session,MUSIG->signer_data,&MUSIG->nonces[MUSIG->myind],MUSIG->commitment_ptrs,MUSIG->num) > 0 ) + fprintf(stderr, "COMMIT: number of MUSIG structs.%li using struct.%i addedindex.%i\n",MUSIG.size(),myind,ind); + if ( secp256k1_musig_session_get_public_nonce(ctx,&MUSIG[myind]->session,MUSIG[myind]->signer_data,&MUSIG[myind]->nonces[MUSIG[myind]->myind],MUSIG[myind]->commitment_ptrs,MUSIG[myind]->num) > 0 ) { - if ( secp256k1_ec_pubkey_serialize(ctx,(uint8_t *)pk.begin(),&clen,&MUSIG->nonces[MUSIG->myind],SECP256K1_EC_COMPRESSED) > 0 && clen == 33 ) + if ( secp256k1_ec_pubkey_serialize(ctx,(uint8_t *)pk.begin(),&clen,&MUSIG[myind]->nonces[MUSIG[myind]->myind],SECP256K1_EC_COMPRESSED) > 0 && clen == 33 ) { for (i=0; i<33; i++) sprintf(&str[i<<1],"%02x",((uint8_t *)pk.begin())[i]); str[66] = 0; - result.push_back(Pair("myind",MUSIG->myind)); + result.push_back(Pair("myind",MUSIG[myind]->myind)); result.push_back(Pair("nonce",str)); result.push_back(Pair("result","success")); } else return(cclib_error(result,"error serializing nonce (pubkey)")); @@ -539,26 +545,29 @@ UniValue musig_commit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) result.push_back(Pair("result","success")); } return(result); - } else return(cclib_error(result,"wrong number of params, need 3: pkhash, ind, commitment")); + } else return(cclib_error(result,"wrong number of params, need 4: myind, pkhash, ind, commitment")); } UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { static secp256k1_context *ctx; - UniValue result(UniValue::VOBJ); int32_t i,n,ind; uint8_t pkhash[32],psig[32]; CPubKey pk; char str[67]; + UniValue result(UniValue::VOBJ); int32_t i,n,ind,myind; uint8_t pkhash[32],psig[32]; CPubKey pk; char str[67]; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); - if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) + if ( params != 0 && (n= cJSON_GetArraySize(params)) == 4 ) { - if ( musig_parsehash(pkhash,jitem(params,0),32) < 0 ) + if ( (myind= juint(jitem(params,0),0)) < 0 ) + return(cclib_error(result,"myind is wrong")); + if ( musig_parsehash(pkhash,jitem(params,1),32) < 0 ) return(cclib_error(result,"error parsing pkhash")); - else if ( memcmp(MUSIG->pkhash,pkhash,32) != 0 ) + else if ( memcmp(MUSIG[myind]->pkhash,pkhash,32) != 0 ) return(cclib_error(result,"pkhash doesnt match session pkhash")); - else if ( (ind= juint(jitem(params,1),0)) < 0 || ind >= MUSIG->num ) + else if ( (ind= juint(jitem(params,2),0)) < 0 || ind >= MUSIG[myind]->num ) return(cclib_error(result,"illegal ind for session")); - else if ( musig_parsepubkey(ctx,MUSIG->nonces[ind],jitem(params,2)) < 0 ) + else if ( musig_parsepubkey(ctx,MUSIG[myind]->nonces[ind],jitem(params,3)) < 0 ) return(cclib_error(result,"error parsing nonce")); result.push_back(Pair("added_index",ind)); + fprintf(stderr, "NONCE: number of MUSIG structs.%li using struct.%i addedindex.%i\n",MUSIG.size(),myind,ind); /** Checks a signer's public nonce against a commitment to said nonce, and update * data structure if they match * @@ -569,10 +578,16 @@ UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) * been used with `musig_session_get_public_nonce` or initialized * with `musig_session_initialize_verifier`. * In: nonce: signer's alleged public nonce (cannot be NULL) - */ - for (i=0; inum; i++) + * + if ( ind != MUSIG[myind]->num-1 ) { - if ( secp256k1_musig_set_nonce(ctx,&MUSIG->signer_data[i],&MUSIG->nonces[i]) == 0 ) + fprintf(stderr, "ind.%i MUSIG[myind]->num.%i\n", ind, MUSIG[myind]->num); + return(cclib_error(result,"need rest of nonce's to continue")); + }*/ + for (i=0; inum; i++) + { + fprintf(stderr, "setting nonce for index.%i\n",i); + if ( secp256k1_musig_set_nonce(ctx,&MUSIG[myind]->signer_data[i],&MUSIG[myind]->nonces[i]) == 0 ) return(cclib_error(result,"error setting nonce")); } /** Updates a session with the combined public nonce of all signers. The combined @@ -593,45 +608,48 @@ UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) * adaptor: point to add to the combined public nonce. If NULL, nothing is * added to the combined nonce. */ - if ( secp256k1_musig_session_combine_nonces(ctx,&MUSIG->session,MUSIG->signer_data,MUSIG->num,NULL,NULL) > 0 ) + if ( secp256k1_musig_session_combine_nonces(ctx,&MUSIG[myind]->session,MUSIG[myind]->signer_data,MUSIG[myind]->num,NULL,NULL) > 0 ) { - if ( secp256k1_musig_partial_sign(ctx,&MUSIG->session,&MUSIG->partial_sig[MUSIG->myind]) > 0 ) + if ( secp256k1_musig_partial_sign(ctx,&MUSIG[myind]->session,&MUSIG[myind]->partial_sig[MUSIG[myind]->myind]) > 0 ) { - if ( secp256k1_musig_partial_signature_serialize(ctx,psig,&MUSIG->partial_sig[MUSIG->myind]) > 0 ) + if ( secp256k1_musig_partial_signature_serialize(ctx,psig,&MUSIG[myind]->partial_sig[MUSIG[myind]->myind]) > 0 ) { for (i=0; i<32; i++) sprintf(&str[i<<1],"%02x",psig[i]); str[64] = 0; - result.push_back(Pair("myind",MUSIG->myind)); + result.push_back(Pair("myind",MUSIG[myind]->myind)); result.push_back(Pair("partialsig",str)); result.push_back(Pair("result","success")); return(result); } else return(cclib_error(result,"error serializing partial sig")); } else return(cclib_error(result,"error making partial sig")); } else return(cclib_error(result,"error combining nonces")); - } else return(cclib_error(result,"wrong number of params, need 3: pkhash, ind, nonce")); + } else return(cclib_error(result,"wrong number of params, need 4: myind, pkhash, ind, nonce")); } UniValue musig_partialsig(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { static secp256k1_context *ctx; - UniValue result(UniValue::VOBJ); int32_t i,ind,n; uint8_t pkhash[32],psig[32],out64[64]; char str[129]; secp256k1_schnorrsig sig; + UniValue result(UniValue::VOBJ); int32_t i,ind,myind,n; uint8_t pkhash[32],psig[32],out64[64]; char str[129]; secp256k1_schnorrsig sig; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); - if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) + if ( params != 0 && (n= cJSON_GetArraySize(params)) == 4 ) { - if ( musig_parsehash(pkhash,jitem(params,0),32) < 0 ) + if ( (myind= juint(jitem(params,0),0)) < 0 ) + return(cclib_error(result,"myind is wrong")); + if ( musig_parsehash(pkhash,jitem(params,1),32) < 0 ) return(cclib_error(result,"error parsing pkhash")); - else if ( memcmp(MUSIG->pkhash,pkhash,32) != 0 ) + else if ( memcmp(MUSIG[myind]->pkhash,pkhash,32) != 0 ) return(cclib_error(result,"pkhash doesnt match session pkhash")); - else if ( (ind= juint(jitem(params,1),0)) < 0 || ind >= MUSIG->num ) + else if ( (ind= juint(jitem(params,2),0)) < 0 || ind >= MUSIG[myind]->num ) return(cclib_error(result,"illegal ind for session")); - else if ( musig_parsehash(psig,jitem(params,2),32) < 0 ) + else if ( musig_parsehash(psig,jitem(params,3),32) < 0 ) return(cclib_error(result,"error parsing psig")); - else if ( secp256k1_musig_partial_signature_parse(ctx,&MUSIG->partial_sig[ind],psig) == 0 ) + else if ( secp256k1_musig_partial_signature_parse(ctx,&MUSIG[myind]->partial_sig[ind],psig) == 0 ) return(cclib_error(result,"error parsing partialsig")); result.push_back(Pair("added_index",ind)); - if ( secp256k1_musig_partial_sig_combine(ctx,&MUSIG->session,&sig,MUSIG->partial_sig,MUSIG->num) > 0 ) + fprintf(stderr, "PARTIALSIG: number of MUSIG structs.%li using struct.%i addedindex.%i\n",MUSIG.size(),myind,ind); + if ( secp256k1_musig_partial_sig_combine(ctx,&MUSIG[myind]->session,&sig,MUSIG[myind]->partial_sig,MUSIG[myind]->num) > 0 ) { if ( secp256k1_schnorrsig_serialize(ctx,out64,&sig) > 0 ) { @@ -644,7 +662,7 @@ UniValue musig_partialsig(uint64_t txfee,struct CCcontract_info *cp,cJSON *param } else { - if ( secp256k1_musig_partial_signature_serialize(ctx,psig,&MUSIG->partial_sig[MUSIG->myind]) > 0 ) + if ( secp256k1_musig_partial_signature_serialize(ctx,psig,&MUSIG[myind]->partial_sig[MUSIG[myind]->myind]) > 0 ) { result.push_back(Pair("myind",ind)); for (i=0; i<32; i++) @@ -656,7 +674,7 @@ UniValue musig_partialsig(uint64_t txfee,struct CCcontract_info *cp,cJSON *param } else return(cclib_error(result,"error generating my partialsig")); } return(result); - } else return(cclib_error(result,"wrong number of params, need 3: pkhash, ind, partialsig")); + } else return(cclib_error(result,"wrong number of params, need 4: myind, pkhash, ind, partialsig")); } int testmain(void); diff --git a/src/musigtest.py b/src/musigtest.py new file mode 100755 index 000000000..26f09d588 --- /dev/null +++ b/src/musigtest.py @@ -0,0 +1,189 @@ +#!/usr/bin/env python3 +import platform +import os +import re +import json +import random +import base58 +import binascii +import hashlib +import sys +import time +from slickrpc import Proxy + +# fucntion to define rpc_connection +def def_credentials(chain): + rpcport = ''; + operating_system = platform.system() + if operating_system == 'Darwin': + ac_dir = os.environ['HOME'] + '/Library/Application Support/Komodo' + elif operating_system == 'Linux': + ac_dir = os.environ['HOME'] + '/.komodo' + elif operating_system == 'Windows': + ac_dir = '%s/komodo/' % os.environ['APPDATA'] + if chain == 'KMD': + coin_config_file = str(ac_dir + '/komodo.conf') + else: + coin_config_file = str(ac_dir + '/' + chain + '/' + chain + '.conf') + with open(coin_config_file, 'r') as f: + for line in f: + l = line.rstrip() + if re.search('rpcuser', l): + rpcuser = l.replace('rpcuser=', '') + elif re.search('rpcpassword', l): + rpcpassword = l.replace('rpcpassword=', '') + elif re.search('rpcport', l): + rpcport = l.replace('rpcport=', '') + if len(rpcport) == 0: + if chain == 'KMD': + rpcport = 7771 + else: + print("rpcport not in conf file, exiting") + print("check " + coin_config_file) + exit(1) + return (Proxy("http://%s:%s@127.0.0.1:%d" % (rpcuser, rpcpassword, int(rpcport)))) + + +# generate address, validate address, dump private key +def genvaldump(rpc_connection): + # get new address + address = rpc_connection.getnewaddress() + # validate address + validateaddress_result = rpc_connection.validateaddress(address) + pubkey = validateaddress_result['pubkey'] + address = validateaddress_result['address'] + # dump private key for the address + privkey = rpc_connection.dumpprivkey(address) + # function output + output = [pubkey, privkey, address] + return(output) + +CHAIN = 'MUSIG' #sys.argv[1] + +rpc = def_credentials(CHAIN) + +pubkeys = [] +address_info = [] +ret = input('Do you want to generate new pubkeys? ').lower() + +if ret.startswith('y'): + numpks = int(input('Enter number of pubkeys to combine: ')) + if os.path.isfile("list.json"): + print('Already have list.json, move it if you would like to generate a new set.') + sys.exit(0) + while len(address_info) < numpks: + addressinfo = genvaldump(rpc) + address_info.append(addressinfo) + f = open("list.json", "w+") + f.write(json.dumps(address_info)) +else: + if os.path.isfile("list.json"): + with open('list.json') as list: + address_info = json.load(list) + else: + sys.exit('No list.json you need to create new pubkeys!') + +for addressinfo in address_info: + pubkeys.append(addressinfo[0]) + +ret = rpc.setpubkey(pubkeys[0]) +ret = rpc.cclib("combine", "18", str(pubkeys)) +pkhash = str(ret['pkhash']) +combinedpk = str(ret['combined_pk']) +print('Your combined pubkey is: ' + combinedpk) +print('Your pkhash is: ' + pkhash) +amount = int(input('Enter amount to send: ')) +tmp = str([combinedpk, amount]) +hex = rpc.cclib("send", "18", tmp)['hex'] +senttxid = rpc.sendrawtransaction(hex) +print('Your senttxid is: ' + senttxid) + +print("Waiting for tx to be confirmed") +while True: + confirmed = int(rpc.gettransaction(senttxid)["confirmations"]) + if not confirmed: + time.sleep(10) + else: + print('SentTX confirmed') + break + +scriptPubKey = rpc.getrawtransaction(senttxid,1)['vout'][1]['scriptPubKey']['hex'] +print('Your scriptPubKey is: ' + scriptPubKey) +tmp = str([senttxid, scriptPubKey]) +msg = rpc.cclib("calcmsg", "18", tmp)['msg'] +print('Your msg is: ' + msg) + +i = 0; +commitments = [] +for pubkey in pubkeys: + ret = rpc.setpubkey(pubkey) + tmp = str([i, len(pubkeys), combinedpk, pkhash, msg]) + commitments.append(rpc.cclib("session", "18", tmp)['commitment']) + i = i + 1 + +print(commitments) + +i = 0 +nonces = [] +for pubkey in pubkeys: + ret = rpc.setpubkey(pubkey) + n = 0 + for commitment in commitments: + if n == i: + n = n + 1 + continue; + tmp = str([i, pkhash, n, commitment]) + ret = rpc.cclib("commit", "18", tmp) + if len(ret) == 4: + nonces.append(ret['nonce']) + n = n + 1 + i = i + 1 + +print(nonces) + +i = 0 +partialsigs = [] +for pubkey in pubkeys: + ret = rpc.setpubkey(pubkey) + n = 0 + for nonce in nonces: + #if n == i: + # n = n + 1 + # continue; + tmp = str([i, pkhash, n, nonce]) + ret = rpc.cclib("nonce", "18", tmp) + print(ret) + if len(ret) == 4: + partialsigs.append(ret['partialsig']) + n = n + 1 + i = i + 1 + +print(partialsigs) + +i = 0 +combinedsigs = [] +for pubkey in pubkeys: + ret = rpc.setpubkey(pubkey) + n = 0 + for partialsig in partialsigs: + if n == i: + n = n + 1 + continue; + tmp = str([i, pkhash, n, partialsig]) + ret = rpc.cclib("partialsig", "18", tmp) + if len(ret) == 4: + combinedsigs.append(ret['combinedsig']) + n = n + 1 + i = i + 1 + +print(combinedsigs) + +tmp = str([msg, combinedpk, combinedsigs[0]]) +ret = rpc.cclib("verify", "18", tmp) + +print(ret) + +tmp = str([sendtxid, scriptPubKey, combinedsigs[0]]) +ret = rpc.cclib("spend", "18", tmp) + +print(ret) diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 0ed2f866c..8cffd78f7 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -5308,8 +5308,8 @@ UniValue setpubkey(const UniValue& params, bool fHelp) char Raddress[64]; uint8_t pubkey33[33]; - if ( NOTARY_PUBKEY33[0] == 0 ) - { + //if ( NOTARY_PUBKEY33[0] == 0 ) + //{ if (strlen(params[0].get_str().c_str()) == 66) { decode_hex(pubkey33,33,(char *)params[0].get_str().c_str()); @@ -5337,14 +5337,14 @@ UniValue setpubkey(const UniValue& params, bool fHelp) USE_EXTERNAL_PUBKEY = 1; } } else result.push_back(Pair("error", "pubkey is wrong length, must be 66 char hex string.")); - } + /*} else { result.push_back(Pair("error", "Can only set pubkey once, to change it you need to restart your daemon, pubkey in use is below.")); pubkey2addr((char *)Raddress,(uint8_t *)NOTARY_PUBKEY33); std::string address_ret; address_ret.assign(Raddress); result.push_back(Pair("address",address_ret)); - } + }*/ result.push_back(Pair("pubkey", NOTARY_PUBKEY)); return result; } From 69a890fe53bfa7d2025b8cebb6d3e5feed164c09 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 23 Feb 2019 04:56:59 -1100 Subject: [PATCH 328/390] Seed based dilithium key generation --- src/cc/cclib.cpp | 2 +- src/cc/dilithium.c | 26 +++++++++++++++++++++----- 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 46a5f4736..4f539b7f9 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -81,7 +81,7 @@ CClib_methods[] = { (char *)"musig", (char *)"verify", (char *)"msg sig pubkey", 3, 3, 'V', EVAL_MUSIG }, { (char *)"musig", (char *)"send", (char *)"combined_pk amount", 2, 2, 'x', EVAL_MUSIG }, { (char *)"musig", (char *)"spend", (char *)"sendtxid sig destpubkey", 3, 3, 'y', EVAL_MUSIG }, - { (char *)"dilithium", (char *)"keypair", (char *)"", 0, 0, 'K', EVAL_DILITHIUM }, + { (char *)"dilithium", (char *)"keypair", (char *)"[hexseed]", 0, 1, 'K', EVAL_DILITHIUM }, { (char *)"dilithium", (char *)"sign", (char *)"msg privkey", 2, 2, 'S', EVAL_DILITHIUM }, { (char *)"dilithium", (char *)"verify", (char *)"msg sig pubtxid", 3, 3, 'V', EVAL_DILITHIUM }, { (char *)"dilithium", (char *)"send", (char *)"pubtxid amount", 2, 2, 'x', EVAL_DILITHIUM }, diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index 9103a6037..10718d1c3 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -2437,7 +2437,8 @@ void challenge(poly *c, * * Returns 0 (success) **************************************************/ -int _dilithium_keypair(uint8_t *pk, uint8_t *sk) { +int _dilithium_keypair(uint8_t *pk, uint8_t *sk,uint8_t *privkey) +{ uint32_t i; uint8_t seedbuf[3*SEEDBYTES]; uint8_t tr[CRHBYTES]; @@ -2448,7 +2449,8 @@ int _dilithium_keypair(uint8_t *pk, uint8_t *sk) { polyveck s2, t, t1, t0; /* Expand 32 bytes of randomness into rho, rhoprime and key */ - randombytes(seedbuf, SEEDBYTES); + //randombytes(seedbuf, SEEDBYTES); + memcpy(seedbuf,privkey,SEEDBYTES); shake256(seedbuf, 3*SEEDBYTES, seedbuf, SEEDBYTES); rho = seedbuf; rhoprime = rho + SEEDBYTES; @@ -2841,8 +2843,16 @@ int32_t main(void) UniValue dilithium_keypair(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); uint8_t pk[CRYPTO_PUBLICKEYBYTES],sk[CRYPTO_SECRETKEYBYTES]; char str[CRYPTO_SECRETKEYBYTES*2+1]; int32_t i; - _dilithium_keypair(pk,sk); + UniValue result(UniValue::VOBJ); uint8_t seed[SEEDBYTES],pk[CRYPTO_PUBLICKEYBYTES],sk[CRYPTO_SECRETKEYBYTES]; char str[CRYPTO_SECRETKEYBYTES*2+1]; int32_t i,n,externalflag=0; + //randombytes(seed,SEEDBYTES); + Myprivkey(seed); + if ( params != 0 && (n= cJSON_GetArraySize(params)) == 1 ) + { + if ( musig_parsehash(seed,jitem(params,0),32) < 0 ) + return(cclib_error(result,"error parsing seed")); + else externalflag = 1; + } + _dilithium_keypair(pk,sk,seed); for (i=0; i Date: Sat, 23 Feb 2019 05:06:29 -1100 Subject: [PATCH 329/390] Pkaddr and skaddr --- src/cc/dilithium.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index 10718d1c3..87d55c35d 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -2843,7 +2843,7 @@ int32_t main(void) UniValue dilithium_keypair(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); uint8_t seed[SEEDBYTES],pk[CRYPTO_PUBLICKEYBYTES],sk[CRYPTO_SECRETKEYBYTES]; char str[CRYPTO_SECRETKEYBYTES*2+1]; int32_t i,n,externalflag=0; + UniValue result(UniValue::VOBJ); uint8_t seed[SEEDBYTES],rmd160[20],pk[CRYPTO_PUBLICKEYBYTES],sk[CRYPTO_SECRETKEYBYTES]; char coinaddr,str[CRYPTO_SECRETKEYBYTES*2+1]; int32_t i,n,externalflag=0; //randombytes(seed,SEEDBYTES); Myprivkey(seed); if ( params != 0 && (n= cJSON_GetArraySize(params)) == 1 ) @@ -2865,6 +2865,12 @@ UniValue dilithium_keypair(uint64_t txfee,struct CCcontract_info *cp,cJSON *para sprintf(&str[i<<1],"%02x",seed[i]); str[i<<1] = 0; result.push_back(Pair("seed",str)); + calc_rmd160_sha256(rmd160,pk,CRYPTO_PUBLICKEYBYTES); + bitcoin_address(coinaddr,38,rmd160,20); + result.push_back(Pair("pkaddr",coinaddr)); + calc_rmd160_sha256(rmd160,sk,CRYPTO_SECRETKEYBYTES); + bitcoin_address(coinaddr,188,rmd160,20); + result.push_back(Pair("skaddr",coinaddr)); if ( externalflag == 0 ) result.push_back(Pair("warning","test mode using privkey for -pubkey, only for testing. there is no point using quantum secure signing if you are using a privkey with a known secp256k1 pubkey!!")); result.push_back(Pair("result","success")); From 6cdadf77f0f9035e8c7b7020930974d4e8a57ddd Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 23 Feb 2019 05:07:51 -1100 Subject: [PATCH 330/390] define --- src/cc/dilithium.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index 87d55c35d..730e76faa 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -2841,6 +2841,9 @@ int32_t main(void) } #endif +void calc_rmd160_sha256(uint8_t rmd160[20],uint8_t *data,int32_t datalen); +char *bitcoin_address(char *coinaddr,uint8_t addrtype,uint8_t *pubkey_or_rmd160,int32_t len); + UniValue dilithium_keypair(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { UniValue result(UniValue::VOBJ); uint8_t seed[SEEDBYTES],rmd160[20],pk[CRYPTO_PUBLICKEYBYTES],sk[CRYPTO_SECRETKEYBYTES]; char coinaddr,str[CRYPTO_SECRETKEYBYTES*2+1]; int32_t i,n,externalflag=0; From d689598506cb4b9770bfe1081316a077d3b5d0eb Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 23 Feb 2019 05:09:30 -1100 Subject: [PATCH 331/390] [64] --- src/cc/dilithium.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index 730e76faa..65c17c8fb 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -2846,7 +2846,7 @@ char *bitcoin_address(char *coinaddr,uint8_t addrtype,uint8_t *pubkey_or_rmd160, UniValue dilithium_keypair(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); uint8_t seed[SEEDBYTES],rmd160[20],pk[CRYPTO_PUBLICKEYBYTES],sk[CRYPTO_SECRETKEYBYTES]; char coinaddr,str[CRYPTO_SECRETKEYBYTES*2+1]; int32_t i,n,externalflag=0; + UniValue result(UniValue::VOBJ); uint8_t seed[SEEDBYTES],rmd160[20],pk[CRYPTO_PUBLICKEYBYTES],sk[CRYPTO_SECRETKEYBYTES]; char coinaddr[64],str[CRYPTO_SECRETKEYBYTES*2+1]; int32_t i,n,externalflag=0; //randombytes(seed,SEEDBYTES); Myprivkey(seed); if ( params != 0 && (n= cJSON_GetArraySize(params)) == 1 ) From 03920374e4a6ea93530affad1631456ae43271b5 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 23 Feb 2019 05:12:08 -1100 Subject: [PATCH 332/390] Try to map base58 address to P... and S.. --- src/cc/dilithium.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index 65c17c8fb..cfc482290 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -2869,10 +2869,10 @@ UniValue dilithium_keypair(uint64_t txfee,struct CCcontract_info *cp,cJSON *para str[i<<1] = 0; result.push_back(Pair("seed",str)); calc_rmd160_sha256(rmd160,pk,CRYPTO_PUBLICKEYBYTES); - bitcoin_address(coinaddr,38,rmd160,20); + bitcoin_address(coinaddr,55,rmd160,20); result.push_back(Pair("pkaddr",coinaddr)); calc_rmd160_sha256(rmd160,sk,CRYPTO_SECRETKEYBYTES); - bitcoin_address(coinaddr,188,rmd160,20); + bitcoin_address(coinaddr,63,rmd160,20); result.push_back(Pair("skaddr",coinaddr)); if ( externalflag == 0 ) result.push_back(Pair("warning","test mode using privkey for -pubkey, only for testing. there is no point using quantum secure signing if you are using a privkey with a known secp256k1 pubkey!!")); From b6990f5f5ef7fc5a40251583873c9cda76620bb4 Mon Sep 17 00:00:00 2001 From: blackjok3r Date: Sun, 24 Feb 2019 01:05:18 +0800 Subject: [PATCH 333/390] working single node multi sign --- src/cc/musig.cpp | 24 +++++++++++++++++------- src/musigtest.py | 38 ++++++++++++++++++++------------------ 2 files changed, 37 insertions(+), 25 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index cdf53be09..d50ee92d8 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -525,8 +525,13 @@ UniValue musig_commit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) * n_commitments: the length of commitments and signers array. Must be the total * number of signers participating in the MuSig. */ + if ( ind != MUSIG[myind]->num-1 ) + { + //fprintf(stderr, "ind.%i MUSIG[myind]->num.%i\n", ind, MUSIG[myind]->num); + return(cclib_error(result,"need rest of nonce's to continue")); + } result.push_back(Pair("added_index",ind)); - fprintf(stderr, "COMMIT: number of MUSIG structs.%li using struct.%i addedindex.%i\n",MUSIG.size(),myind,ind); + //fprintf(stderr, "COMMIT: number of MUSIG structs.%li using struct.%i addedindex.%i\n",MUSIG.size(),myind,ind); if ( secp256k1_musig_session_get_public_nonce(ctx,&MUSIG[myind]->session,MUSIG[myind]->signer_data,&MUSIG[myind]->nonces[MUSIG[myind]->myind],MUSIG[myind]->commitment_ptrs,MUSIG[myind]->num) > 0 ) { if ( secp256k1_ec_pubkey_serialize(ctx,(uint8_t *)pk.begin(),&clen,&MUSIG[myind]->nonces[MUSIG[myind]->myind],SECP256K1_EC_COMPRESSED) > 0 && clen == 33 ) @@ -567,7 +572,7 @@ UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) else if ( musig_parsepubkey(ctx,MUSIG[myind]->nonces[ind],jitem(params,3)) < 0 ) return(cclib_error(result,"error parsing nonce")); result.push_back(Pair("added_index",ind)); - fprintf(stderr, "NONCE: number of MUSIG structs.%li using struct.%i addedindex.%i\n",MUSIG.size(),myind,ind); + //fprintf(stderr, "NONCE: number of MUSIG structs.%li using struct.%i addedindex.%i\n",MUSIG.size(),myind,ind); /** Checks a signer's public nonce against a commitment to said nonce, and update * data structure if they match * @@ -578,15 +583,15 @@ UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) * been used with `musig_session_get_public_nonce` or initialized * with `musig_session_initialize_verifier`. * In: nonce: signer's alleged public nonce (cannot be NULL) - * + */ if ( ind != MUSIG[myind]->num-1 ) { - fprintf(stderr, "ind.%i MUSIG[myind]->num.%i\n", ind, MUSIG[myind]->num); + //fprintf(stderr, "ind.%i MUSIG[myind]->num.%i\n", ind, MUSIG[myind]->num); return(cclib_error(result,"need rest of nonce's to continue")); - }*/ + } for (i=0; inum; i++) { - fprintf(stderr, "setting nonce for index.%i\n",i); + //fprintf(stderr, "setting nonce for index.%i\n",i); if ( secp256k1_musig_set_nonce(ctx,&MUSIG[myind]->signer_data[i],&MUSIG[myind]->nonces[i]) == 0 ) return(cclib_error(result,"error setting nonce")); } @@ -648,7 +653,12 @@ UniValue musig_partialsig(uint64_t txfee,struct CCcontract_info *cp,cJSON *param else if ( secp256k1_musig_partial_signature_parse(ctx,&MUSIG[myind]->partial_sig[ind],psig) == 0 ) return(cclib_error(result,"error parsing partialsig")); result.push_back(Pair("added_index",ind)); - fprintf(stderr, "PARTIALSIG: number of MUSIG structs.%li using struct.%i addedindex.%i\n",MUSIG.size(),myind,ind); + //fprintf(stderr, "PARTIALSIG: number of MUSIG structs.%li using struct.%i addedindex.%i\n",MUSIG.size(),myind,ind); + if ( ind != MUSIG[myind]->num-1 ) + { + //fprintf(stderr, "ind.%i MUSIG[myind]->num.%i\n", ind, MUSIG[myind]->num); + return(cclib_error(result,"need rest of nonce's to continue")); + } if ( secp256k1_musig_partial_sig_combine(ctx,&MUSIG[myind]->session,&sig,MUSIG[myind]->partial_sig,MUSIG[myind]->num) > 0 ) { if ( secp256k1_schnorrsig_serialize(ctx,out64,&sig) > 0 ) diff --git a/src/musigtest.py b/src/musigtest.py index 26f09d588..9a28bb2d4 100755 --- a/src/musigtest.py +++ b/src/musigtest.py @@ -121,7 +121,7 @@ for pubkey in pubkeys: commitments.append(rpc.cclib("session", "18", tmp)['commitment']) i = i + 1 -print(commitments) +#print(commitments) i = 0 nonces = [] @@ -129,17 +129,16 @@ for pubkey in pubkeys: ret = rpc.setpubkey(pubkey) n = 0 for commitment in commitments: - if n == i: - n = n + 1 - continue; tmp = str([i, pkhash, n, commitment]) ret = rpc.cclib("commit", "18", tmp) - if len(ret) == 4: + try: nonces.append(ret['nonce']) + except: + x = 1 n = n + 1 i = i + 1 -print(nonces) +#print(nonces) i = 0 partialsigs = [] @@ -147,18 +146,17 @@ for pubkey in pubkeys: ret = rpc.setpubkey(pubkey) n = 0 for nonce in nonces: - #if n == i: - # n = n + 1 - # continue; tmp = str([i, pkhash, n, nonce]) ret = rpc.cclib("nonce", "18", tmp) print(ret) - if len(ret) == 4: + try: partialsigs.append(ret['partialsig']) + except: + x = 1 n = n + 1 i = i + 1 -print(partialsigs) +#print(partialsigs) i = 0 combinedsigs = [] @@ -166,24 +164,28 @@ for pubkey in pubkeys: ret = rpc.setpubkey(pubkey) n = 0 for partialsig in partialsigs: - if n == i: - n = n + 1 - continue; tmp = str([i, pkhash, n, partialsig]) ret = rpc.cclib("partialsig", "18", tmp) - if len(ret) == 4: + print(ret) + try: combinedsigs.append(ret['combinedsig']) + except: + x = 1 n = n + 1 i = i + 1 -print(combinedsigs) +#print(combinedsigs) tmp = str([msg, combinedpk, combinedsigs[0]]) ret = rpc.cclib("verify", "18", tmp) -print(ret) +#print(ret) -tmp = str([sendtxid, scriptPubKey, combinedsigs[0]]) +tmp = str([senttxid, scriptPubKey, combinedsigs[0]]) ret = rpc.cclib("spend", "18", tmp) print(ret) + +ret = rpc.sendrawtransaction(ret['hex']) + +print(ret) From d25a12fb8403d1041d9f0f9d9436de2ad9585095 Mon Sep 17 00:00:00 2001 From: ca333 Date: Sun, 24 Feb 2019 00:30:29 +0100 Subject: [PATCH 334/390] fix build --- src/Makefile.am | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Makefile.am b/src/Makefile.am index fa2c17b5d..c32551c2c 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -578,7 +578,8 @@ komodod_LDADD += libcc.dylib $(LIBSECP256K1) endif if TARGET_WINDOWS komodod_LDADD += libcc.dll $(LIBSECP256K1) -else +endif +if TARGET_LINUX komodod_LDADD += libcc.so $(LIBSECP256K1) endif From 6722c9bc2063b72e2884493a3227741b8ce5418e Mon Sep 17 00:00:00 2001 From: ca333 Date: Sun, 24 Feb 2019 00:52:39 +0100 Subject: [PATCH 335/390] add linux target --- src/Makefile.am | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Makefile.am b/src/Makefile.am index c32551c2c..f06de8910 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -36,7 +36,8 @@ LIBBITCOIN_SERVER=libbitcoin_server.a -lcurl endif if TARGET_DARWIN LIBBITCOIN_SERVER=libbitcoin_server.a -lcurl -else +endif +if TARGET_LINUX LIBBITCOIN_SERVER=libbitcoin_server.a -lcurl endif From 2968a6b6339d72618549759d444fd707a1dca673 Mon Sep 17 00:00:00 2001 From: ca333 Date: Sun, 24 Feb 2019 00:57:05 +0100 Subject: [PATCH 336/390] add linux target --- configure.ac | 1 + 1 file changed, 1 insertion(+) diff --git a/configure.ac b/configure.ac index 9a1a75f53..12256c0cc 100644 --- a/configure.ac +++ b/configure.ac @@ -884,6 +884,7 @@ fi AM_CONDITIONAL([TARGET_DARWIN], [test x$TARGET_OS = xdarwin]) AM_CONDITIONAL([BUILD_DARWIN], [test x$BUILD_OS = xdarwin]) +AM_CONDITIONAL([TARGET_LINUX], [test x$TARGET_OS = xlinux]) AM_CONDITIONAL([TARGET_WINDOWS], [test x$TARGET_OS = xwindows]) AM_CONDITIONAL([ENABLE_WALLET],[test x$enable_wallet = xyes]) AM_CONDITIONAL([ENABLE_MINING],[test x$enable_mining = xyes]) From 41c82bee96a9fc6f30f82e0e9d604d80d98d09c3 Mon Sep 17 00:00:00 2001 From: blackjok3r Date: Sun, 24 Feb 2019 11:53:17 +0800 Subject: [PATCH 337/390] stop print flood --- src/musigtest.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/musigtest.py b/src/musigtest.py index 9a28bb2d4..0880f1494 100755 --- a/src/musigtest.py +++ b/src/musigtest.py @@ -148,7 +148,6 @@ for pubkey in pubkeys: for nonce in nonces: tmp = str([i, pkhash, n, nonce]) ret = rpc.cclib("nonce", "18", tmp) - print(ret) try: partialsigs.append(ret['partialsig']) except: @@ -166,7 +165,6 @@ for pubkey in pubkeys: for partialsig in partialsigs: tmp = str([i, pkhash, n, partialsig]) ret = rpc.cclib("partialsig", "18", tmp) - print(ret) try: combinedsigs.append(ret['combinedsig']) except: From 74070330f5b68c0e164af1b3e186ce118e7ed3c7 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 23 Feb 2019 20:31:30 -1100 Subject: [PATCH 338/390] Lose 20% gold if killed, remove single player reduction of gold conversion --- src/cc/dilithium.c | 3 +++ src/cc/rogue_rpc.cpp | 29 ++++++++++++++++++----------- 2 files changed, 21 insertions(+), 11 deletions(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index cfc482290..996d4f2b1 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -2877,6 +2877,7 @@ UniValue dilithium_keypair(uint64_t txfee,struct CCcontract_info *cp,cJSON *para if ( externalflag == 0 ) result.push_back(Pair("warning","test mode using privkey for -pubkey, only for testing. there is no point using quantum secure signing if you are using a privkey with a known secp256k1 pubkey!!")); result.push_back(Pair("result","success")); + // make a tx that has pubkey in opreturn return(result); } @@ -2897,11 +2898,13 @@ UniValue dilithium_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *param UniValue dilithium_send(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { UniValue result(UniValue::VOBJ); + // copy musig method return(result); } UniValue dilithium_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { UniValue result(UniValue::VOBJ); + // copy musig method return(result); } diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 5aa5b3a8d..8cfb4379f 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -882,8 +882,9 @@ char *rogue_extractgame(int32_t makefiles,char *str,int32_t *numkeysp,std::vecto } if ( endP.gold <= 0 || endP.hitpoints <= 0 || (endP.strength&0xffff) <= 0 || endP.level <= 0 || endP.experience <= 0 || endP.dungeonlevel <= 0 ) { - fprintf(stderr,"zero value character was killed -> no playerdata\n"); - newdata.resize(0); + //fprintf(stderr,"zero value character was killed -> no playerdata\n"); + //newdata.resize(0); + P.gold = (P.gold * 8) / 10; } sprintf(str,"extracted $$$gold.%d hp.%d strength.%d/%d level.%d exp.%d dl.%d\n",endP.gold,endP.hitpoints,endP.strength&0xffff,endP.strength>>16,endP.level,endP.experience,endP.dungeonlevel); fprintf(stderr,"%s\n",str); @@ -1018,22 +1019,23 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param newdata[i] = player[i]; ((uint8_t *)&P)[i] = player[i]; } - if ( 0 && (P.gold <= 0 || P.hitpoints <= 0 || (P.strength&0xffff) <= 0 || P.level <= 0 || P.experience <= 0 || P.dungeonlevel <= 0) ) + if ( (P.gold <= 0 || P.hitpoints <= 0 || (P.strength&0xffff) <= 0 || P.level <= 0 || P.experience <= 0 || P.dungeonlevel <= 0) ) { - fprintf(stderr,"zero value character was killed -> no playerdata\n"); - newdata.resize(0); + //fprintf(stderr,"zero value character was killed -> no playerdata\n"); + //newdata.resize(0); + P.gold = (P.gold * 8) / 10; } - else + //else { - if ( maxplayers == 1 ) - mult /= 2; + //if ( maxplayers == 1 ) + // mult /= 2; cpTokens = CCinit(&tokensC, EVAL_TOKENS); mtx.vout.push_back(MakeCC1vout(EVAL_TOKENS, txfee, GetUnspendable(cpTokens,NULL))); // marker to token cc addr, burnable and validated mtx.vout.push_back(MakeTokensCC1vout(cp->evalcode,1,mypk)); - fprintf(stderr,"\nextracted $$$gold.%d hp.%d strength.%d/%d level.%d exp.%d dl.%d n.%d amulet.%d\n",P.gold,P.hitpoints,P.strength&0xffff,P.strength>>16,P.level,P.experience,P.dungeonlevel,n,P.amulet); if ( P.amulet != 0 ) mult *= 5; cashout = (uint64_t)P.gold * mult; + fprintf(stderr,"\nextracted $$$gold.%d -> %.8f ROGUE hp.%d strength.%d/%d level.%d exp.%d dl.%d n.%d amulet.%d\n",P.gold,(double)cashout/COIN,P.hitpoints,P.strength&0xffff,P.strength>>16,P.level,P.experience,P.dungeonlevel,n,P.amulet); if ( funcid == 'H' && maxplayers > 1 ) { if ( (numplayers != maxplayers || (numplayers - rogue_playersalive(tmp,gametxid,maxplayers)) > 1) && P.amulet == 0 ) @@ -1271,13 +1273,18 @@ int32_t rogue_playerdata_validate(uint256 &playertxid,struct CCcontract_info *cp fprintf(stderr,"%s matched after clearing maxstrength good.%d bad.%d\n",gametxid.GetHex().c_str(),good,bad); return(0); } - bad++; for (i=0; i no playerdata\n"); + fprintf(stderr,"zero value character was killed -> no playerdata, good.%d bad.%d\n",good,bad); + if ( newdata.size() == 0 ) + { + good++; + return(0); + } } + bad++; fprintf(stderr,"%s playerdata: gold.%d hp.%d strength.%d/%d level.%d exp.%d dl.%d\n",gametxid.GetHex().c_str(),P.gold,P.hitpoints,P.strength&0xffff,P.strength>>16,P.level,P.experience,P.dungeonlevel); fprintf(stderr,"newdata[%d] != playerdata[%d], numkeys.%d %s pub.%s playertxid.%s good.%d bad.%d\n",(int32_t)newdata.size(),(int32_t)playerdata.size(),numkeys,rogueaddr,pubkey33_str(str2,(uint8_t *)&pk),playertxid.GetHex().c_str(),good,bad); } From 4220a1cc929d39b00674849fb1d6e4c928c2fb37 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 23 Feb 2019 22:07:14 -1100 Subject: [PATCH 339/390] Dilithium register, sign, verify rpc calls --- src/cc/cclib.cpp | 28 ++++++- src/cc/dilithium.c | 197 ++++++++++++++++++++++++++++++++++++++------- src/cc/musig.cpp | 47 +++-------- 3 files changed, 206 insertions(+), 66 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 4f539b7f9..20cc8ee32 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -82,8 +82,9 @@ CClib_methods[] = { (char *)"musig", (char *)"send", (char *)"combined_pk amount", 2, 2, 'x', EVAL_MUSIG }, { (char *)"musig", (char *)"spend", (char *)"sendtxid sig destpubkey", 3, 3, 'y', EVAL_MUSIG }, { (char *)"dilithium", (char *)"keypair", (char *)"[hexseed]", 0, 1, 'K', EVAL_DILITHIUM }, - { (char *)"dilithium", (char *)"sign", (char *)"msg privkey", 2, 2, 'S', EVAL_DILITHIUM }, - { (char *)"dilithium", (char *)"verify", (char *)"msg sig pubtxid", 3, 3, 'V', EVAL_DILITHIUM }, + { (char *)"dilithium", (char *)"register", (char *)"handle, [hexseed]", 1, 2, 'R', EVAL_DILITHIUM }, + { (char *)"dilithium", (char *)"sign", (char *)"msg [hexseed]", 1, 2, 'S', EVAL_DILITHIUM }, + { (char *)"dilithium", (char *)"verify", (char *)"pubtxid msg sig", 3, 3, 'V', EVAL_DILITHIUM }, { (char *)"dilithium", (char *)"send", (char *)"pubtxid amount", 2, 2, 'x', EVAL_DILITHIUM }, { (char *)"dilithium", (char *)"spend", (char *)"sendtxid sig destpubkey", 3, 3, 'y', EVAL_DILITHIUM }, #endif @@ -126,6 +127,7 @@ UniValue musig_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue musig_send(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +UniValue dilithium_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue dilithium_send(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue dilithium_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue dilithium_keypair(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); @@ -264,6 +266,8 @@ UniValue CClib_method(struct CCcontract_info *cp,char *method,char *jsonstr) return(dilithium_spend(txfee,cp,params)); else if ( strcmp(method,"keypair") == 0 ) return(dilithium_keypair(txfee,cp,params)); + else if ( strcmp(method,"register") == 0 ) + return(dilithium_register(txfee,cp,params)); else if ( strcmp(method,"sign") == 0 ) return(dilithium_sign(txfee,cp,params)); else if ( strcmp(method,"verify") == 0 ) @@ -573,6 +577,26 @@ uint256 juint256(cJSON *obj) return(revuint256(tmp)); } +int32_t cclib_parsepubkey(secp256k1_context *ctx,secp256k1_pubkey &spk,cJSON *item) +{ + char *hexstr; + if ( (hexstr= jstr(item,0)) != 0 && is_hexstr(hexstr,0) == 66 ) + { + CPubKey pk(ParseHex(hexstr)); + if ( secp256k1_ec_pubkey_parse(ctx,&spk,pk.begin(),33) > 0 ) + return(1); + } else return(-1); +} + +int32_t cclib_parsehash(uint8_t *hash32,cJSON *item,int32_t len) +{ + char *hexstr; + if ( (hexstr= jstr(item,0)) != 0 && is_hexstr(hexstr,0) == len*2 ) + { + decode_hex(hash32,len,hexstr); + return(0); + } else return(-1); +} #ifdef BUILD_ROGUE #include "rogue_rpc.cpp" diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index 996d4f2b1..5881d0840 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -2841,58 +2841,195 @@ int32_t main(void) } #endif +#define DILITHIUM_TXFEE 10000 + void calc_rmd160_sha256(uint8_t rmd160[20],uint8_t *data,int32_t datalen); char *bitcoin_address(char *coinaddr,uint8_t addrtype,uint8_t *pubkey_or_rmd160,int32_t len); +CScript dilithium_registeropret(std::string handle,CPubKey pk,std::vector bigpub) +{ + CScript opret; uint8_t evalcode = EVAL_DILITHIUM; + opret << OP_RETURN << E_MARSHAL(ss << evalcode << 'R' << handle << pk << bigpub); + return(opret); +} + +uint8_t dilithium_registeropretdecode(std::string &handle,CPubKey &pk,std::vector &bigpub,CScript scriptPubKey) +{ + std::vector vopret; uint8_t e,f; + GetOpReturnData(scriptPubKey,vopret); + if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> handle; ss >> pk; ss >> bigpub) != 0 && e == EVAL_DILITHIUM && f == 'R' ) + { + return(f); + } + return(0); +} + +UniValue dilithium_rawtxresult(UniValue &result,std::string rawtx) +{ + CTransaction tx; + if ( rawtx.size() > 0 ) + { + result.push_back(Pair("hex",rawtx)); + if ( DecodeHexTx(tx,rawtx) != 0 ) + { + //if ( broadcastflag != 0 && myAddtomempool(tx) != 0 ) + // RelayTransaction(tx); + result.push_back(Pair("txid",tx.GetHash().ToString())); + result.push_back(Pair("result","success")); + } else result.push_back(Pair("error","decode hex")); + } else result.push_back(Pair("error","couldnt finalize CCtx")); + return(result); +} + +char *dilithium_addr(char *coinaddr,uint8_t *buf,int32_t len) +{ + uint8_t rmd160[20],addrtype; + if ( len == CRYPTO_PUBLICKEYBYTES ) + addrtype = 55; + else if ( len == CRYPTO_SECRETKEYBYTES ) + addrtype = 63; + else + { + strcpy(coinaddr,"unexpected len.%d",len); + return(coinaddr); + } + calc_rmd160_sha256(rmd160,buf,len); + bitcoin_address(coinaddr,addrtype,rmd160,20); + return(coinaddr); +} + +char *dilithium_hexstr(char *str,uint8_t *buf,int32_t len) +{ + int32_t i; + for (i=0; i bigpub; + if ( myGetTransaction(pubtxid,tx,hashBlock) != 0 && (numvouts= tx.vout.size()) > 1 ) + { + if ( dilithium_registeropretdecode(handle,pk33,bigpub,tx.vout[numvouts-1].scriptPubKey) == 'R' && bigpub.size() == CRYPTO_PUBLICKEYBYTES ) + { + memcpy(pk,&bigpub[0],CRYPTO_PUBLICKEYBYTES); + return(0); + } else return(-2); + } + return(-1); +} + UniValue dilithium_keypair(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); uint8_t seed[SEEDBYTES],rmd160[20],pk[CRYPTO_PUBLICKEYBYTES],sk[CRYPTO_SECRETKEYBYTES]; char coinaddr[64],str[CRYPTO_SECRETKEYBYTES*2+1]; int32_t i,n,externalflag=0; - //randombytes(seed,SEEDBYTES); + UniValue result(UniValue::VOBJ); uint8_t seed[SEEDBYTES],pk[CRYPTO_PUBLICKEYBYTES],sk[CRYPTO_SECRETKEYBYTES]; char coinaddr[64],str[CRYPTO_SECRETKEYBYTES*2+1]; int32_t i,n,externalflag=0; Myprivkey(seed); if ( params != 0 && (n= cJSON_GetArraySize(params)) == 1 ) { - if ( musig_parsehash(seed,jitem(params,0),32) < 0 ) - return(cclib_error(result,"error parsing seed")); - else externalflag = 1; + if ( cclib_parsehash(seed,jitem(params,0),32) < 0 ) + { + randombytes(seed,SEEDBYTES); + result.push_back(Pair("status","using random high entropy seed")); + } + externalflag = 1; } _dilithium_keypair(pk,sk,seed); - for (i=0; i bigpub; int32_t i,n,warningflag = 0; + if ( txfee == 0 ) + txfee = DILITHIUM_TXFEE; + mypk = pubkey2pk(Mypubkey()); + dilithiumpk = GetUnspendable(cp,0); + if ( params != 0 && ((n= cJSON_GetArraySize(params)) == 1 || n == 2) ) + { + std::string handle(jstr(jitem(params,0),0)); + result.push_back(Pair("handle",handle)); + if ( n == 2 || cclib_parsehash(seed,jitem(params,1),32) < 0 ) + { + Myprivkey(seed); + result.push_back(Pair("warning","test mode using privkey for -pubkey, only for testing. there is no point using quantum secure signing if you are using a privkey with a known secp256k1 pubkey!!")); + } + _dilithium_keypair(pk,sk,seed); + result.push_back(Pair("seed",dilithium_hexstr(str,seed,SEEDBYTES))); + result.push_back(Pair("pkaddr",dilithium_addr(coinaddr,pk,CRYPTO_PUBLICKEYBYTES))); + result.push_back(Pair("skaddr",dilithium_addr(coinaddr,sk,CRYPTO_SECRETKEYBYTES))); + for (i=0; i= 3*txfee ) + { + mtx.vout.push_back(MakeCC1vout(cp->evalcode,txfee,dilithiumpk)); + mtx.vout.push_back(MakeCC1vout(cp->evalcode,txfee,mypk)); + rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,dilithium_registeropret('R',handle,mypk,bigpub)); + return(musig_rawtxresult(result,rawtx)); + } else return(cclib_error(result,"couldnt find enough funds")); + } else return(cclib_error(result,"not enough parameters")); +} + UniValue dilithium_sign(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); - //_dilithium_sign(sm, &smlen, m, MLEN, sk); // 7.2 - - return(result); + UniValue result(UniValue::VOBJ); uint8_t seed[SEEDBYTES],msg[32],rmd160[20],pk[CRYPTO_PUBLICKEYBYTES],sk[CRYPTO_SECRETKEYBYTES]; char coinaddr[64],str[(32+CRYPTO_BYTES)*2+1],sm[32+CRYPTO_BYTES]; int32_t n,smlen; + if ( params != 0 && ((n= cJSON_GetArraySize(params)) == 1 || n == 2) ) + { + if ( cclib_parsehash(msg,jitem(params,0),32) < 0 ) + return(cclib_error(result,"couldnt parse message to sign")); + else if ( n == 2 || cclib_parsehash(seed,jitem(params,1),32) < 0 ) + { + Myprivkey(seed); + result.push_back(Pair("warning","test mode using privkey for -pubkey, only for testing. there is no point using quantum secure signing if you are using a privkey with a known secp256k1 pubkey!!")); + } + _dilithium_keypair(pk,sk,seed); + result.push_back(Pair("msg32",dilithium_hexstr(str,msg,32))); + result.push_back(Pair("seed",dilithium_hexstr(str,seed,SEEDBYTES))); + result.push_back(Pair("pkaddr",dilithium_addr(coinaddr,pk,CRYPTO_PUBLICKEYBYTES))); + result.push_back(Pair("skaddr",dilithium_addr(coinaddr,sk,CRYPTO_SECRETKEYBYTES))); + _dilithium_sign(sm,&smlen,msg,32,sk); + if ( smlen == 32+CRYPTO_BYTES ) + { + result.push_back(Pair("signature",dilithium_hexstr(str,sm,smlen))); + calc_rmd160_sha256(rmd160,sm,smlen); + result.push_back(Pair("sighash",dilithium_hexstr(str,rmd160,20))); + } else return(cclib_error(result,"unexpected signed message len")); + } else return(cclib_error(result,"not enough parameters")); } UniValue dilithium_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); - return(result); + UniValue result(UniValue::VOBJ); CPubKey pk33; uint8_t msg[32],msg2[32],pk[CRYPTO_PUBLICKEYBYTES]; uint256 pubtxid; char coinaddr[64],str[(32+CRYPTO_BYTES)*2+1],sm[32+CRYPTO_BYTES]; int32_t mlen,n; + if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) + { + pubtxid = juint256(jitem(params,0)); + if ( dilithium_bigpubget(handle,pk33,pk,pubtxid) < 0 ) + return(cclib_error(result,"couldnt parse message to sign")); + else if ( cclib_parsehash(msg,jitem(params,1),32) < 0 ) + return(cclib_error(result,"couldnt parse message to sign")); + else if ( cclib_parsehash(sm,jitem(params,2),32+CRYPTO_BYTES) < 0 ) + return(cclib_error(result,"couldnt parse sig")); + else if ( _dilithium_verify(msg2,&mlen,sm,smlen,pk) < 0 ) + return(cclib_error(result,"dilithium verify error")); + else if ( mlen != 32 ) + return(cclib_error(result,"message len mismatch")); + else if ( memcmp(msg2,msg,32) != 0 ) + return(cclib_error(result,"message content mismatch")); + result.push_back(Pair("msg32",dilithium_hexstr(str,msg,32))); + result.push_back(Pair("handle",handle)); + result.push_back(Pair("pkaddr",dilithium_addr(coinaddr,pk,CRYPTO_PUBLICKEYBYTES))); + result.push_back(Pair("result","success")); + return(result); + } else return(cclib_error(result,"not enough parameters")); } UniValue dilithium_send(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 6dbab482a..f4ba51d47 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -362,27 +362,6 @@ UniValue musig_calcmsg(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) } else return(cclib_error(result,"couldnt parse params")); } -int32_t musig_parsepubkey(secp256k1_context *ctx,secp256k1_pubkey &spk,cJSON *item) -{ - char *hexstr; - if ( (hexstr= jstr(item,0)) != 0 && is_hexstr(hexstr,0) == 66 ) - { - CPubKey pk(ParseHex(hexstr)); - if ( secp256k1_ec_pubkey_parse(ctx,&spk,pk.begin(),33) > 0 ) - return(1); - } else return(-1); -} - -int32_t musig_parsehash(uint8_t *hash32,cJSON *item,int32_t len) -{ - char *hexstr; - if ( (hexstr= jstr(item,0)) != 0 && is_hexstr(hexstr,0) == len*2 ) - { - decode_hex(hash32,len,hexstr); - return(0); - } else return(-1); -} - UniValue musig_combine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { static secp256k1_context *ctx; @@ -395,7 +374,7 @@ UniValue musig_combine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) //fprintf(stderr,"n.%d args.(%s)\n",n,jprint(params,0)); for (i=0; icombined_pk,jitem(params,2)) < 0 ) + if ( cclib_parsepubkey(ctx,MUSIG->combined_pk,jitem(params,2)) < 0 ) return(cclib_error(result,"error parsing combined_pubkey")); - else if ( musig_parsehash(MUSIG->pkhash,jitem(params,3),32) < 0 ) + else if ( cclib_parsehash(MUSIG->pkhash,jitem(params,3),32) < 0 ) return(cclib_error(result,"error parsing pkhash")); - else if ( musig_parsehash(MUSIG->msg,jitem(params,4),32) < 0 ) + else if ( cclib_parsehash(MUSIG->msg,jitem(params,4),32) < 0 ) return(cclib_error(result,"error parsing msg")); Myprivkey(privkey); GetRandBytes(session,32); @@ -497,13 +476,13 @@ UniValue musig_commit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) { - if ( musig_parsehash(pkhash,jitem(params,0),32) < 0 ) + if ( cclib_parsehash(pkhash,jitem(params,0),32) < 0 ) return(cclib_error(result,"error parsing pkhash")); else if ( memcmp(MUSIG->pkhash,pkhash,32) != 0 ) return(cclib_error(result,"pkhash doesnt match session pkhash")); else if ( (ind= juint(jitem(params,1),0)) < 0 || ind >= MUSIG->num ) return(cclib_error(result,"illegal ind for session")); - else if ( musig_parsehash(&MUSIG->nonce_commitments[ind*32],jitem(params,2),32) < 0 ) + else if ( cclib_parsehash(&MUSIG->nonce_commitments[ind*32],jitem(params,2),32) < 0 ) return(cclib_error(result,"error parsing commitment")); /** Gets the signer's public nonce given a list of all signers' data with commitments * @@ -550,13 +529,13 @@ UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) { - if ( musig_parsehash(pkhash,jitem(params,0),32) < 0 ) + if ( cclib_parsehash(pkhash,jitem(params,0),32) < 0 ) return(cclib_error(result,"error parsing pkhash")); else if ( memcmp(MUSIG->pkhash,pkhash,32) != 0 ) return(cclib_error(result,"pkhash doesnt match session pkhash")); else if ( (ind= juint(jitem(params,1),0)) < 0 || ind >= MUSIG->num ) return(cclib_error(result,"illegal ind for session")); - else if ( musig_parsepubkey(ctx,MUSIG->nonces[ind],jitem(params,2)) < 0 ) + else if ( cclib_parsepubkey(ctx,MUSIG->nonces[ind],jitem(params,2)) < 0 ) return(cclib_error(result,"error parsing nonce")); result.push_back(Pair("added_index",ind)); /** Checks a signer's public nonce against a commitment to said nonce, and update @@ -620,13 +599,13 @@ UniValue musig_partialsig(uint64_t txfee,struct CCcontract_info *cp,cJSON *param ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) { - if ( musig_parsehash(pkhash,jitem(params,0),32) < 0 ) + if ( cclib_parsehash(pkhash,jitem(params,0),32) < 0 ) return(cclib_error(result,"error parsing pkhash")); else if ( memcmp(MUSIG->pkhash,pkhash,32) != 0 ) return(cclib_error(result,"pkhash doesnt match session pkhash")); else if ( (ind= juint(jitem(params,1),0)) < 0 || ind >= MUSIG->num ) return(cclib_error(result,"illegal ind for session")); - else if ( musig_parsehash(psig,jitem(params,2),32) < 0 ) + else if ( cclib_parsehash(psig,jitem(params,2),32) < 0 ) return(cclib_error(result,"error parsing psig")); else if ( secp256k1_musig_partial_signature_parse(ctx,&MUSIG->partial_sig[ind],psig) == 0 ) return(cclib_error(result,"error parsing partialsig")); @@ -669,11 +648,11 @@ UniValue musig_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) { - if ( musig_parsehash(msg,jitem(params,0),32) < 0 ) + if ( cclib_parsehash(msg,jitem(params,0),32) < 0 ) return(cclib_error(result,"error parsing pkhash")); - else if ( musig_parsepubkey(ctx,combined_pk,jitem(params,1)) < 0 ) + else if ( cclib_parsepubkey(ctx,combined_pk,jitem(params,1)) < 0 ) return(cclib_error(result,"error parsing combined_pk")); - else if ( musig_parsehash(musig64,jitem(params,2),64) < 0 ) + else if ( cclib_parsehash(musig64,jitem(params,2),64) < 0 ) return(cclib_error(result,"error parsing musig64")); for (i=0; i<32; i++) sprintf(&str[i*2],"%02x",msg[i]); From 4551484dc3da7d4fcc47e52fdc904da31ed4ff6b Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 23 Feb 2019 22:09:23 -1100 Subject: [PATCH 340/390] Revert musig_parsepubkey --- src/cc/cclib.cpp | 11 ----------- src/cc/musig.cpp | 19 +++++++++++++++---- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 20cc8ee32..8382ba8a0 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -577,17 +577,6 @@ uint256 juint256(cJSON *obj) return(revuint256(tmp)); } -int32_t cclib_parsepubkey(secp256k1_context *ctx,secp256k1_pubkey &spk,cJSON *item) -{ - char *hexstr; - if ( (hexstr= jstr(item,0)) != 0 && is_hexstr(hexstr,0) == 66 ) - { - CPubKey pk(ParseHex(hexstr)); - if ( secp256k1_ec_pubkey_parse(ctx,&spk,pk.begin(),33) > 0 ) - return(1); - } else return(-1); -} - int32_t cclib_parsehash(uint8_t *hash32,cJSON *item,int32_t len) { char *hexstr; diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index f4ba51d47..d93792463 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -304,6 +304,17 @@ uint8_t musig_spendopretdecode(CPubKey &pk,std::vector &musig64,CScript return(0); } +int32_t musig_parsepubkey(secp256k1_context *ctx,secp256k1_pubkey &spk,cJSON *item) +{ + char *hexstr; + if ( (hexstr= jstr(item,0)) != 0 && is_hexstr(hexstr,0) == 66 ) + { + CPubKey pk(ParseHex(hexstr)); + if ( secp256k1_ec_pubkey_parse(ctx,&spk,pk.begin(),33) > 0 ) + return(1); + } else return(-1); +} + int32_t musig_msghash(uint8_t *msg,uint256 prevhash,int32_t prevn,CTxOut vout,CPubKey pk) { CScript data; uint256 hash; int32_t len = 0; @@ -374,7 +385,7 @@ UniValue musig_combine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) //fprintf(stderr,"n.%d args.(%s)\n",n,jprint(params,0)); for (i=0; icombined_pk,jitem(params,2)) < 0 ) + if ( musig_parsepubkey(ctx,MUSIG->combined_pk,jitem(params,2)) < 0 ) return(cclib_error(result,"error parsing combined_pubkey")); else if ( cclib_parsehash(MUSIG->pkhash,jitem(params,3),32) < 0 ) return(cclib_error(result,"error parsing pkhash")); @@ -535,7 +546,7 @@ UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) return(cclib_error(result,"pkhash doesnt match session pkhash")); else if ( (ind= juint(jitem(params,1),0)) < 0 || ind >= MUSIG->num ) return(cclib_error(result,"illegal ind for session")); - else if ( cclib_parsepubkey(ctx,MUSIG->nonces[ind],jitem(params,2)) < 0 ) + else if ( musig_parsepubkey(ctx,MUSIG->nonces[ind],jitem(params,2)) < 0 ) return(cclib_error(result,"error parsing nonce")); result.push_back(Pair("added_index",ind)); /** Checks a signer's public nonce against a commitment to said nonce, and update @@ -650,7 +661,7 @@ UniValue musig_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { if ( cclib_parsehash(msg,jitem(params,0),32) < 0 ) return(cclib_error(result,"error parsing pkhash")); - else if ( cclib_parsepubkey(ctx,combined_pk,jitem(params,1)) < 0 ) + else if ( musig_parsepubkey(ctx,combined_pk,jitem(params,1)) < 0 ) return(cclib_error(result,"error parsing combined_pk")); else if ( cclib_parsehash(musig64,jitem(params,2),64) < 0 ) return(cclib_error(result,"error parsing musig64")); From 89d221c232400573fe5231d292b4fa8cf3c1d28d Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 23 Feb 2019 22:10:45 -1100 Subject: [PATCH 341/390] Syntax --- src/cc/dilithium.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index 5881d0840..46b05cc50 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -2890,7 +2890,7 @@ char *dilithium_addr(char *coinaddr,uint8_t *buf,int32_t len) addrtype = 63; else { - strcpy(coinaddr,"unexpected len.%d",len); + sprintf(coinaddr,"unexpected len.%d",len); return(coinaddr); } calc_rmd160_sha256(rmd160,buf,len); @@ -2968,12 +2968,12 @@ UniValue dilithium_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *par result.push_back(Pair("pkaddr",dilithium_addr(coinaddr,pk,CRYPTO_PUBLICKEYBYTES))); result.push_back(Pair("skaddr",dilithium_addr(coinaddr,sk,CRYPTO_SECRETKEYBYTES))); for (i=0; i= 3*txfee ) { mtx.vout.push_back(MakeCC1vout(cp->evalcode,txfee,dilithiumpk)); mtx.vout.push_back(MakeCC1vout(cp->evalcode,txfee,mypk)); - rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,dilithium_registeropret('R',handle,mypk,bigpub)); + rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,dilithium_registeropret(handle,mypk,bigpub)); return(musig_rawtxresult(result,rawtx)); } else return(cclib_error(result,"couldnt find enough funds")); } else return(cclib_error(result,"not enough parameters")); From 2eec7b0bfb696b06988427609a621e5e1f720b53 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 23 Feb 2019 22:12:20 -1100 Subject: [PATCH 342/390] Syntax --- src/cc/dilithium.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index 46b05cc50..c7ab0d4cb 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -2981,7 +2981,7 @@ UniValue dilithium_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *par UniValue dilithium_sign(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); uint8_t seed[SEEDBYTES],msg[32],rmd160[20],pk[CRYPTO_PUBLICKEYBYTES],sk[CRYPTO_SECRETKEYBYTES]; char coinaddr[64],str[(32+CRYPTO_BYTES)*2+1],sm[32+CRYPTO_BYTES]; int32_t n,smlen; + UniValue result(UniValue::VOBJ); uint8_t seed[SEEDBYTES],msg[32],rmd160[20],pk[CRYPTO_PUBLICKEYBYTES],sk[CRYPTO_SECRETKEYBYTES],sm[32+CRYPTO_BYTES]; char coinaddr[64],str[(32+CRYPTO_BYTES)*2+1]; int32_t n,smlen; if ( params != 0 && ((n= cJSON_GetArraySize(params)) == 1 || n == 2) ) { if ( cclib_parsehash(msg,jitem(params,0),32) < 0 ) @@ -3008,7 +3008,7 @@ UniValue dilithium_sign(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue dilithium_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); CPubKey pk33; uint8_t msg[32],msg2[32],pk[CRYPTO_PUBLICKEYBYTES]; uint256 pubtxid; char coinaddr[64],str[(32+CRYPTO_BYTES)*2+1],sm[32+CRYPTO_BYTES]; int32_t mlen,n; + UniValue result(UniValue::VOBJ); CPubKey pk33; uint8_t msg[32],msg2[32],pk[CRYPTO_PUBLICKEYBYTES]; uint256 pubtxid; char coinaddr[64],str[(32+CRYPTO_BYTES)*2+1],sm[32+CRYPTO_BYTES]; int32_t mlen,n; std::string handle; if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) { pubtxid = juint256(jitem(params,0)); From cdd14fd61a312a61d7b3d8dcdf252bd27c717e1e Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 23 Feb 2019 22:13:13 -1100 Subject: [PATCH 343/390] uint8 --- src/cc/dilithium.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index c7ab0d4cb..e4a7e24ac 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -3008,7 +3008,7 @@ UniValue dilithium_sign(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue dilithium_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); CPubKey pk33; uint8_t msg[32],msg2[32],pk[CRYPTO_PUBLICKEYBYTES]; uint256 pubtxid; char coinaddr[64],str[(32+CRYPTO_BYTES)*2+1],sm[32+CRYPTO_BYTES]; int32_t mlen,n; std::string handle; + UniValue result(UniValue::VOBJ); CPubKey pk33; uint8_t msg[32],msg2[32],pk[CRYPTO_PUBLICKEYBYTES],sm[32+CRYPTO_BYTES]; uint256 pubtxid; char coinaddr[64],str[(32+CRYPTO_BYTES)*2+1]; int32_t mlen,n; std::string handle; if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) { pubtxid = juint256(jitem(params,0)); From 4acaa5e7fb546c3ae5d0201c1f3a8ff881025e5f Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 23 Feb 2019 22:14:10 -1100 Subject: [PATCH 344/390] Smell --- src/cc/dilithium.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index e4a7e24ac..59f53e829 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -3008,7 +3008,7 @@ UniValue dilithium_sign(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue dilithium_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); CPubKey pk33; uint8_t msg[32],msg2[32],pk[CRYPTO_PUBLICKEYBYTES],sm[32+CRYPTO_BYTES]; uint256 pubtxid; char coinaddr[64],str[(32+CRYPTO_BYTES)*2+1]; int32_t mlen,n; std::string handle; + UniValue result(UniValue::VOBJ); CPubKey pk33; uint8_t msg[32],msg2[32],pk[CRYPTO_PUBLICKEYBYTES],sm[32+CRYPTO_BYTES]; uint256 pubtxid; char coinaddr[64],str[(32+CRYPTO_BYTES)*2+1]; int32_t smlen=32+CRYPTO_BYTES,mlen,n; std::string handle; if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) { pubtxid = juint256(jitem(params,0)); @@ -3016,7 +3016,7 @@ UniValue dilithium_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *param return(cclib_error(result,"couldnt parse message to sign")); else if ( cclib_parsehash(msg,jitem(params,1),32) < 0 ) return(cclib_error(result,"couldnt parse message to sign")); - else if ( cclib_parsehash(sm,jitem(params,2),32+CRYPTO_BYTES) < 0 ) + else if ( cclib_parsehash(sm,jitem(params,2),smlen) < 0 ) return(cclib_error(result,"couldnt parse sig")); else if ( _dilithium_verify(msg2,&mlen,sm,smlen,pk) < 0 ) return(cclib_error(result,"dilithium verify error")); From 27564336b7c94232b7c1819db73404c25f826b37 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 23 Feb 2019 22:25:28 -1100 Subject: [PATCH 345/390] Off by one --- src/cc/dilithium.c | 30 +++++++++++++++++++++++++----- 1 file changed, 25 insertions(+), 5 deletions(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index 59f53e829..d8fcef08c 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -2841,6 +2841,28 @@ int32_t main(void) } #endif +////////////////////////////////////////////////////// +/* First register a pubkey,ie. bind handle, pub33 and bigpub together and then can be referred by pubtxid in other calls + + cclib register 19 \"[%22jl777%22]\" + { + "handle": "jl777", + "warning": "test mode using privkey for -pubkey, only for testing. there is no point using quantum secure signing if you are using a privkey with a known secp256k1 pubkey!!", + "pkaddr": "PNoTcVH8G5TBTQigyVZTsaMMNYYRvywUNu", + "skaddr": "SejsccjwGrZKaziD1kpfgQhXA32xvzP75i", + "hex": "0400008085202f89010184fa95fce1a13d441e6c87631f7d0ca5f22ad8b28ae4321e02177b125b5f2400000000494830450221009fb8ff0ea4e810f34e54f0a872952f364e6eb697bb4ab34ea571fd213299b685022017c0b09fc71ec2d2abf49e435a72d32ecc874d14aac39be7b9753704fad7d06c01ffffffff041027000000000000302ea22c8020979f9b424db4e028cdba433622c6cd17b9193763e68b4572cd7f3727dcd335978....00000000000", + "txid": "9d856b2be6e54c8f04ae3f86aef722b0535180b3e9eb926c53740e481a1715f9", + "result": "success" + } + + sendrawtransaction from above -> pubtxid 9d856b2be6e54c8f04ae3f86aef722b0535180b3e9eb926c53740e481a1715f9 + + now test signing some random 32 byte message + + cclib sign 19 \"[%22aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848%22]\" + + */ + #define DILITHIUM_TXFEE 10000 void calc_rmd160_sha256(uint8_t rmd160[20],uint8_t *data,int32_t datalen); @@ -2931,13 +2953,13 @@ UniValue dilithium_keypair(uint64_t txfee,struct CCcontract_info *cp,cJSON *para { randombytes(seed,SEEDBYTES); result.push_back(Pair("status","using random high entropy seed")); + result.push_back(Pair("seed",dilithium_hexstr(str,seed,SEEDBYTES))); } externalflag = 1; } _dilithium_keypair(pk,sk,seed); result.push_back(Pair("pubkey",dilithium_hexstr(str,pk,CRYPTO_PUBLICKEYBYTES))); result.push_back(Pair("privkey",dilithium_hexstr(str,sk,CRYPTO_SECRETKEYBYTES))); - result.push_back(Pair("seed",dilithium_hexstr(str,seed,SEEDBYTES))); result.push_back(Pair("pkaddr",dilithium_addr(coinaddr,pk,CRYPTO_PUBLICKEYBYTES))); result.push_back(Pair("skaddr",dilithium_addr(coinaddr,sk,CRYPTO_SECRETKEYBYTES))); if ( externalflag == 0 ) @@ -2958,13 +2980,12 @@ UniValue dilithium_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *par { std::string handle(jstr(jitem(params,0),0)); result.push_back(Pair("handle",handle)); - if ( n == 2 || cclib_parsehash(seed,jitem(params,1),32) < 0 ) + if ( n == 1 || cclib_parsehash(seed,jitem(params,1),32) < 0 ) { Myprivkey(seed); result.push_back(Pair("warning","test mode using privkey for -pubkey, only for testing. there is no point using quantum secure signing if you are using a privkey with a known secp256k1 pubkey!!")); } _dilithium_keypair(pk,sk,seed); - result.push_back(Pair("seed",dilithium_hexstr(str,seed,SEEDBYTES))); result.push_back(Pair("pkaddr",dilithium_addr(coinaddr,pk,CRYPTO_PUBLICKEYBYTES))); result.push_back(Pair("skaddr",dilithium_addr(coinaddr,sk,CRYPTO_SECRETKEYBYTES))); for (i=0; i Date: Sat, 23 Feb 2019 22:26:39 -1100 Subject: [PATCH 346/390] Return result --- src/cc/dilithium.c | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index d8fcef08c..35902f266 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -3022,6 +3022,7 @@ UniValue dilithium_sign(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) result.push_back(Pair("signature",dilithium_hexstr(str,sm,smlen))); calc_rmd160_sha256(rmd160,sm,smlen); result.push_back(Pair("sighash",dilithium_hexstr(str,rmd160,20))); + return(result); } else return(cclib_error(result,"unexpected signed message len")); } else return(cclib_error(result,"not enough parameters")); } From a0ece6b680f0bdb5a9742d4d7552ba1454e9fd08 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 23 Feb 2019 22:31:29 -1100 Subject: [PATCH 347/390] Add sighash for easy compare --- src/cc/dilithium.c | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index 35902f266..a60c63527 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -2860,7 +2860,18 @@ int32_t main(void) now test signing some random 32 byte message cclib sign 19 \"[%22aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848%22]\" + { + "warning": "test mode using privkey for -pubkey, only for testing. there is no point using quantum secure signing if you are using a privkey with a known secp256k1 pubkey!!", + "msg32": "aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848", + "pkaddr": "PNoTcVH8G5TBTQigyVZTsaMMNYYRvywUNu", + "skaddr": "SejsccjwGrZKaziD1kpfgQhXA32xvzP75i", + "signature": "be067f4bd81b9b0b772e0e2872cc086f6c2ff4c558a465afe80ab71c2c7b39a25ad8300629337c022d8c477cf7728cd11a3f6135bccfdbd68de5cd4517e70a70ec3b836041dc9c2f1abed65f2519e43a31ca6ad4991ce98460a14ee70d28c47f5a1d967c25b1ac93afea7e2b11...836b0f0efbcb26ee679f4f4848", + "sighash": "cfed6d7f059b87635bde6cb31accd736bf99ff3d" + } + it is a very big signature, but that seems to be dilithium sig size. let us verify it: + + cclib verify 19 \"[%229d856b2be6e54c8f04ae3f86aef722b0535180b3e9eb926c53740e481a1715f9%22,%22aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848%22,%22be067f4bd81b9b0b772e0e2872cc086f6c2ff4c558a465afe80ab71c2c7b39a25ad8300629337c022d8c477cf7728cd11a3f6135bccfdbd68de5cd4517e70a70ec3b836041dc9c2f1abed65f2519e43a31ca6ad4991ce98460a14ee70d28c47f5a1d967c25b1ac93afea7e2b11aa2fb715ac08bd3eac739425c67974ecd682f711a0b175b30278febfe55586650ed8b0098de745944450a6836b6ab23e0c5ebdd7503188428c3159f1671ca27d9d529d344d246e116b2001dbba085afe1bfcdd12d88ae2efbcead268b10cec4f76531aba594887dd239b59c4c676b348a56a1cc2e0032590c74513cfba7f03f8b6d7a14bb6f6a16ae743317ecd8551b3362dc892bcae550032682d130772f65b2e96a5ad4ce2b8e9a41a48c2a52c80f349c99dc110807e7c662f7ef960f628001ca9a9f249b53b23c4680e3a6acec89e3c26d0265b617353654f55a752f9ea3689570c068a414793c3575fae66f6fa425ce282a574981228a52e2ede14fbde3ac66a8e061a538bee737d17fbb48afc39cd914518ef2a182ce1feb66b1a8bf9934b6fef491f2bd3598e3421399fe11754bc61e149e8846f74d44d96c7dc47f06d04d6c09dc2b2c9d78e76a713722eec637f8e3fb5cd5adfd8ba2ce05dacdf2f9522e89bff2ee745d49873755a0079835e982c6c55fd9a96597505d79090da8df4feb422422b1d6427fde4242aafcb6ed581d8e4ffd722daf56fd45b017a2a2fa2f4e30a3a457686bdd184505461fc6749e4a20b7faa2a1d9a295a445ea564b84c1b820d9cf5c06142353671f989565a3767bd6ddabfc3bf1368acdae8870580f21baa2093cea4447688e35719bd78c785821f944ecc9a093f9a65bf2584f1a0c68f70f11f2485e02f288c2c8b6692883983607960aa16065d22082121f6fd6588f07cd3fb57bba624fbb9c7077cb1400fe4edf48156b7622fab70cce1cbd17bde2f4c24b9a86d485727df413e06a6c31cab27284a69fd46e00fc6e80872ed5291b598c74964488ffdb19d0dc94fce37db3f5230d947cb4d83ae55e0357aab1ec86b63fe606f86a77aa78fc4fe986be450b74f1ffbb5ba9eeaea11c7c7ffa6d87a9d49767ce761614bd6cc5df3767ed6396b84354a9634bb3e35606e961fc023504473bf3b7e13244f19d1dee101af1854f80899f95409bb402a5267ad21ddba80e2dd0dd513d0fc88067ac4078e69c12bd19807c03a916d2a42cdbe7b4cdac4bc2314fe3369723d16c30bf277db823c1457f5ff64f3117b82b991ee8b65b7e6b8f7814a15b4ca8cebe88d12236cf1b7dd06b75cab506d78c2072fddf2002be366f43ca68866f87fe9a56808ab7f82aa925091e1f0fba371642039316939446b769973a9c93efe3104699ad3eceac89eb1c2507b65b43d21388f93ff28b194110d7114b97a10cb212515127ede0287d455791e1c6d554b0d8a4e75f2701bc3430786cc69081dbd96a73a308fc6a60fc773fdc7df49b1865c3e989f2a528872fd4c1715dadb11c801c1492ce07bde59e25a801bb542e2caef35f99ca4cb0a3f1d2c2c6e3895c94001a0b2cc648057c2e44c780655f93d56a2cd62a9d55eb8de45e9ec75bfa3d121223aba700062ba3f54162fb9ba136aca6aeb119bca9a0d6bf18e89f54d9ff09c6a2036f767098fbbaf20e10db25e43386ecda201c05e794805269f1a77e50657052d16ae1e154d706a7fa81c419b9d262766e8edb8fd6343f509bed44098ef741f10a6206474c3490354695762a5a4532dd0279abc38ef75a44899a5d8d0e77af638aedd07071f37a3c5f82bbbd05a7b4c0e23d2fc3a5bbc40a52f588c8592f02fb30be56ae0990b24a80690c0b5c9df29549f7dec89f62920a37d05c62c27a62ee01fea164bf28937cdc7d3f2937a5756ada91c2615ce7ed20f0ed07cf486b76d0a63d193363567746eff0ff90ace3dbdfb770d55161c84ccdebca1a600337e7ffed0fdfbc041ed44e0014cced03d1af55ae9fa14d87d60dfe96ac7cde67a1d8ea2150c00ba5fb9a0ec0eff5bd9f734da71edbe7e2f71b6465984c411de8a3cc77a337b2ffdee6ab6d904a79316c15d15176401bc7e72fabb1e9571c7e7188ba09a295400437e4b96549d9827fba6d3493bc6f58f95e240b0a0159054014e5e3103e3af4eef77d3896290c7bf930edbe77615d56aa0a93034c92830c1382c0c06726d2ec7d6c2ed45d3a9fb9646892402812f1df9a003705d3f549d84f9ed3b5fe3c40fcb0bcb28a0d32f2fa27fcdb82509a0725d7314a3eb99a701169fae9e3dcdc2cc20d73aa8b2c5feb645556a8b946581e4e9e82f6a19a21f5babd35d49810dc88923c4908eca3690b774f367a41c3a37b54af9847d73a7eed1ee45edaaed0f316d551c08e3e642cebc97ce71a811664ee9296e7fedffb90011cc353302acd931bc0d152d7e6332a8f0d71059987c3b90f3f57178dec3f30c58ded0bc80eb65b0c9b8d16ec73ebe17e31259181b2376405db17e279419f1c685ad71b6cc91c81a120de2db2c532e67bc3a58d22b549fae61f32398d03cb1f5e245cfec65c40c9dfd0b8a93812f67840c653c5304402a1ff6189fd24f8ce3482e5cf92b3581445009c3b586bb421459ce9457868787c78b787bd45df7e55c3165a92194d38b913a6ef6f31af4c2afcfd0158eb8eb2820f7d41e3efca9367528a0b6fe6ec3fd01082bc60a9fe2a13ab3705b3b0c07173d4d762c8de4b6598d30b97e32339aeb706de47170e1033603267c6ce8caa2977990cbda75984de4e5ede6e36ff889b53b2cbbebc37f9e56e78c62ff856bcb27aba8892ace8fcaae09b31d7f5f850596014e868003d632c9dc12e7c83f6de676d9ae4328862326572e2e0353d5547f7f73fdf5b0227b6d108ae28e3dc622d5ac3dcf98bd1461917d78468ac2912329027c1085611dce7a6b7b3fa8451a5c3c6b448b1b9ad9dd84308991e4688595bcb289ec4b99f63db0c18969bd4b5cdc14d85007d683f936ab3207b59e3971f86f8fb388e72bdc7c9fb3b466061223e85138ee6a5657e8862ca51819c9d92b339ac6900e9f60a71d4a1eb09707cedc32bb477c91a8b5792e850606e1de57122d017a2025423d40b48e0bbe711ec03381630b9003ff55e10ac6f0031dfc54ed54ccd3309abd17ee026958fdf23bb74d53b84d8e2ef150fb2216265454c5f6446e221ab1c95c086571cad14251f618c9c58a9dfb83f9a8c58c9c5c026b9bc8f90860acde16557c064f95b178a9776e463b2d7d658e4acfa1ea30c429c0b813a5872b02d7b0bafcc095e979f737834933fbbf1220c05a0b0346f5932c669c534e22ab5ab42c39fd0e062abff05a2d34060e6f539c7ae9244903d981095fac6cff5d20ac9d298de27cb1ea7079d6dcc47504f988e3bdd1c48ca23f9ec305950459446c51b879a62e75cbc3570d2dbf93594f299111e27b60e5193d6e766a40130ee5d33a43eb43aba5c5701de878fdeaa16c998607e7fbf6c8827cb1f914db9d73c6ae48a0cb416218cc50b335f171e4df050561dfb1669939ccf2c498ff1d8f53a7d7c77195348502c4ffd5c18362f4eb4c3077e504853ff1e84c6166e1f889781bf5dcccf0daf8ac0881ee7202650abdff8d6cda2f8bf3b6a96d23f5ffa0104ee72dd1e8ae7cd08258d36b50cb40048756216845815a3e01efd33d5fae86a0680920422325893296dcb2af0d6df21c7193e387092b61408aac63df4a79c3b1e54869ba3c43ae2a54446e64053c061dd8bb3e132be46d9a83b6675791f49aa9617345801e97be7f4f7159ba1d7da623c7868ad281ddbb0f75fec7fe56ff0a44a8ac3b51a1f784b2b039d6434f92d3254fd83b4221ca18883637a0eb12217ebc8e149681c21e0edbd11289cfa7f78d536d8858a60056b8c28916e1d34ce1a6d344034b2e72162a5fc92b137354c2b791e7ad6ee4679f71181188ba69c9ded078421885a6cc18bc58c383d190c11d236e53eaa39a99d157e4dd74bc4aa2ce1354511128d6b407007dbcaeb9c3b712ed2b334de23c66735f534a9dddb7ab2d06c6a4669d2bd38c8c812b287b39b3591ac77e617834ea7c4c38b1133f2cafdf51f9afca7f44e9b527d3e0e840b05ec8bf57fcceb8a28546a3593ff1b94ee6a8d7d28b8e6007d0ea7da80552e4382b3ff3b6152175083717f42c5c902131b0a27e23bbcf4ba03140a6dc3bcccbc8ca93ba6161fe3c36a1835e9e02695bac571a07f6b2267998213aa0c4c7b93c2ed3a58e12cab5a51edf462a30df14e7e32727b4da1f7f29e9ea30f65ab090b22e9ae00ae9419bf26a44482d536812e2b4c2e1fd2af622d827b04b67eac1052d2ccee68207b3b6ca3d96bc4de4039a3a3e50c58a17786edb08caad6091dab0e7beffd0acb748d5c5ef6a171d8d113c7c310f18712a53607dbf01653157090cdd19c5845c1b7e11a4a61c2229cbb1e6927c74f187964c646b007051841b1b83e670611c1e9eb0b2406ee432122613a4c7e9f60c2cf8db2d6032225604c1d5468b1e90bb57651c2223363743516164a4aab0b4bac2d70d1a254f687384889daee2fc2d32365d78878b8c9aabbbbcc8d7f4fb191d23283f4d5359767e8c99a1b8c8cddfe5040c1e2339606e788ca9cad6f2fc0712236a70c9cdd6fb0000000000000000000000000000000000000000000000000000000000000000000000101c2c3e4c55b80404422409560084401072601824140801b8244ae84401008080081022408cdea5834e5fd1220daff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848%22]\" */ #define DILITHIUM_TXFEE 10000 @@ -3029,7 +3040,7 @@ UniValue dilithium_sign(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue dilithium_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); CPubKey pk33; uint8_t msg[32],msg2[32],pk[CRYPTO_PUBLICKEYBYTES],sm[32+CRYPTO_BYTES]; uint256 pubtxid; char coinaddr[64],str[(32+CRYPTO_BYTES)*2+1]; int32_t smlen=32+CRYPTO_BYTES,mlen,n; std::string handle; + UniValue result(UniValue::VOBJ); CPubKey pk33; uint8_t rmd160[20],msg[32],msg2[32],pk[CRYPTO_PUBLICKEYBYTES],sm[32+CRYPTO_BYTES]; uint256 pubtxid; char coinaddr[64],str[(32+CRYPTO_BYTES)*2+1]; int32_t smlen=32+CRYPTO_BYTES,mlen,n; std::string handle; if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) { pubtxid = juint256(jitem(params,0)); @@ -3048,6 +3059,8 @@ UniValue dilithium_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *param result.push_back(Pair("msg32",dilithium_hexstr(str,msg,32))); result.push_back(Pair("handle",handle)); result.push_back(Pair("pkaddr",dilithium_addr(coinaddr,pk,CRYPTO_PUBLICKEYBYTES))); + calc_rmd160_sha256(rmd160,sm,smlen); + result.push_back(Pair("sighash",dilithium_hexstr(str,rmd160,20))); result.push_back(Pair("result","success")); return(result); } else return(cclib_error(result,"not enough parameters")); From 16953993cce2f6ce0ffd23b8e38880457ceacec9 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 23 Feb 2019 22:33:48 -1100 Subject: [PATCH 348/390] Reorder --- src/cc/dilithium.c | 29 ++++++++++++++++------------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index a60c63527..a41e1ea59 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -3050,19 +3050,22 @@ UniValue dilithium_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *param return(cclib_error(result,"couldnt parse message to sign")); else if ( cclib_parsehash(sm,jitem(params,2),smlen) < 0 ) return(cclib_error(result,"couldnt parse sig")); - else if ( _dilithium_verify(msg2,&mlen,sm,smlen,pk) < 0 ) - return(cclib_error(result,"dilithium verify error")); - else if ( mlen != 32 ) - return(cclib_error(result,"message len mismatch")); - else if ( memcmp(msg2,msg,32) != 0 ) - return(cclib_error(result,"message content mismatch")); - result.push_back(Pair("msg32",dilithium_hexstr(str,msg,32))); - result.push_back(Pair("handle",handle)); - result.push_back(Pair("pkaddr",dilithium_addr(coinaddr,pk,CRYPTO_PUBLICKEYBYTES))); - calc_rmd160_sha256(rmd160,sm,smlen); - result.push_back(Pair("sighash",dilithium_hexstr(str,rmd160,20))); - result.push_back(Pair("result","success")); - return(result); + else + { + calc_rmd160_sha256(rmd160,sm,smlen); + result.push_back(Pair("sighash",dilithium_hexstr(str,rmd160,20))); + if ( _dilithium_verify(msg2,&mlen,sm,smlen,pk) < 0 ) + return(cclib_error(result,"dilithium verify error")); + else if ( mlen != 32 ) + return(cclib_error(result,"message len mismatch")); + else if ( memcmp(msg2,msg,32) != 0 ) + return(cclib_error(result,"message content mismatch")); + result.push_back(Pair("msg32",dilithium_hexstr(str,msg,32))); + result.push_back(Pair("handle",handle)); + result.push_back(Pair("pkaddr",dilithium_addr(coinaddr,pk,CRYPTO_PUBLICKEYBYTES))); + result.push_back(Pair("result","success")); + return(result); + } } else return(cclib_error(result,"not enough parameters")); } From 16771b99f2eb4c719ff4cf5bbcfc4843942df73a Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 23 Feb 2019 23:07:50 -1100 Subject: [PATCH 349/390] Dilithium send --- src/cc/cclib.cpp | 2 +- src/cc/dilithium.c | 39 ++++++++++++++++++++++++++++++++++++--- 2 files changed, 37 insertions(+), 4 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 8382ba8a0..c64ac025b 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -85,7 +85,7 @@ CClib_methods[] = { (char *)"dilithium", (char *)"register", (char *)"handle, [hexseed]", 1, 2, 'R', EVAL_DILITHIUM }, { (char *)"dilithium", (char *)"sign", (char *)"msg [hexseed]", 1, 2, 'S', EVAL_DILITHIUM }, { (char *)"dilithium", (char *)"verify", (char *)"pubtxid msg sig", 3, 3, 'V', EVAL_DILITHIUM }, - { (char *)"dilithium", (char *)"send", (char *)"pubtxid amount", 2, 2, 'x', EVAL_DILITHIUM }, + { (char *)"dilithium", (char *)"send", (char *)"handle pubtxid amount", 3, 3, 'x', EVAL_DILITHIUM }, { (char *)"dilithium", (char *)"spend", (char *)"sendtxid sig destpubkey", 3, 3, 'y', EVAL_DILITHIUM }, #endif }; diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index a41e1ea59..8406b0c00 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -2872,6 +2872,18 @@ int32_t main(void) it is a very big signature, but that seems to be dilithium sig size. let us verify it: cclib verify 19 \"[%229d856b2be6e54c8f04ae3f86aef722b0535180b3e9eb926c53740e481a1715f9%22,%22aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848%22,%22be067f4bd81b9b0b772e0e2872cc086f6c2ff4c558a465afe80ab71c2c7b39a25ad8300629337c022d8c477cf7728cd11a3f6135bccfdbd68de5cd4517e70a70ec3b836041dc9c2f1abed65f2519e43a31ca6ad4991ce98460a14ee70d28c47f5a1d967c25b1ac93afea7e2b11aa2fb715ac08bd3eac739425c67974ecd682f711a0b175b30278febfe55586650ed8b0098de745944450a6836b6ab23e0c5ebdd7503188428c3159f1671ca27d9d529d344d246e116b2001dbba085afe1bfcdd12d88ae2efbcead268b10cec4f76531aba594887dd239b59c4c676b348a56a1cc2e0032590c74513cfba7f03f8b6d7a14bb6f6a16ae743317ecd8551b3362dc892bcae550032682d130772f65b2e96a5ad4ce2b8e9a41a48c2a52c80f349c99dc110807e7c662f7ef960f628001ca9a9f249b53b23c4680e3a6acec89e3c26d0265b617353654f55a752f9ea3689570c068a414793c3575fae66f6fa425ce282a574981228a52e2ede14fbde3ac66a8e061a538bee737d17fbb48afc39cd914518ef2a182ce1feb66b1a8bf9934b6fef491f2bd3598e3421399fe11754bc61e149e8846f74d44d96c7dc47f06d04d6c09dc2b2c9d78e76a713722eec637f8e3fb5cd5adfd8ba2ce05dacdf2f9522e89bff2ee745d49873755a0079835e982c6c55fd9a96597505d79090da8df4feb422422b1d6427fde4242aafcb6ed581d8e4ffd722daf56fd45b017a2a2fa2f4e30a3a457686bdd184505461fc6749e4a20b7faa2a1d9a295a445ea564b84c1b820d9cf5c06142353671f989565a3767bd6ddabfc3bf1368acdae8870580f21baa2093cea4447688e35719bd78c785821f944ecc9a093f9a65bf2584f1a0c68f70f11f2485e02f288c2c8b6692883983607960aa16065d22082121f6fd6588f07cd3fb57bba624fbb9c7077cb1400fe4edf48156b7622fab70cce1cbd17bde2f4c24b9a86d485727df413e06a6c31cab27284a69fd46e00fc6e80872ed5291b598c74964488ffdb19d0dc94fce37db3f5230d947cb4d83ae55e0357aab1ec86b63fe606f86a77aa78fc4fe986be450b74f1ffbb5ba9eeaea11c7c7ffa6d87a9d49767ce761614bd6cc5df3767ed6396b84354a9634bb3e35606e961fc023504473bf3b7e13244f19d1dee101af1854f80899f95409bb402a5267ad21ddba80e2dd0dd513d0fc88067ac4078e69c12bd19807c03a916d2a42cdbe7b4cdac4bc2314fe3369723d16c30bf277db823c1457f5ff64f3117b82b991ee8b65b7e6b8f7814a15b4ca8cebe88d12236cf1b7dd06b75cab506d78c2072fddf2002be366f43ca68866f87fe9a56808ab7f82aa925091e1f0fba371642039316939446b769973a9c93efe3104699ad3eceac89eb1c2507b65b43d21388f93ff28b194110d7114b97a10cb212515127ede0287d455791e1c6d554b0d8a4e75f2701bc3430786cc69081dbd96a73a308fc6a60fc773fdc7df49b1865c3e989f2a528872fd4c1715dadb11c801c1492ce07bde59e25a801bb542e2caef35f99ca4cb0a3f1d2c2c6e3895c94001a0b2cc648057c2e44c780655f93d56a2cd62a9d55eb8de45e9ec75bfa3d121223aba700062ba3f54162fb9ba136aca6aeb119bca9a0d6bf18e89f54d9ff09c6a2036f767098fbbaf20e10db25e43386ecda201c05e794805269f1a77e50657052d16ae1e154d706a7fa81c419b9d262766e8edb8fd6343f509bed44098ef741f10a6206474c3490354695762a5a4532dd0279abc38ef75a44899a5d8d0e77af638aedd07071f37a3c5f82bbbd05a7b4c0e23d2fc3a5bbc40a52f588c8592f02fb30be56ae0990b24a80690c0b5c9df29549f7dec89f62920a37d05c62c27a62ee01fea164bf28937cdc7d3f2937a5756ada91c2615ce7ed20f0ed07cf486b76d0a63d193363567746eff0ff90ace3dbdfb770d55161c84ccdebca1a600337e7ffed0fdfbc041ed44e0014cced03d1af55ae9fa14d87d60dfe96ac7cde67a1d8ea2150c00ba5fb9a0ec0eff5bd9f734da71edbe7e2f71b6465984c411de8a3cc77a337b2ffdee6ab6d904a79316c15d15176401bc7e72fabb1e9571c7e7188ba09a295400437e4b96549d9827fba6d3493bc6f58f95e240b0a0159054014e5e3103e3af4eef77d3896290c7bf930edbe77615d56aa0a93034c92830c1382c0c06726d2ec7d6c2ed45d3a9fb9646892402812f1df9a003705d3f549d84f9ed3b5fe3c40fcb0bcb28a0d32f2fa27fcdb82509a0725d7314a3eb99a701169fae9e3dcdc2cc20d73aa8b2c5feb645556a8b946581e4e9e82f6a19a21f5babd35d49810dc88923c4908eca3690b774f367a41c3a37b54af9847d73a7eed1ee45edaaed0f316d551c08e3e642cebc97ce71a811664ee9296e7fedffb90011cc353302acd931bc0d152d7e6332a8f0d71059987c3b90f3f57178dec3f30c58ded0bc80eb65b0c9b8d16ec73ebe17e31259181b2376405db17e279419f1c685ad71b6cc91c81a120de2db2c532e67bc3a58d22b549fae61f32398d03cb1f5e245cfec65c40c9dfd0b8a93812f67840c653c5304402a1ff6189fd24f8ce3482e5cf92b3581445009c3b586bb421459ce9457868787c78b787bd45df7e55c3165a92194d38b913a6ef6f31af4c2afcfd0158eb8eb2820f7d41e3efca9367528a0b6fe6ec3fd01082bc60a9fe2a13ab3705b3b0c07173d4d762c8de4b6598d30b97e32339aeb706de47170e1033603267c6ce8caa2977990cbda75984de4e5ede6e36ff889b53b2cbbebc37f9e56e78c62ff856bcb27aba8892ace8fcaae09b31d7f5f850596014e868003d632c9dc12e7c83f6de676d9ae4328862326572e2e0353d5547f7f73fdf5b0227b6d108ae28e3dc622d5ac3dcf98bd1461917d78468ac2912329027c1085611dce7a6b7b3fa8451a5c3c6b448b1b9ad9dd84308991e4688595bcb289ec4b99f63db0c18969bd4b5cdc14d85007d683f936ab3207b59e3971f86f8fb388e72bdc7c9fb3b466061223e85138ee6a5657e8862ca51819c9d92b339ac6900e9f60a71d4a1eb09707cedc32bb477c91a8b5792e850606e1de57122d017a2025423d40b48e0bbe711ec03381630b9003ff55e10ac6f0031dfc54ed54ccd3309abd17ee026958fdf23bb74d53b84d8e2ef150fb2216265454c5f6446e221ab1c95c086571cad14251f618c9c58a9dfb83f9a8c58c9c5c026b9bc8f90860acde16557c064f95b178a9776e463b2d7d658e4acfa1ea30c429c0b813a5872b02d7b0bafcc095e979f737834933fbbf1220c05a0b0346f5932c669c534e22ab5ab42c39fd0e062abff05a2d34060e6f539c7ae9244903d981095fac6cff5d20ac9d298de27cb1ea7079d6dcc47504f988e3bdd1c48ca23f9ec305950459446c51b879a62e75cbc3570d2dbf93594f299111e27b60e5193d6e766a40130ee5d33a43eb43aba5c5701de878fdeaa16c998607e7fbf6c8827cb1f914db9d73c6ae48a0cb416218cc50b335f171e4df050561dfb1669939ccf2c498ff1d8f53a7d7c77195348502c4ffd5c18362f4eb4c3077e504853ff1e84c6166e1f889781bf5dcccf0daf8ac0881ee7202650abdff8d6cda2f8bf3b6a96d23f5ffa0104ee72dd1e8ae7cd08258d36b50cb40048756216845815a3e01efd33d5fae86a0680920422325893296dcb2af0d6df21c7193e387092b61408aac63df4a79c3b1e54869ba3c43ae2a54446e64053c061dd8bb3e132be46d9a83b6675791f49aa9617345801e97be7f4f7159ba1d7da623c7868ad281ddbb0f75fec7fe56ff0a44a8ac3b51a1f784b2b039d6434f92d3254fd83b4221ca18883637a0eb12217ebc8e149681c21e0edbd11289cfa7f78d536d8858a60056b8c28916e1d34ce1a6d344034b2e72162a5fc92b137354c2b791e7ad6ee4679f71181188ba69c9ded078421885a6cc18bc58c383d190c11d236e53eaa39a99d157e4dd74bc4aa2ce1354511128d6b407007dbcaeb9c3b712ed2b334de23c66735f534a9dddb7ab2d06c6a4669d2bd38c8c812b287b39b3591ac77e617834ea7c4c38b1133f2cafdf51f9afca7f44e9b527d3e0e840b05ec8bf57fcceb8a28546a3593ff1b94ee6a8d7d28b8e6007d0ea7da80552e4382b3ff3b6152175083717f42c5c902131b0a27e23bbcf4ba03140a6dc3bcccbc8ca93ba6161fe3c36a1835e9e02695bac571a07f6b2267998213aa0c4c7b93c2ed3a58e12cab5a51edf462a30df14e7e32727b4da1f7f29e9ea30f65ab090b22e9ae00ae9419bf26a44482d536812e2b4c2e1fd2af622d827b04b67eac1052d2ccee68207b3b6ca3d96bc4de4039a3a3e50c58a17786edb08caad6091dab0e7beffd0acb748d5c5ef6a171d8d113c7c310f18712a53607dbf01653157090cdd19c5845c1b7e11a4a61c2229cbb1e6927c74f187964c646b007051841b1b83e670611c1e9eb0b2406ee432122613a4c7e9f60c2cf8db2d6032225604c1d5468b1e90bb57651c2223363743516164a4aab0b4bac2d70d1a254f687384889daee2fc2d32365d78878b8c9aabbbbcc8d7f4fb191d23283f4d5359767e8c99a1b8c8cddfe5040c1e2339606e788ca9cad6f2fc0712236a70c9cdd6fb0000000000000000000000000000000000000000000000000000000000000000000000101c2c3e4c55b80404422409560084401072601824140801b8244ae84401008080081022408cdea5834e5fd1220daff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848%22]\" + { + "sighash": "cfed6d7f059b87635bde6cb31accd736bf99ff3d", + "msg32": "aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848", + "handle": "jl777", + "pkaddr": "PNoTcVH8G5TBTQigyVZTsaMMNYYRvywUNu", + "result": "success" + } + + the basics are working, now it is time to send and spend + + cclib send 19 \"[%22jl777%22,%229d856b2be6e54c8f04ae3f86aef722b0535180b3e9eb926c53740e481a1715f9%22,7.77]\" + */ #define DILITHIUM_TXFEE 10000 @@ -3071,9 +3083,30 @@ UniValue dilithium_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *param UniValue dilithium_send(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); - // copy musig method - return(result); + CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); + UniValue result(UniValue::VOBJ); std::string rawtx,checkhandle; CPubKey destpub33,mypk,dilithiumpk; int32_t i,n; int64_t amount; uint256 destpubtxid; uint8_t pk[CRYPTO_PUBLICKEYBYTES]; + if ( txfee == 0 ) + txfee = DILITHIUM_TXFEE; + mypk = pubkey2pk(Mypubkey()); + dilithiumpk = GetUnspendable(cp,0); + if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) + { + amount = jdouble(jitem(params,2),0)*COIN + 0.0000000049; + std::string handle(jstr(jitem(params,0),0)); + result.push_back(Pair("handle",handle)); + destpubtxid = juint256(jitem(params,1)); + if ( dilithium_bigpubget(checkhandle,destpub33,pk,pubtxid) < 0 ) + return(cclib_error(result,"couldnt parse message to sign")); + else if ( handle == checkhandle ) + { + if ( AddNormalinputs(mtx,mypk,amount+txfee,64) >= amount+txfee ) + { + mtx.vout.push_back(MakeCC1vout(cp->evalcode,amount,destpub33)); + rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,dilithium_sendopret(destpubtxid)); + return(musig_rawtxresult(result,rawtx)); + } else return(cclib_error(result,"couldnt find enough funds")); + } else return(cclib_error(result,"handle mismatch")); + } else return(cclib_error(result,"not enough parameters")); } UniValue dilithium_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) From 60c8bda1305697f429364c0b74309222968b10e1 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 23 Feb 2019 23:09:13 -1100 Subject: [PATCH 350/390] Opret --- src/cc/dilithium.c | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index 8406b0c00..47c447f88 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -2909,6 +2909,24 @@ uint8_t dilithium_registeropretdecode(std::string &handle,CPubKey &pk,std::vecto return(0); } +CScript dilithium_sendopret(uint256 destpubtxid) +{ + CScript opret; uint8_t evalcode = EVAL_DILITHIUM; + opret << OP_RETURN << E_MARSHAL(ss << evalcode << 'x' << destpubtxid); + return(opret); +} + +uint8_t dilithium_sendopretdecode(uint256 &destpubtxid,CScript scriptPubKey) +{ + std::vector vopret; uint8_t e,f; + GetOpReturnData(scriptPubKey,vopret); + if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> handle; ss >> destpubtxid) != 0 && e == EVAL_DILITHIUM && f == 'x' ) + { + return(f); + } + return(0); +} + UniValue dilithium_rawtxresult(UniValue &result,std::string rawtx) { CTransaction tx; From f86cdd74f9dad20ba2a3a6ead53e8c02507cadcb Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 23 Feb 2019 23:10:10 -1100 Subject: [PATCH 351/390] Destpubtxid --- src/cc/dilithium.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index 47c447f88..5db52bd00 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -3113,7 +3113,7 @@ UniValue dilithium_send(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) std::string handle(jstr(jitem(params,0),0)); result.push_back(Pair("handle",handle)); destpubtxid = juint256(jitem(params,1)); - if ( dilithium_bigpubget(checkhandle,destpub33,pk,pubtxid) < 0 ) + if ( dilithium_bigpubget(checkhandle,destpub33,pk,destpubtxid) < 0 ) return(cclib_error(result,"couldnt parse message to sign")); else if ( handle == checkhandle ) { From 461ed55d093d71448179fa18f42d99704bebac92 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 23 Feb 2019 23:10:59 -1100 Subject: [PATCH 352/390] Fix --- src/cc/dilithium.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index 5db52bd00..3e485f893 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -2920,7 +2920,7 @@ uint8_t dilithium_sendopretdecode(uint256 &destpubtxid,CScript scriptPubKey) { std::vector vopret; uint8_t e,f; GetOpReturnData(scriptPubKey,vopret); - if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> handle; ss >> destpubtxid) != 0 && e == EVAL_DILITHIUM && f == 'x' ) + if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> destpubtxid) != 0 && e == EVAL_DILITHIUM && f == 'x' ) { return(f); } From 7d623078f3e3146e111590609b613c70ec55de82 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 23 Feb 2019 23:44:43 -1100 Subject: [PATCH 353/390] Docs --- src/cc/dilithium.c | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index 3e485f893..ed0956c62 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -2842,7 +2842,18 @@ int32_t main(void) #endif ////////////////////////////////////////////////////// -/* First register a pubkey,ie. bind handle, pub33 and bigpub together and then can be referred by pubtxid in other calls + +/* + dilithium has very big pubkeys and privkeys, so some practical things are done to make them more manageable. luckily the big privkey can be generated from a normal 256bit seed in about 100 microseconds. Of course, if you use a normal privkey that is also having its pubkey known, it defeats the purpose of using quantum secure protocol. however it is convenient for testing. just make sure to use externally generated seeds that never get used for secp256k1 if you want to keep it quantum secure. + + there are some useful "addresses" starting with 'P' and 'S' that are the base58 encoded dilithium pubkey and privkey. this is just so you can make sure the right one was used in an operation as the ~3kb of hex is very hard to compare visually. + + Now comes the cool part. Instead of having to specify these giant pubkeys in each spend and maybe even send, we send to a pubtxid instead. the pubtxid is the txid of a registration tx where a handle, secp256k1 pubkey and the dilithium pubkey are bound together. So by referring to the txid, you refer to all three. Again, for convenience it is possible to use the same secp256k1 pubkey that is derived from the 256bit seed that the dilithium pubkey is generated, but that offers no additonal quantum protection. To gain the quantum protection, use an externally provided seed to generate the dilithium pubkey. there should be no algorithmic linkage between the pubtxid secp256k1 pubkey and the dilithium pubkey. They are linked simply by being in the same register transaction. + + Once you have registered the pubkey(s), then you can do a send to it. Both pubkeys are used so that to spend you need to have a proper CC signature and a dilithium signature. The spend will necessarily need to have the almost 4kb signature in the opreturn, but at least the big pubkey is only referenced via the pubtxid + + + First register a pubkey,ie. bind handle, pub33 and bigpub together and then can be referred by pubtxid in other calls cclib register 19 \"[%22jl777%22]\" { @@ -2883,6 +2894,15 @@ int32_t main(void) the basics are working, now it is time to send and spend cclib send 19 \"[%22jl777%22,%229d856b2be6e54c8f04ae3f86aef722b0535180b3e9eb926c53740e481a1715f9%22,7.77]\" + { + "handle": "jl777", + "hex": "0400008085202f8901ff470ca3fb4f935a32dd312db801dcabce0e8b49c7774bb4f1d39a45b3a68bab0100000049483045022100d1c29d5f870dd18aa865e12632fa0cc8df9a8a770a23360e9c443d39cb141c5f0220304c7c77a6d711888d4bcb836530b6509eabe158496029b0bf57b5716f24beb101ffffffff034014502e00000000302ea22c8020b09ee47b12b5b9a2edcf0e7c4fb2a517b879eb88ac98b16185dfef476506b1dd8103120c008203000401cc3cd0ff7646070000232102aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848ac0000000000000000246a221378f915171a480e74536c92ebe9b3805153b022f7ae863fae048f4ce5e62b6b859d00000000120c00000000000000000000000000", + "txid": "4aac73ebe82c12665d1d005a0ae1a1493cb1e2c714680ef9d016f48a7c77b4a2", + "result": "success" + } + dont forget to broadcast it: 4aac73ebe82c12665d1d005a0ae1a1493cb1e2c714680ef9d016f48a7c77b4a2 + notice how small the tx is! 289 bytes as it is sent to the destpubtxid, which in turn contains the handle, pub33 and bigpub. the handle is used for error check, pub33 is used to make the destination CC address, so the normal CC signing needs to be passed in addition to the spend restrictions for dilithium. + */ From 4136857e21370a9c44a9afb0f3a963bc95bfb27b Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 23 Feb 2019 23:50:15 -1100 Subject: [PATCH 354/390] Guard against combining before having num music --- src/cc/musig.cpp | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index d93792463..33695aeaa 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -219,7 +219,7 @@ struct musig_info secp256k1_musig_session_signer_data *signer_data; //[N_SIGNERS]; secp256k1_pubkey *nonces; //[N_SIGNERS]; secp256k1_musig_partial_signature *partial_sig; //[N_SIGNERS]; - int32_t myind,num; + int32_t myind,num,numcommits,numnonces,numpartials; uint8_t msg[32],pkhash[32],combpk[33]; } *MUSIG; @@ -511,7 +511,8 @@ UniValue musig_commit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) * number of signers participating in the MuSig. */ result.push_back(Pair("added_index",ind)); - if ( secp256k1_musig_session_get_public_nonce(ctx,&MUSIG->session,MUSIG->signer_data,&MUSIG->nonces[MUSIG->myind],MUSIG->commitment_ptrs,MUSIG->num) > 0 ) + MUSIG->numcommits++; + if ( MUSIG->numcommits >= MUSIG->num && secp256k1_musig_session_get_public_nonce(ctx,&MUSIG->session,MUSIG->signer_data,&MUSIG->nonces[MUSIG->myind],MUSIG->commitment_ptrs,MUSIG->num) > 0 ) { if ( secp256k1_ec_pubkey_serialize(ctx,(uint8_t *)pk.begin(),&clen,&MUSIG->nonces[MUSIG->myind],SECP256K1_EC_COMPRESSED) > 0 && clen == 33 ) { @@ -583,7 +584,8 @@ UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) * adaptor: point to add to the combined public nonce. If NULL, nothing is * added to the combined nonce. */ - if ( secp256k1_musig_session_combine_nonces(ctx,&MUSIG->session,MUSIG->signer_data,MUSIG->num,NULL,NULL) > 0 ) + MUSIG->numnonces++; + if ( MUSIG->numnonces >= MUSIG->num && secp256k1_musig_session_combine_nonces(ctx,&MUSIG->session,MUSIG->signer_data,MUSIG->num,NULL,NULL) > 0 ) { if ( secp256k1_musig_partial_sign(ctx,&MUSIG->session,&MUSIG->partial_sig[MUSIG->myind]) > 0 ) { @@ -621,7 +623,8 @@ UniValue musig_partialsig(uint64_t txfee,struct CCcontract_info *cp,cJSON *param else if ( secp256k1_musig_partial_signature_parse(ctx,&MUSIG->partial_sig[ind],psig) == 0 ) return(cclib_error(result,"error parsing partialsig")); result.push_back(Pair("added_index",ind)); - if ( secp256k1_musig_partial_sig_combine(ctx,&MUSIG->session,&sig,MUSIG->partial_sig,MUSIG->num) > 0 ) + MUSIG->numpartials++; + if ( MUSIG->numpartials >= MUSIG->num && secp256k1_musig_partial_sig_combine(ctx,&MUSIG->session,&sig,MUSIG->partial_sig,MUSIG->num) > 0 ) { if ( secp256k1_schnorrsig_serialize(ctx,out64,&sig) > 0 ) { From 8bfc74cef033bf4ed8d796a85e827a9acca0239f Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 23 Feb 2019 23:52:24 -1100 Subject: [PATCH 355/390] Set numb to 1 --- src/cc/musig.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 33695aeaa..5986f8716 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -466,6 +466,7 @@ UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) for (i=0; i<32; i++) sprintf(&str[i<<1],"%02x",MUSIG->nonce_commitments[MUSIG->myind*32 + i]); str[64] = 0; + MUSIG->numcommits = 1; result.push_back(Pair("commitment",str)); result.push_back(Pair("result","success")); return(result); @@ -519,6 +520,7 @@ UniValue musig_commit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) for (i=0; i<33; i++) sprintf(&str[i<<1],"%02x",((uint8_t *)pk.begin())[i]); str[66] = 0; + MUSIG->numnonces = 1; result.push_back(Pair("myind",MUSIG->myind)); result.push_back(Pair("nonce",str)); result.push_back(Pair("result","success")); @@ -597,6 +599,7 @@ UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) result.push_back(Pair("myind",MUSIG->myind)); result.push_back(Pair("partialsig",str)); result.push_back(Pair("result","success")); + MUSIG->numpartials = 1; return(result); } else return(cclib_error(result,"error serializing partial sig")); } else return(cclib_error(result,"error making partial sig")); From 9dcb99c828800311803140e37298d3f0204ced7e Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 06:08:21 -1100 Subject: [PATCH 356/390] Dilithium spend --- src/cc/cclib.cpp | 4 +-- src/cc/dilithium.c | 74 ++++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 73 insertions(+), 5 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index c64ac025b..b7b2db059 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -80,13 +80,13 @@ CClib_methods[] = { (char *)"musig", (char *)"partialsig", (char *)"pkhash,ind,partialsig", 3, 3, 'S', EVAL_MUSIG }, { (char *)"musig", (char *)"verify", (char *)"msg sig pubkey", 3, 3, 'V', EVAL_MUSIG }, { (char *)"musig", (char *)"send", (char *)"combined_pk amount", 2, 2, 'x', EVAL_MUSIG }, - { (char *)"musig", (char *)"spend", (char *)"sendtxid sig destpubkey", 3, 3, 'y', EVAL_MUSIG }, + { (char *)"musig", (char *)"spend", (char *)"sendtxid sig scriptPubKey", 3, 3, 'y', EVAL_MUSIG }, { (char *)"dilithium", (char *)"keypair", (char *)"[hexseed]", 0, 1, 'K', EVAL_DILITHIUM }, { (char *)"dilithium", (char *)"register", (char *)"handle, [hexseed]", 1, 2, 'R', EVAL_DILITHIUM }, { (char *)"dilithium", (char *)"sign", (char *)"msg [hexseed]", 1, 2, 'S', EVAL_DILITHIUM }, { (char *)"dilithium", (char *)"verify", (char *)"pubtxid msg sig", 3, 3, 'V', EVAL_DILITHIUM }, { (char *)"dilithium", (char *)"send", (char *)"handle pubtxid amount", 3, 3, 'x', EVAL_DILITHIUM }, - { (char *)"dilithium", (char *)"spend", (char *)"sendtxid sig destpubkey", 3, 3, 'y', EVAL_DILITHIUM }, + { (char *)"dilithium", (char *)"spend", (char *)"sendtxid scriptPubKey [hexseed]", 2, 3, 'y', EVAL_DILITHIUM }, #endif }; diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index ed0956c62..30fd2a3bd 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -2947,6 +2947,24 @@ uint8_t dilithium_sendopretdecode(uint256 &destpubtxid,CScript scriptPubKey) return(0); } +CScript dilithium_spendopret(uint256 destpubtxid,std::vector sig) +{ + CScript opret; uint8_t evalcode = EVAL_DILITHIUM; + opret << OP_RETURN << E_MARSHAL(ss << evalcode << 'y' << destpubtxid << sig); + return(opret); +} + +uint8_t dilithium_spendopretdecode(uint256 &destpubtxid,std::vector &sig,CScript scriptPubKey) +{ + std::vector vopret; uint8_t e,f; + GetOpReturnData(scriptPubKey,vopret); + if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> destpubtxid; ss > sig) != 0 && e == EVAL_DILITHIUM && f == 'y' ) + { + return(f); + } + return(0); +} + UniValue dilithium_rawtxresult(UniValue &result,std::string rawtx) { CTransaction tx; @@ -3147,9 +3165,59 @@ UniValue dilithium_send(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) } else return(cclib_error(result,"not enough parameters")); } +/* + ultimately what is needed is to be able to scan all utxos to the CC address and be able to spend many vins in the same tx. to do this the opreturn would need to be able to have txid of special with the sigs. However, it is complicated by the need to create a specific message to sign that is the desired outputs and all the inputs. Also, to properly be able to do change and keep everything in dilithium outputs, there needs to be a second destpub. + + so the proposed opreturn for spend would be: + + destpubtxid0, destpubtxid1 (zeroid if only 1), vector of sigs/sigtxid where if it is len 32 it is a txid that just has the sig in the opreturn. + + however, for now, to keep things simple we will only support spending a specific txid to normal output to avoid needing a combined opreturn and other complications. + */ + UniValue dilithium_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); - // copy musig method - return(result); + CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); + UniValue result(UniValue::VOBJ); std::string rawtx; CPubKey mypk,destpub33; char *scriptstr; uint8_t msg[32]; CTransaction vintx; uint256 prevhash,hashBlock,destpubtxid; int32_t i,smlen,n,numvouts; char str[129]; CTxOut vout; std::string handle; uint8_t pk[CRYPTO_PUBLICKEYBYTES],pk2[CRYPTO_PUBLICKEYBYTES],sk[CRYPTO_SECRETKEYBYTES]; std::vector sig; + if ( txfee == 0 ) + txfee = DILITHIUM_TXFEE; + mypk = pubkey2pk(Mypubkey()); + if ( params != 0 && ((n= cJSON_GetArraySize(params)) == 2 || n == 3) ) + { + prevhash = juint256(jitem(params,0)); + scriptstr = jstr(jitem(params,1),0); + if ( n == 2 || cclib_parsehash(seed,jitem(params,2),32) < 0 ) + { + Myprivkey(seed); + result.push_back(Pair("warning","test mode using privkey for -pubkey, only for testing. there is no point using quantum secure signing if you are using a privkey with a known secp256k1 pubkey!!")); + } + _dilithium_keypair(pk,sk,seed); + if ( is_hexstr(scriptstr,0) != 0 ) + { + CScript scriptPubKey; + scriptPubKey.resize(strlen(scriptstr)/2); + decode_hex(&scriptPubKey[0],strlen(scriptstr)/2,scriptstr); + if ( myGetTransaction(prevhash,vintx,hashBlock) != 0 && (numvouts= vintx.vout.size()) > 1 ) + { + vout.nValue = vintx.vout[0].nValue - txfee; + vout.scriptPubKey = scriptPubKey; + musig_prevoutmsg(msg,prevhash,vout.scriptPubKey); + sig.resize(32+CRYPTO_SIZE); + if ( dilithium_bigpubget(handle,destpub33,pk2,destpubtxid) < 0 ) + return(cclib_error(result,"couldnt parse message to sign")); + else if ( memcmp(pk,pk2,sizeof(pk)) != 0 ) + return(cclib_error(result,"dilithium bigpub mismatch")); + else if ( destpub33 != mypk ) + return(cclib_error(result,"destpub33 is not for this -pubkey")); + else if ( _dilithium_sign(&sig[0],&smlen,msg,32,sk) < 0 ) + return(cclib_error(result,"dilithium signing error")); + else if ( smlen != 32+CRYPTO_SIZE ) + return(cclib_error(result,"siglen error")); + mtx.vin.push_back(CTxIn(prevhash,0)); + mtx.vout.push_back(vout); + rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,dilithium_spendopret('y',destpubtxid,sig)); + return(dilithium_rawtxresult(result,rawtx)); + } else return(cclib_error(result,"couldnt find vin0")); + } else return(cclib_error(result,"script or bad destpubtxid is not hex")); + } else return(cclib_error(result,"need to have exactly 2 params sendtxid, scriptPubKey")); } From 1d4243bb951802fe5eed257161dcbbbdf307a10e Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 06:11:30 -1100 Subject: [PATCH 357/390] > -> >> --- src/cc/dilithium.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index 30fd2a3bd..cc41d2360 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -2958,7 +2958,7 @@ uint8_t dilithium_spendopretdecode(uint256 &destpubtxid,std::vector &si { std::vector vopret; uint8_t e,f; GetOpReturnData(scriptPubKey,vopret); - if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> destpubtxid; ss > sig) != 0 && e == EVAL_DILITHIUM && f == 'y' ) + if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> destpubtxid; ss >> sig) != 0 && e == EVAL_DILITHIUM && f == 'y' ) { return(f); } From 852e7ce0162e18c31cbd500df5c7ed97c9e0e444 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 06:13:30 -1100 Subject: [PATCH 358/390] Syntax --- src/cc/dilithium.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index cc41d2360..197d62786 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -3178,7 +3178,7 @@ UniValue dilithium_send(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue dilithium_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); std::string rawtx; CPubKey mypk,destpub33; char *scriptstr; uint8_t msg[32]; CTransaction vintx; uint256 prevhash,hashBlock,destpubtxid; int32_t i,smlen,n,numvouts; char str[129]; CTxOut vout; std::string handle; uint8_t pk[CRYPTO_PUBLICKEYBYTES],pk2[CRYPTO_PUBLICKEYBYTES],sk[CRYPTO_SECRETKEYBYTES]; std::vector sig; + UniValue result(UniValue::VOBJ); std::string rawtx; CPubKey mypk,destpub33; CTransaction vintx; uint256 prevhash,hashBlock,destpubtxid; int32_t i,smlen,n,numvouts; char str[129],*scriptstr; CTxOut vout; std::string handle; uint8_t pk[CRYPTO_PUBLICKEYBYTES],pk2[CRYPTO_PUBLICKEYBYTES],sk[CRYPTO_SECRETKEYBYTES],msg[32],seed[32]; std::vector sig; if ( txfee == 0 ) txfee = DILITHIUM_TXFEE; mypk = pubkey2pk(Mypubkey()); @@ -3211,11 +3211,11 @@ UniValue dilithium_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params return(cclib_error(result,"destpub33 is not for this -pubkey")); else if ( _dilithium_sign(&sig[0],&smlen,msg,32,sk) < 0 ) return(cclib_error(result,"dilithium signing error")); - else if ( smlen != 32+CRYPTO_SIZE ) + else if ( smlen != 32+CRYPTO_BYTES ) return(cclib_error(result,"siglen error")); mtx.vin.push_back(CTxIn(prevhash,0)); mtx.vout.push_back(vout); - rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,dilithium_spendopret('y',destpubtxid,sig)); + rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,dilithium_spendopret(destpubtxid,sig)); return(dilithium_rawtxresult(result,rawtx)); } else return(cclib_error(result,"couldnt find vin0")); } else return(cclib_error(result,"script or bad destpubtxid is not hex")); From 32a3cc94bbd6799754f083e0c2eb4fa86bb3f024 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 06:18:43 -1100 Subject: [PATCH 359/390] Prev --- src/cc/dilithium.c | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index 197d62786..8a59ecba3 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -2903,6 +2903,7 @@ int32_t main(void) dont forget to broadcast it: 4aac73ebe82c12665d1d005a0ae1a1493cb1e2c714680ef9d016f48a7c77b4a2 notice how small the tx is! 289 bytes as it is sent to the destpubtxid, which in turn contains the handle, pub33 and bigpub. the handle is used for error check, pub33 is used to make the destination CC address, so the normal CC signing needs to be passed in addition to the spend restrictions for dilithium. + cclib spend 19 \"[%224aac73ebe82c12665d1d005a0ae1a1493cb1e2c714680ef9d016f48a7c77b4a2%22,%22210255c46dbce584e3751081b39d7fc054fc807100557e73fc444481618b5706afb4ac%22]\" */ @@ -3182,6 +3183,7 @@ UniValue dilithium_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params if ( txfee == 0 ) txfee = DILITHIUM_TXFEE; mypk = pubkey2pk(Mypubkey()); + fprintf(stderr,"inside\n"); if ( params != 0 && ((n= cJSON_GetArraySize(params)) == 2 || n == 3) ) { prevhash = juint256(jitem(params,0)); @@ -3192,13 +3194,16 @@ UniValue dilithium_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params result.push_back(Pair("warning","test mode using privkey for -pubkey, only for testing. there is no point using quantum secure signing if you are using a privkey with a known secp256k1 pubkey!!")); } _dilithium_keypair(pk,sk,seed); + fprintf(stderr,"after keypair\n"); if ( is_hexstr(scriptstr,0) != 0 ) { + fprintf(stderr,"have script\n"); CScript scriptPubKey; scriptPubKey.resize(strlen(scriptstr)/2); decode_hex(&scriptPubKey[0],strlen(scriptstr)/2,scriptstr); if ( myGetTransaction(prevhash,vintx,hashBlock) != 0 && (numvouts= vintx.vout.size()) > 1 ) { + fprintf(stderr,"got tx\n"); vout.nValue = vintx.vout[0].nValue - txfee; vout.scriptPubKey = scriptPubKey; musig_prevoutmsg(msg,prevhash,vout.scriptPubKey); @@ -3213,6 +3218,7 @@ UniValue dilithium_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params return(cclib_error(result,"dilithium signing error")); else if ( smlen != 32+CRYPTO_BYTES ) return(cclib_error(result,"siglen error")); + fprintf(stderr,"prepare tx\n"); mtx.vin.push_back(CTxIn(prevhash,0)); mtx.vout.push_back(vout); rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,dilithium_spendopret(destpubtxid,sig)); From 93770abb7e0fd41b1e75e936305a91db112cbf2f Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 06:20:15 -1100 Subject: [PATCH 360/390] CRYPTO_BYTES --- src/cc/dilithium.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index 8a59ecba3..d1a700e0b 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -3207,7 +3207,7 @@ UniValue dilithium_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params vout.nValue = vintx.vout[0].nValue - txfee; vout.scriptPubKey = scriptPubKey; musig_prevoutmsg(msg,prevhash,vout.scriptPubKey); - sig.resize(32+CRYPTO_SIZE); + sig.resize(32+CRYPTO_BYTES); if ( dilithium_bigpubget(handle,destpub33,pk2,destpubtxid) < 0 ) return(cclib_error(result,"couldnt parse message to sign")); else if ( memcmp(pk,pk2,sizeof(pk)) != 0 ) From 6deb58ad51184bfb28e48b6be1b1440d201ecb94 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 06:24:31 -1100 Subject: [PATCH 361/390] Fix --- src/cc/dilithium.c | 36 +++++++++++++++++------------------- 1 file changed, 17 insertions(+), 19 deletions(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index d1a700e0b..58a3fd514 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -3183,7 +3183,6 @@ UniValue dilithium_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params if ( txfee == 0 ) txfee = DILITHIUM_TXFEE; mypk = pubkey2pk(Mypubkey()); - fprintf(stderr,"inside\n"); if ( params != 0 && ((n= cJSON_GetArraySize(params)) == 2 || n == 3) ) { prevhash = juint256(jitem(params,0)); @@ -3194,35 +3193,34 @@ UniValue dilithium_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params result.push_back(Pair("warning","test mode using privkey for -pubkey, only for testing. there is no point using quantum secure signing if you are using a privkey with a known secp256k1 pubkey!!")); } _dilithium_keypair(pk,sk,seed); - fprintf(stderr,"after keypair\n"); if ( is_hexstr(scriptstr,0) != 0 ) { - fprintf(stderr,"have script\n"); CScript scriptPubKey; scriptPubKey.resize(strlen(scriptstr)/2); decode_hex(&scriptPubKey[0],strlen(scriptstr)/2,scriptstr); if ( myGetTransaction(prevhash,vintx,hashBlock) != 0 && (numvouts= vintx.vout.size()) > 1 ) { - fprintf(stderr,"got tx\n"); vout.nValue = vintx.vout[0].nValue - txfee; vout.scriptPubKey = scriptPubKey; musig_prevoutmsg(msg,prevhash,vout.scriptPubKey); sig.resize(32+CRYPTO_BYTES); - if ( dilithium_bigpubget(handle,destpub33,pk2,destpubtxid) < 0 ) - return(cclib_error(result,"couldnt parse message to sign")); - else if ( memcmp(pk,pk2,sizeof(pk)) != 0 ) - return(cclib_error(result,"dilithium bigpub mismatch")); - else if ( destpub33 != mypk ) - return(cclib_error(result,"destpub33 is not for this -pubkey")); - else if ( _dilithium_sign(&sig[0],&smlen,msg,32,sk) < 0 ) - return(cclib_error(result,"dilithium signing error")); - else if ( smlen != 32+CRYPTO_BYTES ) - return(cclib_error(result,"siglen error")); - fprintf(stderr,"prepare tx\n"); - mtx.vin.push_back(CTxIn(prevhash,0)); - mtx.vout.push_back(vout); - rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,dilithium_spendopret(destpubtxid,sig)); - return(dilithium_rawtxresult(result,rawtx)); + if ( dilithium_sendopretdecode(destpubtxid,tx.vout[numvouts-1].scriptPubKey) == 'x' ) + { + if ( dilithium_bigpubget(handle,destpub33,pk2,destpubtxid) < 0 ) + return(cclib_error(result,"couldnt parse message to sign")); + else if ( memcmp(pk,pk2,sizeof(pk)) != 0 ) + return(cclib_error(result,"dilithium bigpub mismatch")); + else if ( destpub33 != mypk ) + return(cclib_error(result,"destpub33 is not for this -pubkey")); + else if ( _dilithium_sign(&sig[0],&smlen,msg,32,sk) < 0 ) + return(cclib_error(result,"dilithium signing error")); + else if ( smlen != 32+CRYPTO_BYTES ) + return(cclib_error(result,"siglen error")); + mtx.vin.push_back(CTxIn(prevhash,0)); + mtx.vout.push_back(vout); + rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,dilithium_spendopret(destpubtxid,sig)); + return(dilithium_rawtxresult(result,rawtx)); + } else return(cclib_error(result,"couldnt decode send opret")); } else return(cclib_error(result,"couldnt find vin0")); } else return(cclib_error(result,"script or bad destpubtxid is not hex")); } else return(cclib_error(result,"need to have exactly 2 params sendtxid, scriptPubKey")); From c16c21f664a3ef3f448046f3b8680b70da9324b9 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 06:25:08 -1100 Subject: [PATCH 362/390] Vent --- src/cc/dilithium.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index 58a3fd514..94e2efc66 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -3204,7 +3204,7 @@ UniValue dilithium_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params vout.scriptPubKey = scriptPubKey; musig_prevoutmsg(msg,prevhash,vout.scriptPubKey); sig.resize(32+CRYPTO_BYTES); - if ( dilithium_sendopretdecode(destpubtxid,tx.vout[numvouts-1].scriptPubKey) == 'x' ) + if ( dilithium_sendopretdecode(destpubtxid,vintx.vout[numvouts-1].scriptPubKey) == 'x' ) { if ( dilithium_bigpubget(handle,destpub33,pk2,destpubtxid) < 0 ) return(cclib_error(result,"couldnt parse message to sign")); From 57c1d1cc8c7303cf6bd81ca20b8e9358136e5fe0 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 06:43:30 -1100 Subject: [PATCH 363/390] Dilithium validate --- src/cc/cclib.cpp | 3 +++ src/cc/dilithium.c | 34 +++++++++++++++++++++++++++++++++- 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index b7b2db059..286008660 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -127,6 +127,7 @@ UniValue musig_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue musig_send(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +bool dilithium_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx); UniValue dilithium_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue dilithium_send(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue dilithium_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); @@ -406,6 +407,8 @@ bool CClib_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C return(sudoku_validate(cp,height,eval,tx)); else if ( cp->evalcode == EVAL_MUSIG ) return(musig_validate(cp,height,eval,tx)); + else if ( cp->evalcode == DILITHIUM_MUSIG ) + return(dilithium_validate(cp,height,eval,tx)); else return eval->Invalid("invalid evalcode"); #endif } diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index 94e2efc66..dc636d7e8 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -3207,7 +3207,7 @@ UniValue dilithium_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params if ( dilithium_sendopretdecode(destpubtxid,vintx.vout[numvouts-1].scriptPubKey) == 'x' ) { if ( dilithium_bigpubget(handle,destpub33,pk2,destpubtxid) < 0 ) - return(cclib_error(result,"couldnt parse message to sign")); + return(cclib_error(result,"couldnt get bigpub")); else if ( memcmp(pk,pk2,sizeof(pk)) != 0 ) return(cclib_error(result,"dilithium bigpub mismatch")); else if ( destpub33 != mypk ) @@ -3225,3 +3225,35 @@ UniValue dilithium_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params } else return(cclib_error(result,"script or bad destpubtxid is not hex")); } else return(cclib_error(result,"need to have exactly 2 params sendtxid, scriptPubKey")); } + +bool dilithium_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) +{ + CPubKey destpub33; std::string handle; uint256 hashBlock,destpubtxid,checktxid; CTransaction vintx; int32_t numvouts,mlen,smlen=CRYPTO_BYTES+32; std::vector sig; uint8_t msg[32],msg2[32],pk[CRYPTO_PUBLICKEYBYTES]; + if ( tx.vout.size() != 2 ) + return eval->Invalid("numvouts != 2"); + else if ( tx.vin.size() != 1 ) + return eval->Invalid("numvins != 1"); + else if ( IsCCInput(tx.vin[0].scriptSig) == 0 ) + return eval->Invalid("illegal normal vin0"); + else if ( myGetTransaction(tx.vin[0].prevout.hash,vintx,hashBlock) != 0 && (numvouts= vintx.vout.size()) > 1 ) + { + if ( dilithium_sendopretdecode(destpubtxid,vintx.vout[numvouts-1].scriptPubKey) == 'x' ) + { + if ( dilithium_spendopretdecode(checktxid,sig,tx.vout[tx.vout.size()-1].scriptPubKey) == 'y' ) + { + if ( destpubtxid == checktxid ) + { + musig_prevoutmsg(msg,tx.vin[0].prevout.hash,tx.vout[0].scriptPubKey); + if ( dilithium_bigpubget(handle,destpub33,pk,destpubtxid) < 0 ) + return eval->Invalid(result,"couldnt get bigpub"); + else if ( _dilithium_verify(msg2,&mlen,&sig[0],(int32_t)sig.size(),pk) < 0 ) + return eval->Invalid("failed dilithium verify"); + else if ( mlen != 32 || memcmp(msg,msg2,32) != 0 ) + return eval->Invalid("failed dilithium msg verify"); + else return eval->Invalid("this is actually success!"); + } else return eval->Invalid("destpubtxid didnt match send opret"); + } else return eval->Invalid("failed decode dilithium spendopret"); + } else return eval->Invalid("couldnt decode send opret"); + } else return eval->Invalid("couldnt find vin0 tx"); +} + From 0ee7d2fed4c0988e49cc79bbcc182cc7a3078213 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 06:45:00 -1100 Subject: [PATCH 364/390] Fix --- src/cc/cclib.cpp | 2 +- src/cc/dilithium.c | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 286008660..f7749d99f 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -407,7 +407,7 @@ bool CClib_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C return(sudoku_validate(cp,height,eval,tx)); else if ( cp->evalcode == EVAL_MUSIG ) return(musig_validate(cp,height,eval,tx)); - else if ( cp->evalcode == DILITHIUM_MUSIG ) + else if ( cp->evalcode == EVAL_DILITHIUM ) return(dilithium_validate(cp,height,eval,tx)); else return eval->Invalid("invalid evalcode"); #endif diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index dc636d7e8..cf52a98c2 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -3245,7 +3245,7 @@ bool dilithium_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,con { musig_prevoutmsg(msg,tx.vin[0].prevout.hash,tx.vout[0].scriptPubKey); if ( dilithium_bigpubget(handle,destpub33,pk,destpubtxid) < 0 ) - return eval->Invalid(result,"couldnt get bigpub"); + return eval->Invalid("couldnt get bigpub"); else if ( _dilithium_verify(msg2,&mlen,&sig[0],(int32_t)sig.size(),pk) < 0 ) return eval->Invalid("failed dilithium verify"); else if ( mlen != 32 || memcmp(msg,msg2,32) != 0 ) From 7f601cbfc7b284aceea87bc87d8721cab85c640a Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 06:50:16 -1100 Subject: [PATCH 365/390] +print --- src/cc/dilithium.c | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index cf52a98c2..bb6b06e91 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -3237,13 +3237,18 @@ bool dilithium_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,con return eval->Invalid("illegal normal vin0"); else if ( myGetTransaction(tx.vin[0].prevout.hash,vintx,hashBlock) != 0 && (numvouts= vintx.vout.size()) > 1 ) { + fprintf(stderr,"inside\n"); if ( dilithium_sendopretdecode(destpubtxid,vintx.vout[numvouts-1].scriptPubKey) == 'x' ) { + fprintf(stderr,"about to spendopret\n"); if ( dilithium_spendopretdecode(checktxid,sig,tx.vout[tx.vout.size()-1].scriptPubKey) == 'y' ) { - if ( destpubtxid == checktxid ) + fprintf(stderr,"checktxid.%s vs %s\n",destpubtxid.GetHex().c_str(),checktxid.GetHex().c_str()); + if ( destpubtxid == checktxid && sig.size() == CRYPTO_BYTES+32 ) { + fprintf(stderr,"call prevoutmsg\n"); musig_prevoutmsg(msg,tx.vin[0].prevout.hash,tx.vout[0].scriptPubKey); + fprintf(stderr,"call dilithium_bigpubget\n"); if ( dilithium_bigpubget(handle,destpub33,pk,destpubtxid) < 0 ) return eval->Invalid("couldnt get bigpub"); else if ( _dilithium_verify(msg2,&mlen,&sig[0],(int32_t)sig.size(),pk) < 0 ) @@ -3251,7 +3256,7 @@ bool dilithium_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,con else if ( mlen != 32 || memcmp(msg,msg2,32) != 0 ) return eval->Invalid("failed dilithium msg verify"); else return eval->Invalid("this is actually success!"); - } else return eval->Invalid("destpubtxid didnt match send opret"); + } else return eval->Invalid("destpubtxid or sig size didnt match send opret"); } else return eval->Invalid("failed decode dilithium spendopret"); } else return eval->Invalid("couldnt decode send opret"); } else return eval->Invalid("couldnt find vin0 tx"); From 97db451dc1e635801dcacf277af8d94538590247 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 06:55:31 -1100 Subject: [PATCH 366/390] Bigger msg2 --- src/cc/dilithium.c | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index bb6b06e91..5e6b926fa 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -3109,7 +3109,7 @@ UniValue dilithium_sign(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue dilithium_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); CPubKey pk33; uint8_t rmd160[20],msg[32],msg2[32],pk[CRYPTO_PUBLICKEYBYTES],sm[32+CRYPTO_BYTES]; uint256 pubtxid; char coinaddr[64],str[(32+CRYPTO_BYTES)*2+1]; int32_t smlen=32+CRYPTO_BYTES,mlen,n; std::string handle; + UniValue result(UniValue::VOBJ); CPubKey pk33; uint8_t rmd160[20],msg[32],msg2[CRYPTO_BYTES+32],pk[CRYPTO_PUBLICKEYBYTES],sm[32+CRYPTO_BYTES]; uint256 pubtxid; char coinaddr[64],str[(32+CRYPTO_BYTES)*2+1]; int32_t smlen=32+CRYPTO_BYTES,mlen,n; std::string handle; if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) { pubtxid = juint256(jitem(params,0)); @@ -3228,7 +3228,7 @@ UniValue dilithium_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params bool dilithium_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { - CPubKey destpub33; std::string handle; uint256 hashBlock,destpubtxid,checktxid; CTransaction vintx; int32_t numvouts,mlen,smlen=CRYPTO_BYTES+32; std::vector sig; uint8_t msg[32],msg2[32],pk[CRYPTO_PUBLICKEYBYTES]; + CPubKey destpub33; std::string handle; uint256 hashBlock,destpubtxid,checktxid; CTransaction vintx; int32_t numvouts,mlen,smlen=CRYPTO_BYTES+32; std::vector sig; uint8_t msg[32],msg2[CRYPTO_BYTES+32],pk[CRYPTO_PUBLICKEYBYTES]; if ( tx.vout.size() != 2 ) return eval->Invalid("numvouts != 2"); else if ( tx.vin.size() != 1 ) @@ -3244,18 +3244,22 @@ bool dilithium_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,con if ( dilithium_spendopretdecode(checktxid,sig,tx.vout[tx.vout.size()-1].scriptPubKey) == 'y' ) { fprintf(stderr,"checktxid.%s vs %s\n",destpubtxid.GetHex().c_str(),checktxid.GetHex().c_str()); - if ( destpubtxid == checktxid && sig.size() == CRYPTO_BYTES+32 ) + if ( destpubtxid == checktxid && sig.size() == smlen ) { fprintf(stderr,"call prevoutmsg\n"); musig_prevoutmsg(msg,tx.vin[0].prevout.hash,tx.vout[0].scriptPubKey); fprintf(stderr,"call dilithium_bigpubget\n"); if ( dilithium_bigpubget(handle,destpub33,pk,destpubtxid) < 0 ) return eval->Invalid("couldnt get bigpub"); - else if ( _dilithium_verify(msg2,&mlen,&sig[0],(int32_t)sig.size(),pk) < 0 ) - return eval->Invalid("failed dilithium verify"); - else if ( mlen != 32 || memcmp(msg,msg2,32) != 0 ) - return eval->Invalid("failed dilithium msg verify"); - else return eval->Invalid("this is actually success!"); + else + { + fprintf(stderr,"call _dilithium_verify\n"); + if ( _dilithium_verify(msg2,&mlen,&sig[0],smlen,pk) < 0 ) + return eval->Invalid("failed dilithium verify"); + else if ( mlen != 32 || memcmp(msg,msg2,32) != 0 ) + return eval->Invalid("failed dilithium msg verify"); + else return eval->Invalid("this is actually success!"); + } } else return eval->Invalid("destpubtxid or sig size didnt match send opret"); } else return eval->Invalid("failed decode dilithium spendopret"); } else return eval->Invalid("couldnt decode send opret"); From 38a94fefae6a9a7f448a056dbcc47a1993c370e8 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 06:58:12 -1100 Subject: [PATCH 367/390] Test bad sig --- src/cc/dilithium.c | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index 5e6b926fa..8c56b0bc7 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -3237,23 +3237,18 @@ bool dilithium_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,con return eval->Invalid("illegal normal vin0"); else if ( myGetTransaction(tx.vin[0].prevout.hash,vintx,hashBlock) != 0 && (numvouts= vintx.vout.size()) > 1 ) { - fprintf(stderr,"inside\n"); if ( dilithium_sendopretdecode(destpubtxid,vintx.vout[numvouts-1].scriptPubKey) == 'x' ) { - fprintf(stderr,"about to spendopret\n"); if ( dilithium_spendopretdecode(checktxid,sig,tx.vout[tx.vout.size()-1].scriptPubKey) == 'y' ) { - fprintf(stderr,"checktxid.%s vs %s\n",destpubtxid.GetHex().c_str(),checktxid.GetHex().c_str()); if ( destpubtxid == checktxid && sig.size() == smlen ) { - fprintf(stderr,"call prevoutmsg\n"); musig_prevoutmsg(msg,tx.vin[0].prevout.hash,tx.vout[0].scriptPubKey); - fprintf(stderr,"call dilithium_bigpubget\n"); if ( dilithium_bigpubget(handle,destpub33,pk,destpubtxid) < 0 ) return eval->Invalid("couldnt get bigpub"); else { - fprintf(stderr,"call _dilithium_verify\n"); + sig[777] ^= 0xaa; if ( _dilithium_verify(msg2,&mlen,&sig[0],smlen,pk) < 0 ) return eval->Invalid("failed dilithium verify"); else if ( mlen != 32 || memcmp(msg,msg2,32) != 0 ) From ddae255171e120b7fdb00bfef1a744a98352c6a2 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 07:00:21 -1100 Subject: [PATCH 368/390] Dlithium validation active, hardforking change --- src/cc/dilithium.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index 8c56b0bc7..ab8ca9ae5 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -2905,6 +2905,9 @@ int32_t main(void) cclib spend 19 \"[%224aac73ebe82c12665d1d005a0ae1a1493cb1e2c714680ef9d016f48a7c77b4a2%22,%22210255c46dbce584e3751081b39d7fc054fc807100557e73fc444481618b5706afb4ac%22]\" + this generates a really big hex, broadcast it and if all went well it will get confirmed. + a dilithium spend! + */ #define DILITHIUM_TXFEE 10000 @@ -3248,12 +3251,11 @@ bool dilithium_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,con return eval->Invalid("couldnt get bigpub"); else { - sig[777] ^= 0xaa; if ( _dilithium_verify(msg2,&mlen,&sig[0],smlen,pk) < 0 ) return eval->Invalid("failed dilithium verify"); else if ( mlen != 32 || memcmp(msg,msg2,32) != 0 ) return eval->Invalid("failed dilithium msg verify"); - else return eval->Invalid("this is actually success!"); + else return(true); } } else return eval->Invalid("destpubtxid or sig size didnt match send opret"); } else return eval->Invalid("failed decode dilithium spendopret"); From 98d8d03e2f8928e74cc8b3700c041806a3cf39ba Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 07:27:30 -1100 Subject: [PATCH 369/390] Gold * gold payout algo change --- src/cc/rogue_rpc.cpp | 106 ++++++++++++++++++++++--------------------- 1 file changed, 54 insertions(+), 52 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 8cfb4379f..16c09fbe9 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -947,6 +947,56 @@ UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) return(result); } +int32_t rogue_playerdata_validate(uint256 &playertxid,struct CCcontract_info *cp,std::vector playerdata,uint256 gametxid,CPubKey pk) +{ + static uint32_t good,bad; static uint256 prevgame; + char str[512],*keystrokes,rogueaddr[64],str2[67]; int32_t i,numkeys; std::vector newdata; uint64_t seed; CPubKey roguepk; struct rogue_player P; + if ( gametxid == prevgame ) + return(0); + prevgame = gametxid; + roguepk = GetUnspendable(cp,0); + GetCCaddress1of2(cp,rogueaddr,roguepk,pk); + //fprintf(stderr,"call extractgame\n"); + if ( (keystrokes= rogue_extractgame(0,str,&numkeys,newdata,seed,playertxid,cp,gametxid,rogueaddr)) != 0 ) + { + //fprintf(stderr,"numkeys.%d rogue_extractgame %s\n",numkeys,gametxid.GetHex().c_str()); + free(keystrokes); + //fprintf(stderr,"extracted.(%s)\n",str); + if ( newdata == playerdata ) + { + good++; + fprintf(stderr,"%s good.%d bad.%d\n",gametxid.GetHex().c_str(),good,bad); + return(0); + } + newdata[10] = newdata[11] = playerdata[10] = playerdata[11] = 0; + if ( newdata == playerdata ) + { + good++; + fprintf(stderr,"%s matched after clearing maxstrength good.%d bad.%d\n",gametxid.GetHex().c_str(),good,bad); + return(0); + } + for (i=0; i no playerdata, good.%d bad.%d\n",good,bad); + } + bad++; + fprintf(stderr,"%s playerdata: gold.%d hp.%d strength.%d/%d level.%d exp.%d dl.%d\n",gametxid.GetHex().c_str(),P.gold,P.hitpoints,P.strength&0xffff,P.strength>>16,P.level,P.experience,P.dungeonlevel); + fprintf(stderr,"newdata[%d] != playerdata[%d], numkeys.%d %s pub.%s playertxid.%s good.%d bad.%d\n",(int32_t)newdata.size(),(int32_t)playerdata.size(),numkeys,rogueaddr,pubkey33_str(str2,(uint8_t *)&pk),playertxid.GetHex().c_str(),good,bad); + } + //fprintf(stderr,"no keys rogue_extractgame %s\n",gametxid.GetHex().c_str()); + return(-1); +} + UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *params,char *method) { //vin0 -> highlander vout from creategame TCBOO @@ -975,12 +1025,12 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param if ( strcmp(method,"bailout") == 0 ) { funcid = 'Q'; - mult = 100000; + mult = 100; //100000; } else { funcid = 'H'; - mult = 200000; + mult = 200; //200000; } if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) { @@ -1005,7 +1055,7 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param { num = rogue_replay2(player,seed,keystrokes,numkeys,playerdata.size()==0?0:&P,0); if ( keystrokes != 0 ) - free(keystrokes); + free(keystrokes), keystrokes = 0; } else num = 0; mtx.vin.push_back(CTxIn(batontxid,batonvout,CScript())); mtx.vin.push_back(CTxIn(gametxid,1+maxplayers+regslot,CScript())); @@ -1034,7 +1084,7 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param mtx.vout.push_back(MakeTokensCC1vout(cp->evalcode,1,mypk)); if ( P.amulet != 0 ) mult *= 5; - cashout = (uint64_t)P.gold * mult; + cashout = (uint64_t)P.gold * P.gold * mult; fprintf(stderr,"\nextracted $$$gold.%d -> %.8f ROGUE hp.%d strength.%d/%d level.%d exp.%d dl.%d n.%d amulet.%d\n",P.gold,(double)cashout/COIN,P.hitpoints,P.strength&0xffff,P.strength>>16,P.level,P.experience,P.dungeonlevel,n,P.amulet); if ( funcid == 'H' && maxplayers > 1 ) { @@ -1051,7 +1101,6 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param } } mtx.vout.push_back(MakeCC1vout(cp->evalcode,CCchange + (batonvalue-3*txfee),roguepk)); - Myprivkey(mypriv); CCaddr1of2set(cp,roguepk,mypk,mypriv,myrogueaddr); CScript opret; @@ -1245,53 +1294,6 @@ UniValue rogue_setname(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) return(result); } -int32_t rogue_playerdata_validate(uint256 &playertxid,struct CCcontract_info *cp,std::vector playerdata,uint256 gametxid,CPubKey pk) -{ - static uint32_t good,bad; static uint256 prevgame; - char str[512],*keystrokes,rogueaddr[64],str2[67]; int32_t i,numkeys; std::vector newdata; uint64_t seed; CPubKey roguepk; struct rogue_player P; - if ( gametxid == prevgame ) - return(0); - prevgame = gametxid; - roguepk = GetUnspendable(cp,0); - GetCCaddress1of2(cp,rogueaddr,roguepk,pk); - //fprintf(stderr,"call extractgame\n"); - if ( (keystrokes= rogue_extractgame(0,str,&numkeys,newdata,seed,playertxid,cp,gametxid,rogueaddr)) != 0 ) - { - //fprintf(stderr,"numkeys.%d rogue_extractgame %s\n",numkeys,gametxid.GetHex().c_str()); - free(keystrokes); - //fprintf(stderr,"extracted.(%s)\n",str); - if ( newdata == playerdata ) - { - good++; - fprintf(stderr,"%s good.%d bad.%d\n",gametxid.GetHex().c_str(),good,bad); - return(0); - } - newdata[10] = newdata[11] = playerdata[10] = playerdata[11] = 0; - if ( newdata == playerdata ) - { - good++; - fprintf(stderr,"%s matched after clearing maxstrength good.%d bad.%d\n",gametxid.GetHex().c_str(),good,bad); - return(0); - } - for (i=0; i no playerdata, good.%d bad.%d\n",good,bad); - if ( newdata.size() == 0 ) - { - good++; - return(0); - } - } - bad++; - fprintf(stderr,"%s playerdata: gold.%d hp.%d strength.%d/%d level.%d exp.%d dl.%d\n",gametxid.GetHex().c_str(),P.gold,P.hitpoints,P.strength&0xffff,P.strength>>16,P.level,P.experience,P.dungeonlevel); - fprintf(stderr,"newdata[%d] != playerdata[%d], numkeys.%d %s pub.%s playertxid.%s good.%d bad.%d\n",(int32_t)newdata.size(),(int32_t)playerdata.size(),numkeys,rogueaddr,pubkey33_str(str2,(uint8_t *)&pk),playertxid.GetHex().c_str(),good,bad); - } - //fprintf(stderr,"no keys rogue_extractgame %s\n",gametxid.GetHex().c_str()); - return(-1); -} - bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,maxplayers,decoded=0,regslot,ind,err,dispflag,gameheight,score,numvouts; CTransaction vintx,gametx; CPubKey pk; uint256 hashBlock,gametxid,tokenid,batontxid,playertxid,ptxid; int64_t buyin; std::vector playerdata,keystrokes; std::string symbol,pname; From 4dcef6624bc8f2c1da09a9e8e78bca8357872028 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 08:17:20 -1100 Subject: [PATCH 370/390] Delay after keystrokes --- src/cc/rogue/main.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index 165f01dfd..4dba36f2b 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -726,9 +726,10 @@ void rogue_progress(struct rogue_state *rs,uint64_t seed,char *keystrokes,int32_ sprintf(params,"[\"keystrokes\",\"17\",\"[%%22%s%%22,%%22%s%%22]\"]",Gametxidstr,hexstr); if ( (retstr= komodo_issuemethod(USERPASS,"cclib",params,ROGUE_PORT)) != 0 ) { - //fprintf(stderr,"KEYSTROKES.(%s)\n",retstr); + fprintf(stderr,"KEYSTROKES.(%s)\n",retstr); free(retstr); } + sleep(1); } } } From b88129c21cfeb98a32131056daafdcfc462652b7 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 08:19:09 -1100 Subject: [PATCH 371/390] Force keystrokes --- src/cc/rogue/rogue.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index e8de063de..52d41435c 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -567,6 +567,8 @@ playit(struct rogue_state *rs) } } } + if ( rs->guiflag != 0 ) + flushkeystrokes(rs); endit(0); } From 46055e824fbf3d9b1e132863026faef9eb30236e Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 08:29:21 -1100 Subject: [PATCH 372/390] Log keystrokes to keystrokes.log --- src/cc/rogue/main.c | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index 4dba36f2b..5de27317e 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -723,10 +723,17 @@ void rogue_progress(struct rogue_state *rs,uint64_t seed,char *keystrokes,int32_ } else { + static FILE *fp; + if ( fp == 0 ) + fp = fopen("keystrokes.log","a"); sprintf(params,"[\"keystrokes\",\"17\",\"[%%22%s%%22,%%22%s%%22]\"]",Gametxidstr,hexstr); if ( (retstr= komodo_issuemethod(USERPASS,"cclib",params,ROGUE_PORT)) != 0 ) { - fprintf(stderr,"KEYSTROKES.(%s)\n",retstr); + if ( fp != 0 ) + { + fprintf(fp,"%s\n",retstr); + fflush(fp); + } free(retstr); } sleep(1); From df66ea2b9da0a3bcafc4517077736607cf255f8e Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 08:37:33 -1100 Subject: [PATCH 373/390] Kill the zombies --- src/cc/rogue/state.c | 2 +- src/cc/rogue_rpc.cpp | 33 +++++++++++++++++++++------------ 2 files changed, 22 insertions(+), 13 deletions(-) diff --git a/src/cc/rogue/state.c b/src/cc/rogue/state.c index 7a0e2e4c6..b0176a042 100644 --- a/src/cc/rogue/state.c +++ b/src/cc/rogue/state.c @@ -1432,7 +1432,7 @@ rs_write_object(struct rogue_state *rs,FILE *savef, THING *o) if ( o->_o._o_packch != 0 ) { item = &rs->P.roguepack[rs->P.packsize]; - if ( 0 && pstats.s_hpt <= 0 ) + if ( 1 && pstats.s_hpt <= 0 ) { //fprintf(stderr,"KILLED\n"); rs->P.gold = -1; diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 16c09fbe9..4790932d1 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -883,13 +883,22 @@ char *rogue_extractgame(int32_t makefiles,char *str,int32_t *numkeysp,std::vecto if ( endP.gold <= 0 || endP.hitpoints <= 0 || (endP.strength&0xffff) <= 0 || endP.level <= 0 || endP.experience <= 0 || endP.dungeonlevel <= 0 ) { //fprintf(stderr,"zero value character was killed -> no playerdata\n"); - //newdata.resize(0); - P.gold = (P.gold * 8) / 10; + newdata.resize(0); + //P.gold = (P.gold * 8) / 10; + if ( keystrokes != 0 ) + { + free(keystrokes); + keystrokes = 0; + *numkeysp = 0; + } + } + else + { + sprintf(str,"extracted $$$gold.%d hp.%d strength.%d/%d level.%d exp.%d dl.%d\n",endP.gold,endP.hitpoints,endP.strength&0xffff,endP.strength>>16,endP.level,endP.experience,endP.dungeonlevel); + fprintf(stderr,"%s\n",str); + *numkeysp = numkeys; + return(keystrokes); } - sprintf(str,"extracted $$$gold.%d hp.%d strength.%d/%d level.%d exp.%d dl.%d\n",endP.gold,endP.hitpoints,endP.strength&0xffff,endP.strength>>16,endP.level,endP.experience,endP.dungeonlevel); - fprintf(stderr,"%s\n",str); - *numkeysp = numkeys; - return(keystrokes); } else num = 0; } else @@ -979,9 +988,9 @@ int32_t rogue_playerdata_validate(uint256 &playertxid,struct CCcontract_info *cp ((uint8_t *)&P)[i] = playerdata[i]; if ( P.gold <= 0 || P.hitpoints <= 0 || (P.strength&0xffff) <= 0 || P.level <= 0 || P.experience <= 0 || P.dungeonlevel <= 0 ) { - P.gold = (P.gold * 8) / 10; - for (i=0; i no playerdata\n"); - //newdata.resize(0); - P.gold = (P.gold * 8) / 10; + newdata.resize(0); + //P.gold = (P.gold * 8) / 10; } - //else + else { //if ( maxplayers == 1 ) // mult /= 2; From b0735e2f327ce7ca08224e274b86a3a177a9d2d7 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 09:11:38 -1100 Subject: [PATCH 374/390] Gold payout = (gold * gold * level * 10) satoshi --- src/cc/rogue_rpc.cpp | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 4790932d1..1a4f7c1cd 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1020,7 +1020,7 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param // vout0 -> 1% ingame gold // get any playerdata, get all keystrokes, replay game and compare final state CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); std::string rawtx,symbol,pname; CTransaction gametx; uint64_t seed,mult; int64_t buyin,batonvalue,inputsum,cashout,CCchange=0; int32_t i,err,gameheight,tmp,numplayers,regslot,n,num,numkeys,maxplayers,batonht,batonvout; char myrogueaddr[64],*keystrokes = 0; std::vector playerdata,newdata,nodata; uint256 batontxid,playertxid,gametxid; CPubKey mypk,roguepk; uint8_t player[10000],mypriv[32],funcid; + UniValue result(UniValue::VOBJ); std::string rawtx,symbol,pname; CTransaction gametx; uint64_t seed,mult; int64_t buyin,batonvalue,inputsum,cashout,CCchange=0; int32_t i,err,gameheight,tmp,numplayers,regslot,n,num,dungeonlevel,numkeys,maxplayers,batonht,batonvout; char myrogueaddr[64],*keystrokes = 0; std::vector playerdata,newdata,nodata; uint256 batontxid,playertxid,gametxid; CPubKey mypk,roguepk; uint8_t player[10000],mypriv[32],funcid; struct CCcontract_info *cpTokens, tokensC; if ( txfee == 0 ) @@ -1034,12 +1034,12 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param if ( strcmp(method,"bailout") == 0 ) { funcid = 'Q'; - mult = 100; //100000; + mult = 10; //100000; } else { funcid = 'H'; - mult = 200; //200000; + mult = 20; //200000; } if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) { @@ -1093,7 +1093,10 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param mtx.vout.push_back(MakeTokensCC1vout(cp->evalcode,1,mypk)); if ( P.amulet != 0 ) mult *= 5; - cashout = (uint64_t)P.gold * P.gold * mult; + dungeonlevel = P.dungeonlevel; + if ( P.amulet != 0 && dungeonlevel < 21 ) + dungeonlevel = 21; + cashout = (uint64_t)P.gold * P.gold * mult * dungeonlevel; fprintf(stderr,"\nextracted $$$gold.%d -> %.8f ROGUE hp.%d strength.%d/%d level.%d exp.%d dl.%d n.%d amulet.%d\n",P.gold,(double)cashout/COIN,P.hitpoints,P.strength&0xffff,P.strength>>16,P.level,P.experience,P.dungeonlevel,n,P.amulet); if ( funcid == 'H' && maxplayers > 1 ) { From 8c5ba39d22f91af50e0bf93d1e7cd2f1dce5828f Mon Sep 17 00:00:00 2001 From: blackjok3r Date: Mon, 25 Feb 2019 13:18:14 +0800 Subject: [PATCH 375/390] fix ipaddress --- src/cc/rogue/main.c | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index 5de27317e..02690a482 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -587,9 +587,9 @@ char *curl_post(CURL **cHandlep,char *url,char *userpass,char *postfields,char * return(chunk.memory); } -uint16_t _komodo_userpass(char *username, char *password, char *ipaddress, FILE *fp) +uint16_t _komodo_userpass(char *username, char *password, FILE *fp) { - char *rpcuser,*rpcpassword,*str,line[8192]; uint16_t port = 0; + char *rpcuser,*rpcpassword,*str,*ipaddress,line[8192]; uint16_t port = 0; rpcuser = rpcpassword = 0; username[0] = password[0] = 0; while ( fgets(line,sizeof(line),fp) != 0 ) @@ -609,6 +609,7 @@ uint16_t _komodo_userpass(char *username, char *password, char *ipaddress, FILE else if ( (str= strstr(line,(char *)"ipaddress")) != 0 ) { ipaddress = parse_conf_line(str,(char *)"ipaddress"); + strcpy(IPADDRESS,ipaddress); } } if ( rpcuser != 0 && rpcpassword != 0 ) @@ -616,7 +617,7 @@ uint16_t _komodo_userpass(char *username, char *password, char *ipaddress, FILE strcpy(username,rpcuser); strcpy(password,rpcpassword); } - //printf("rpcuser.(%s) rpcpassword.(%s) KMDUSERPASS.(%s) %u\n",rpcuser,rpcpassword,KMDUSERPASS,port); + //printf("rpcuser.(%s) rpcpassword.(%s) %u ipaddress.%s\n",rpcuser,rpcpassword,port,ipaddress); if ( rpcuser != 0 ) free(rpcuser); if ( rpcpassword != 0 ) @@ -661,7 +662,7 @@ uint16_t _komodo_userpass(char *username, char *password, char *ipaddress, FILE //printf("test.(%s) -> [%s] statename.(%s) %s\n",test,ASSETCHAINS_SYMBOL,symbol,fname); }*/ -uint16_t komodo_userpass(char *userpass,char *symbol,char *ipaddress) +uint16_t komodo_userpass(char *userpass,char *symbol) { FILE *fp; uint16_t port = 0; char fname[512],username[512],password[512],confname[KOMODO_ASSETCHAIN_MAXLEN]; userpass[0] = 0; @@ -677,7 +678,7 @@ uint16_t komodo_userpass(char *userpass,char *symbol,char *ipaddress) //komodo_statefname(fname,symbol,confname); if ( (fp= fopen(confname,"rb")) != 0 ) { - port = _komodo_userpass(username,password,ipaddress,fp); + port = _komodo_userpass(username,password,fp); sprintf(userpass,"%s:%s",username,password); if ( strcmp(symbol,ASSETCHAINS_SYMBOL) == 0 ) strcpy(USERPASS,userpass); @@ -809,10 +810,10 @@ int main(int argc, char **argv, char **envp) ASSETCHAINS_SYMBOL[j++] = toupper(c); } ASSETCHAINS_SYMBOL[j++] = 0; - ROGUE_PORT = komodo_userpass(userpass,ASSETCHAINS_SYMBOL,IPADDRESS); + ROGUE_PORT = komodo_userpass(userpass,ASSETCHAINS_SYMBOL); if ( IPADDRESS[0] == 0 ) strcpy(IPADDRESS,"127.0.0.1"); - printf("ASSETCHAINS_SYMBOL.(%s) port.%u (%s)\n",ASSETCHAINS_SYMBOL,ROGUE_PORT,USERPASS); sleep(1); + printf("ASSETCHAINS_SYMBOL.(%s) port.%u (%s) IPADDRESS.%s \n",ASSETCHAINS_SYMBOL,ROGUE_PORT,USERPASS,IPADDRESS); sleep(1); if ( argc == 2 && (fp=fopen(argv[1],"rb")) == 0 ) { seed = atol(argv[1]); From 6f5d9655c903ae265eb0f0cb72da4cf9af4b0b9d Mon Sep 17 00:00:00 2001 From: blackjok3r Date: Mon, 25 Feb 2019 13:20:48 +0800 Subject: [PATCH 376/390] fix --- src/musigtest.py | 189 --------------------------------------- src/wallet/rpcwallet.cpp | 8 +- 2 files changed, 4 insertions(+), 193 deletions(-) delete mode 100755 src/musigtest.py diff --git a/src/musigtest.py b/src/musigtest.py deleted file mode 100755 index 0880f1494..000000000 --- a/src/musigtest.py +++ /dev/null @@ -1,189 +0,0 @@ -#!/usr/bin/env python3 -import platform -import os -import re -import json -import random -import base58 -import binascii -import hashlib -import sys -import time -from slickrpc import Proxy - -# fucntion to define rpc_connection -def def_credentials(chain): - rpcport = ''; - operating_system = platform.system() - if operating_system == 'Darwin': - ac_dir = os.environ['HOME'] + '/Library/Application Support/Komodo' - elif operating_system == 'Linux': - ac_dir = os.environ['HOME'] + '/.komodo' - elif operating_system == 'Windows': - ac_dir = '%s/komodo/' % os.environ['APPDATA'] - if chain == 'KMD': - coin_config_file = str(ac_dir + '/komodo.conf') - else: - coin_config_file = str(ac_dir + '/' + chain + '/' + chain + '.conf') - with open(coin_config_file, 'r') as f: - for line in f: - l = line.rstrip() - if re.search('rpcuser', l): - rpcuser = l.replace('rpcuser=', '') - elif re.search('rpcpassword', l): - rpcpassword = l.replace('rpcpassword=', '') - elif re.search('rpcport', l): - rpcport = l.replace('rpcport=', '') - if len(rpcport) == 0: - if chain == 'KMD': - rpcport = 7771 - else: - print("rpcport not in conf file, exiting") - print("check " + coin_config_file) - exit(1) - return (Proxy("http://%s:%s@127.0.0.1:%d" % (rpcuser, rpcpassword, int(rpcport)))) - - -# generate address, validate address, dump private key -def genvaldump(rpc_connection): - # get new address - address = rpc_connection.getnewaddress() - # validate address - validateaddress_result = rpc_connection.validateaddress(address) - pubkey = validateaddress_result['pubkey'] - address = validateaddress_result['address'] - # dump private key for the address - privkey = rpc_connection.dumpprivkey(address) - # function output - output = [pubkey, privkey, address] - return(output) - -CHAIN = 'MUSIG' #sys.argv[1] - -rpc = def_credentials(CHAIN) - -pubkeys = [] -address_info = [] -ret = input('Do you want to generate new pubkeys? ').lower() - -if ret.startswith('y'): - numpks = int(input('Enter number of pubkeys to combine: ')) - if os.path.isfile("list.json"): - print('Already have list.json, move it if you would like to generate a new set.') - sys.exit(0) - while len(address_info) < numpks: - addressinfo = genvaldump(rpc) - address_info.append(addressinfo) - f = open("list.json", "w+") - f.write(json.dumps(address_info)) -else: - if os.path.isfile("list.json"): - with open('list.json') as list: - address_info = json.load(list) - else: - sys.exit('No list.json you need to create new pubkeys!') - -for addressinfo in address_info: - pubkeys.append(addressinfo[0]) - -ret = rpc.setpubkey(pubkeys[0]) -ret = rpc.cclib("combine", "18", str(pubkeys)) -pkhash = str(ret['pkhash']) -combinedpk = str(ret['combined_pk']) -print('Your combined pubkey is: ' + combinedpk) -print('Your pkhash is: ' + pkhash) -amount = int(input('Enter amount to send: ')) -tmp = str([combinedpk, amount]) -hex = rpc.cclib("send", "18", tmp)['hex'] -senttxid = rpc.sendrawtransaction(hex) -print('Your senttxid is: ' + senttxid) - -print("Waiting for tx to be confirmed") -while True: - confirmed = int(rpc.gettransaction(senttxid)["confirmations"]) - if not confirmed: - time.sleep(10) - else: - print('SentTX confirmed') - break - -scriptPubKey = rpc.getrawtransaction(senttxid,1)['vout'][1]['scriptPubKey']['hex'] -print('Your scriptPubKey is: ' + scriptPubKey) -tmp = str([senttxid, scriptPubKey]) -msg = rpc.cclib("calcmsg", "18", tmp)['msg'] -print('Your msg is: ' + msg) - -i = 0; -commitments = [] -for pubkey in pubkeys: - ret = rpc.setpubkey(pubkey) - tmp = str([i, len(pubkeys), combinedpk, pkhash, msg]) - commitments.append(rpc.cclib("session", "18", tmp)['commitment']) - i = i + 1 - -#print(commitments) - -i = 0 -nonces = [] -for pubkey in pubkeys: - ret = rpc.setpubkey(pubkey) - n = 0 - for commitment in commitments: - tmp = str([i, pkhash, n, commitment]) - ret = rpc.cclib("commit", "18", tmp) - try: - nonces.append(ret['nonce']) - except: - x = 1 - n = n + 1 - i = i + 1 - -#print(nonces) - -i = 0 -partialsigs = [] -for pubkey in pubkeys: - ret = rpc.setpubkey(pubkey) - n = 0 - for nonce in nonces: - tmp = str([i, pkhash, n, nonce]) - ret = rpc.cclib("nonce", "18", tmp) - try: - partialsigs.append(ret['partialsig']) - except: - x = 1 - n = n + 1 - i = i + 1 - -#print(partialsigs) - -i = 0 -combinedsigs = [] -for pubkey in pubkeys: - ret = rpc.setpubkey(pubkey) - n = 0 - for partialsig in partialsigs: - tmp = str([i, pkhash, n, partialsig]) - ret = rpc.cclib("partialsig", "18", tmp) - try: - combinedsigs.append(ret['combinedsig']) - except: - x = 1 - n = n + 1 - i = i + 1 - -#print(combinedsigs) - -tmp = str([msg, combinedpk, combinedsigs[0]]) -ret = rpc.cclib("verify", "18", tmp) - -#print(ret) - -tmp = str([senttxid, scriptPubKey, combinedsigs[0]]) -ret = rpc.cclib("spend", "18", tmp) - -print(ret) - -ret = rpc.sendrawtransaction(ret['hex']) - -print(ret) diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 8cffd78f7..0ed2f866c 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -5308,8 +5308,8 @@ UniValue setpubkey(const UniValue& params, bool fHelp) char Raddress[64]; uint8_t pubkey33[33]; - //if ( NOTARY_PUBKEY33[0] == 0 ) - //{ + if ( NOTARY_PUBKEY33[0] == 0 ) + { if (strlen(params[0].get_str().c_str()) == 66) { decode_hex(pubkey33,33,(char *)params[0].get_str().c_str()); @@ -5337,14 +5337,14 @@ UniValue setpubkey(const UniValue& params, bool fHelp) USE_EXTERNAL_PUBKEY = 1; } } else result.push_back(Pair("error", "pubkey is wrong length, must be 66 char hex string.")); - /*} + } else { result.push_back(Pair("error", "Can only set pubkey once, to change it you need to restart your daemon, pubkey in use is below.")); pubkey2addr((char *)Raddress,(uint8_t *)NOTARY_PUBKEY33); std::string address_ret; address_ret.assign(Raddress); result.push_back(Pair("address",address_ret)); - }*/ + } result.push_back(Pair("pubkey", NOTARY_PUBKEY)); return result; } From c5930804ab2789402fa7c0a0d73460a1aa32488b Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 18:24:33 -1100 Subject: [PATCH 377/390] Flush keystrokes every 1000 --- src/cc/rogue/rogue.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 52d41435c..53f6da353 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -560,7 +560,7 @@ playit(struct rogue_state *rs) } else { - if ( rs->needflush != 0 && rs->num > 8000 ) + if ( rs->needflush != 0 && rs->num > 1000 ) { if ( flushkeystrokes(rs) == 0 ) rs->needflush = 0; From 54ee605f7f5be48886c14e9bfbc56564096238f8 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 18:27:26 -1100 Subject: [PATCH 378/390] Save params in keystrokes.log --- src/cc/rogue/main.c | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index 5de27317e..ec347dd12 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -731,6 +731,7 @@ void rogue_progress(struct rogue_state *rs,uint64_t seed,char *keystrokes,int32_ { if ( fp != 0 ) { + fprintf(fp,"%s\n",params); fprintf(fp,"%s\n",retstr); fflush(fp); } From e8a36b89826e934a20f95a229b3ab103a67414af Mon Sep 17 00:00:00 2001 From: blackjok3r Date: Mon, 25 Feb 2019 17:12:25 +0800 Subject: [PATCH 379/390] Update to enable using a single node with musigtest.py script. Fix crash in nonce step. --- src/cc/musig.cpp | 126 +++++++++++++++--------- src/musigtest.py | 200 +++++++++++++++++++++++++++++++++++++++ src/wallet/rpcwallet.cpp | 2 +- 3 files changed, 282 insertions(+), 46 deletions(-) create mode 100755 src/musigtest.py diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 5986f8716..35293088c 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -33,7 +33,6 @@ } sendrawtransaction of the above hex. - ./komodo-cli -ac_name=MUSIG getrawtransaction 5ce74037a153ee210413b48d4e88638b99825a2de1a1f1aa0d36ebf93019824c 1 "vout": [ { @@ -83,7 +82,7 @@ the "msg" is what needs to be signed to create a valid spend 5 args: ind, numsigners, combined_pk, pkhash, message to be signed on node with pubkey: 02fb6aa0b96cad24d46b5da93eba3864c45ce07a73bba12da530ae841e140fcf28 - ./komodo-cli -ac_name=MUSIG cclib session 18 '[0,2,"03f016c348437c7422eed92d865aa9789614f75327cada463eefc566126b54785b","c1b34139744f3b54b652dc741ebd0f9d5b53ad28795cc6614dd8ad3aaabf15ae","f5d91999b23b85630a4cbd0baea3736529411b052cf5f1f4345c5d181af12825"]' + ./komodo-cli -ac_name=MUSIG cclib session 18 '[0,2,"03f016c348437c7422eed92d865aa9789614f75327cada463eefc566126b54785b","5cb5a225064ca6ffc1438cb2a6ac2ac65fe2d5055dc7f6c7ebffb9a231f8912b","f7fb85d1412814e3c2f98b990802af6ee33dad368c6ba05c2050e9e5506fcd75"]' { "myind": 0, "numsigners": 2, @@ -221,7 +220,9 @@ struct musig_info secp256k1_musig_partial_signature *partial_sig; //[N_SIGNERS]; int32_t myind,num,numcommits,numnonces,numpartials; uint8_t msg[32],pkhash[32],combpk[33]; -} *MUSIG; +}; + +std::vector MUSIG; struct musig_info *musig_infocreate(int32_t myind,int32_t num) { @@ -412,23 +413,33 @@ UniValue musig_combine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { static secp256k1_context *ctx; - UniValue result(UniValue::VOBJ); int32_t i,n,myind,num; char *pkstr,*pkhashstr,*msgstr; uint8_t session[32],msg[32],pkhash[32],privkey[32],pub33[33]; CPubKey pk; char str[67]; + UniValue result(UniValue::VOBJ); int32_t i,n,myind,num,musiglocation; char *pkstr,*pkhashstr,*msgstr; uint8_t session[32],msg[32],pkhash[32],privkey[32],pub33[33]; CPubKey pk; char str[67]; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); - if ( params != 0 && (n= cJSON_GetArraySize(params)) == 5 ) + if ( params != 0 && (n= cJSON_GetArraySize(params)) >= 5 ) { myind = juint(jitem(params,0),0); num = juint(jitem(params,1),0); if ( myind < 0 || myind >= num || num <= 0 ) return(cclib_error(result,"illegal myindex and numsigners")); - if ( MUSIG != 0 ) - musig_infofree(MUSIG), MUSIG = 0; - MUSIG = musig_infocreate(myind,num); - if ( musig_parsepubkey(ctx,MUSIG->combined_pk,jitem(params,2)) < 0 ) + if ( n > 5 ) + musiglocation = juint(jitem(params,5),0); + else if ( n == 5 ) + musiglocation = 0; + //printf("number of params.%i musiglocation.%i\n",n,musiglocation); + if ( MUSIG.size() > musiglocation ) + { + for (int i = 0; i < MUSIG.size()-1; i++) + musig_infofree(MUSIG[i]); + MUSIG.clear(); + } + struct musig_info *temp_musig = musig_infocreate(myind,num); + MUSIG.push_back(temp_musig); + if ( musig_parsepubkey(ctx,MUSIG[musiglocation]->combined_pk,jitem(params,2)) < 0 ) return(cclib_error(result,"error parsing combined_pubkey")); - else if ( cclib_parsehash(MUSIG->pkhash,jitem(params,3),32) < 0 ) + else if ( cclib_parsehash(MUSIG[musiglocation]->pkhash,jitem(params,3),32) < 0 ) return(cclib_error(result,"error parsing pkhash")); - else if ( cclib_parsehash(MUSIG->msg,jitem(params,4),32) < 0 ) + else if ( cclib_parsehash(MUSIG[musiglocation]->msg,jitem(params,4),32) < 0 ) return(cclib_error(result,"error parsing msg")); Myprivkey(privkey); GetRandBytes(session,32); @@ -458,15 +469,17 @@ UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) * my_index: index of this signer in the signers array * seckey: the signer's 32-byte secret key (cannot be NULL) */ - if ( secp256k1_musig_session_initialize(ctx,&MUSIG->session,MUSIG->signer_data, &MUSIG->nonce_commitments[MUSIG->myind * 32],session,MUSIG->msg,&MUSIG->combined_pk,MUSIG->pkhash,MUSIG->num,MUSIG->myind,privkey) > 0 ) + //fprintf(stderr, "SESSION: struct_size.%li using struct %i\n",MUSIG.size(), musiglocation); + if ( secp256k1_musig_session_initialize(ctx,&MUSIG[musiglocation]->session,MUSIG[musiglocation]->signer_data, &MUSIG[musiglocation]->nonce_commitments[MUSIG[musiglocation]->myind * 32],session,MUSIG[musiglocation]->msg,&MUSIG[musiglocation]->combined_pk,MUSIG[musiglocation]->pkhash,MUSIG[musiglocation]->num,MUSIG[musiglocation]->myind,privkey) > 0 ) { memset(session,0,sizeof(session)); result.push_back(Pair("myind",(int64_t)myind)); result.push_back(Pair("numsigners",(int64_t)num)); for (i=0; i<32; i++) - sprintf(&str[i<<1],"%02x",MUSIG->nonce_commitments[MUSIG->myind*32 + i]); + sprintf(&str[i<<1],"%02x",MUSIG[musiglocation]->nonce_commitments[MUSIG[musiglocation]->myind*32 + i]); str[64] = 0; - MUSIG->numcommits = 1; + if ( n == 5 ) + MUSIG[musiglocation]->numcommits = 1; result.push_back(Pair("commitment",str)); result.push_back(Pair("result","success")); return(result); @@ -483,18 +496,22 @@ UniValue musig_commit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { static secp256k1_context *ctx; size_t clen = CPubKey::PUBLIC_KEY_SIZE; - UniValue result(UniValue::VOBJ); int32_t i,n,ind; uint8_t pkhash[32]; CPubKey pk; char str[67]; + UniValue result(UniValue::VOBJ); int32_t i,n,ind,myind; uint8_t pkhash[32]; CPubKey pk; char str[67]; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); - if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) + if ( params != 0 && (n= cJSON_GetArraySize(params)) >= 3 ) { + if ( n > 3 ) + myind = juint(jitem(params,3),0); + else if ( n == 3 ) + myind = 0; if ( cclib_parsehash(pkhash,jitem(params,0),32) < 0 ) return(cclib_error(result,"error parsing pkhash")); - else if ( memcmp(MUSIG->pkhash,pkhash,32) != 0 ) + else if ( memcmp(MUSIG[myind]->pkhash,pkhash,32) != 0 ) return(cclib_error(result,"pkhash doesnt match session pkhash")); - else if ( (ind= juint(jitem(params,1),0)) < 0 || ind >= MUSIG->num ) + else if ( (ind= juint(jitem(params,1),0)) < 0 || ind >= MUSIG[myind]->num ) return(cclib_error(result,"illegal ind for session")); - else if ( cclib_parsehash(&MUSIG->nonce_commitments[ind*32],jitem(params,2),32) < 0 ) + else if ( cclib_parsehash(&MUSIG[myind]->nonce_commitments[ind*32],jitem(params,2),32) < 0 ) return(cclib_error(result,"error parsing commitment")); /** Gets the signer's public nonce given a list of all signers' data with commitments * @@ -512,16 +529,18 @@ UniValue musig_commit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) * number of signers participating in the MuSig. */ result.push_back(Pair("added_index",ind)); - MUSIG->numcommits++; - if ( MUSIG->numcommits >= MUSIG->num && secp256k1_musig_session_get_public_nonce(ctx,&MUSIG->session,MUSIG->signer_data,&MUSIG->nonces[MUSIG->myind],MUSIG->commitment_ptrs,MUSIG->num) > 0 ) + //fprintf(stderr, "COMMIT: struct_size.%li using_struct.%i added_index.%i\n",MUSIG.size(), myind, ind); + MUSIG[myind]->numcommits++; + if ( MUSIG[myind]->numcommits >= MUSIG[myind]->num && secp256k1_musig_session_get_public_nonce(ctx,&MUSIG[myind]->session,MUSIG[myind]->signer_data,&MUSIG[myind]->nonces[MUSIG[myind]->myind],MUSIG[myind]->commitment_ptrs,MUSIG[myind]->num) > 0 ) { - if ( secp256k1_ec_pubkey_serialize(ctx,(uint8_t *)pk.begin(),&clen,&MUSIG->nonces[MUSIG->myind],SECP256K1_EC_COMPRESSED) > 0 && clen == 33 ) + if ( secp256k1_ec_pubkey_serialize(ctx,(uint8_t *)pk.begin(),&clen,&MUSIG[myind]->nonces[MUSIG[myind]->myind],SECP256K1_EC_COMPRESSED) > 0 && clen == 33 ) { for (i=0; i<33; i++) sprintf(&str[i<<1],"%02x",((uint8_t *)pk.begin())[i]); str[66] = 0; - MUSIG->numnonces = 1; - result.push_back(Pair("myind",MUSIG->myind)); + if ( n == 5 ) + MUSIG[myind]->numnonces = 1; + result.push_back(Pair("myind",MUSIG[myind]->myind)); result.push_back(Pair("nonce",str)); result.push_back(Pair("result","success")); } else return(cclib_error(result,"error serializing nonce (pubkey)")); @@ -538,18 +557,22 @@ UniValue musig_commit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { static secp256k1_context *ctx; - UniValue result(UniValue::VOBJ); int32_t i,n,ind; uint8_t pkhash[32],psig[32]; CPubKey pk; char str[67]; + UniValue result(UniValue::VOBJ); int32_t i,n,ind,myind; uint8_t pkhash[32],psig[32]; CPubKey pk; char str[67]; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); - if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) + if ( params != 0 && (n= cJSON_GetArraySize(params)) >= 3 ) { + if ( n > 3 ) + myind = juint(jitem(params,3),0); + else if ( n == 3 ) + myind = 0; if ( cclib_parsehash(pkhash,jitem(params,0),32) < 0 ) return(cclib_error(result,"error parsing pkhash")); - else if ( memcmp(MUSIG->pkhash,pkhash,32) != 0 ) + else if ( memcmp(MUSIG[myind]->pkhash,pkhash,32) != 0 ) return(cclib_error(result,"pkhash doesnt match session pkhash")); - else if ( (ind= juint(jitem(params,1),0)) < 0 || ind >= MUSIG->num ) + else if ( (ind= juint(jitem(params,1),0)) < 0 || ind >= MUSIG[myind]->num ) return(cclib_error(result,"illegal ind for session")); - else if ( musig_parsepubkey(ctx,MUSIG->nonces[ind],jitem(params,2)) < 0 ) + else if ( musig_parsepubkey(ctx,MUSIG[myind]->nonces[ind],jitem(params,2)) < 0 ) return(cclib_error(result,"error parsing nonce")); result.push_back(Pair("added_index",ind)); /** Checks a signer's public nonce against a commitment to said nonce, and update @@ -563,9 +586,17 @@ UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) * with `musig_session_initialize_verifier`. * In: nonce: signer's alleged public nonce (cannot be NULL) */ - for (i=0; inum; i++) + MUSIG[myind]->numnonces++; + //fprintf(stderr, "NONCE: struct_size.%li using_struct.%i added_index.%i numnounces.%i num.%i\n",MUSIG.size(), myind, ind, MUSIG[myind]->numnonces, MUSIG[myind]->num); + if ( MUSIG[myind]->numnonces < MUSIG[myind]->num ) { - if ( secp256k1_musig_set_nonce(ctx,&MUSIG->signer_data[i],&MUSIG->nonces[i]) == 0 ) + result.push_back(Pair("status","not enough nonces")); + result.push_back(Pair("result","success")); + return(result); + } + for (i=0; inum; i++) + { + if ( secp256k1_musig_set_nonce(ctx,&MUSIG[myind]->signer_data[i],&MUSIG[myind]->nonces[i]) == 0 ) return(cclib_error(result,"error setting nonce")); } /** Updates a session with the combined public nonce of all signers. The combined @@ -586,20 +617,20 @@ UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) * adaptor: point to add to the combined public nonce. If NULL, nothing is * added to the combined nonce. */ - MUSIG->numnonces++; - if ( MUSIG->numnonces >= MUSIG->num && secp256k1_musig_session_combine_nonces(ctx,&MUSIG->session,MUSIG->signer_data,MUSIG->num,NULL,NULL) > 0 ) + if ( secp256k1_musig_session_combine_nonces(ctx,&MUSIG[myind]->session,MUSIG[myind]->signer_data,MUSIG[myind]->num,NULL,NULL) > 0 ) { - if ( secp256k1_musig_partial_sign(ctx,&MUSIG->session,&MUSIG->partial_sig[MUSIG->myind]) > 0 ) + if ( secp256k1_musig_partial_sign(ctx,&MUSIG[myind]->session,&MUSIG[myind]->partial_sig[MUSIG[myind]->myind]) > 0 ) { - if ( secp256k1_musig_partial_signature_serialize(ctx,psig,&MUSIG->partial_sig[MUSIG->myind]) > 0 ) + if ( secp256k1_musig_partial_signature_serialize(ctx,psig,&MUSIG[myind]->partial_sig[MUSIG[myind]->myind]) > 0 ) { for (i=0; i<32; i++) sprintf(&str[i<<1],"%02x",psig[i]); str[64] = 0; - result.push_back(Pair("myind",MUSIG->myind)); + result.push_back(Pair("myind",MUSIG[myind]->myind)); result.push_back(Pair("partialsig",str)); result.push_back(Pair("result","success")); - MUSIG->numpartials = 1; + if ( n == 5 ) + MUSIG[myind]->numpartials = 1; return(result); } else return(cclib_error(result,"error serializing partial sig")); } else return(cclib_error(result,"error making partial sig")); @@ -610,24 +641,29 @@ UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue musig_partialsig(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { static secp256k1_context *ctx; - UniValue result(UniValue::VOBJ); int32_t i,ind,n; uint8_t pkhash[32],psig[32],out64[64]; char str[129]; secp256k1_schnorrsig sig; + UniValue result(UniValue::VOBJ); int32_t i,ind,n,myind; uint8_t pkhash[32],psig[32],out64[64]; char str[129]; secp256k1_schnorrsig sig; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); - if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) + if ( params != 0 && (n= cJSON_GetArraySize(params)) >= 3 ) { + if ( n > 3 ) + myind = juint(jitem(params,3),0); + else if ( n == 3 ) + myind = 0; if ( cclib_parsehash(pkhash,jitem(params,0),32) < 0 ) return(cclib_error(result,"error parsing pkhash")); - else if ( memcmp(MUSIG->pkhash,pkhash,32) != 0 ) + else if ( memcmp(MUSIG[myind]->pkhash,pkhash,32) != 0 ) return(cclib_error(result,"pkhash doesnt match session pkhash")); - else if ( (ind= juint(jitem(params,1),0)) < 0 || ind >= MUSIG->num ) + else if ( (ind= juint(jitem(params,1),0)) < 0 || ind >= MUSIG[myind]->num ) return(cclib_error(result,"illegal ind for session")); else if ( cclib_parsehash(psig,jitem(params,2),32) < 0 ) return(cclib_error(result,"error parsing psig")); - else if ( secp256k1_musig_partial_signature_parse(ctx,&MUSIG->partial_sig[ind],psig) == 0 ) + else if ( secp256k1_musig_partial_signature_parse(ctx,&MUSIG[myind]->partial_sig[ind],psig) == 0 ) return(cclib_error(result,"error parsing partialsig")); result.push_back(Pair("added_index",ind)); - MUSIG->numpartials++; - if ( MUSIG->numpartials >= MUSIG->num && secp256k1_musig_partial_sig_combine(ctx,&MUSIG->session,&sig,MUSIG->partial_sig,MUSIG->num) > 0 ) + //fprintf(stderr, "SIG: struct_size.%li using_struct.%i added_index.%i\n",MUSIG.size(), myind, ind); + MUSIG[myind]->numpartials++; + if ( MUSIG[myind]->numpartials >= MUSIG[myind]->num && secp256k1_musig_partial_sig_combine(ctx,&MUSIG[myind]->session,&sig,MUSIG[myind]->partial_sig,MUSIG[myind]->num) > 0 ) { if ( secp256k1_schnorrsig_serialize(ctx,out64,&sig) > 0 ) { @@ -640,7 +676,7 @@ UniValue musig_partialsig(uint64_t txfee,struct CCcontract_info *cp,cJSON *param } else { - if ( secp256k1_musig_partial_signature_serialize(ctx,psig,&MUSIG->partial_sig[MUSIG->myind]) > 0 ) + if ( secp256k1_musig_partial_signature_serialize(ctx,psig,&MUSIG[myind]->partial_sig[MUSIG[myind]->myind]) > 0 ) { result.push_back(Pair("myind",ind)); for (i=0; i<32; i++) diff --git a/src/musigtest.py b/src/musigtest.py new file mode 100755 index 000000000..a452b7e97 --- /dev/null +++ b/src/musigtest.py @@ -0,0 +1,200 @@ +#!/usr/bin/env python3 +import platform +import os +import re +import json +import random +import base58 +import binascii +import hashlib +import sys +import time +from slickrpc import Proxy + +# fucntion to define rpc_connection +def def_credentials(chain): + rpcport = ''; + operating_system = platform.system() + if operating_system == 'Darwin': + ac_dir = os.environ['HOME'] + '/Library/Application Support/Komodo' + elif operating_system == 'Linux': + ac_dir = os.environ['HOME'] + '/.komodo' + elif operating_system == 'Windows': + ac_dir = '%s/komodo/' % os.environ['APPDATA'] + if chain == 'KMD': + coin_config_file = str(ac_dir + '/komodo.conf') + else: + coin_config_file = str(ac_dir + '/' + chain + '/' + chain + '.conf') + with open(coin_config_file, 'r') as f: + for line in f: + l = line.rstrip() + if re.search('rpcuser', l): + rpcuser = l.replace('rpcuser=', '') + elif re.search('rpcpassword', l): + rpcpassword = l.replace('rpcpassword=', '') + elif re.search('rpcport', l): + rpcport = l.replace('rpcport=', '') + if len(rpcport) == 0: + if chain == 'KMD': + rpcport = 7771 + else: + print("rpcport not in conf file, exiting") + print("check " + coin_config_file) + exit(1) + return (Proxy("http://%s:%s@127.0.0.1:%d" % (rpcuser, rpcpassword, int(rpcport)))) + + +# generate address, validate address, dump private key +def genvaldump(rpc_connection): + # get new address + address = rpc_connection.getnewaddress() + # validate address + validateaddress_result = rpc_connection.validateaddress(address) + pubkey = validateaddress_result['pubkey'] + address = validateaddress_result['address'] + # dump private key for the address + privkey = rpc_connection.dumpprivkey(address) + # function output + output = [pubkey, privkey, address] + return(output) + +CHAIN = 'MUSIG' #sys.argv[1] + +rpc = def_credentials(CHAIN) + +pubkeys = [] +address_info = [] +ret = input('Do you want to generate new pubkeys? ').lower() + +if ret.startswith('y'): + numpks = int(input('Enter number of pubkeys to combine: ')) + if os.path.isfile("list.json"): + print('Already have list.json, move it if you would like to generate a new set.') + sys.exit(0) + while len(address_info) < numpks: + addressinfo = genvaldump(rpc) + address_info.append(addressinfo) + f = open("list.json", "w+") + f.write(json.dumps(address_info)) +else: + if os.path.isfile("list.json"): + with open('list.json') as list: + address_info = json.load(list) + else: + sys.exit('No list.json you need to create new pubkeys!') + +for addressinfo in address_info: + pubkeys.append(addressinfo[0]) + +ret = rpc.setpubkey(pubkeys[0]) +ret = rpc.cclib("combine", "18", str(pubkeys)) +pkhash = str(ret['pkhash']) +combinedpk = str(ret['combined_pk']) +print('Your combined pubkey is: ' + combinedpk) +print('Your pkhash is: ' + pkhash) +amount = float(input('Enter amount to send: ')) +if amount == 0: + sys.exit('Cannot send 0 coins. Exiting.') +tmp = str([combinedpk, amount]) +hex = rpc.cclib("send", "18", tmp)['hex'] +senttxid = rpc.sendrawtransaction(hex) +print('Your senttxid is: ' + senttxid) + +print("Waiting for tx to be confirmed") +while True: + confirmed = int(rpc.gettransaction(senttxid)["confirmations"]) + if not confirmed: + time.sleep(10) + else: + print('SentTX confirmed') + break + +scriptPubKey = rpc.getrawtransaction(senttxid,1)['vout'][1]['scriptPubKey']['hex'] +print('Your scriptPubKey is: ' + scriptPubKey) +tmp = str([senttxid, scriptPubKey]) +msg = rpc.cclib("calcmsg", "18", tmp)['msg'] +print('Your msg is: ' + msg) + +i = 0; +commitments = [] +for pubkey in pubkeys: + ret = rpc.setpubkey(pubkey) + tmp = str([i, len(pubkeys), combinedpk, pkhash, msg, i]) + commitments.append(rpc.cclib("session", "18", tmp)['commitment']) + i = i + 1 + +print("Created commitments sucessfully... Sending to all signers.") + +i = 0 +nonces = [] +for pubkey in pubkeys: + ret = rpc.setpubkey(pubkey) + n = 0 + for commitment in commitments: + tmp = str([pkhash, n, commitment, i]) + ret = rpc.cclib("commit", "18", tmp) + try: + nonces.append(ret['nonce']) + except: + x = 1 + n = n + 1 + i = i + 1 + +print("Created nounce's sucessfully... Sending to all signers.") + +i = 0 +partialsigs = [] +for pubkey in pubkeys: + ret = rpc.setpubkey(pubkey) + n = 0 + for nonce in nonces: + tmp = str([pkhash, n, nonce, i]) + ret = rpc.cclib("nonce", "18", tmp) + try: + partialsigs.append(ret['partialsig']) + except: + x = 1 + n = n + 1 + i = i + 1 + +print("Created partial sigs sucessfully... Sending to all signers.") + +i = 0 +combinedsigs = [] +for pubkey in pubkeys: + ret = rpc.setpubkey(pubkey) + n = 0 + for partialsig in partialsigs: + tmp = str([pkhash, n, partialsig, i]) + ret = rpc.cclib("partialsig", "18", tmp) + try: + combinedsigs.append(ret['combinedsig']) + except: + x = 1 + n = n + 1 + i = i + 1 + +print("Created combined sigs sucessfully... Verifying.") + +tmp = str([msg, combinedpk, combinedsigs[0]]) +ret = rpc.cclib("verify", "18", tmp) + +if ret['result'] != "success": + print(ret) + sys.exit('Could not verify signature.') + +print('Verified... Attempting to send.') + +tmp = str([senttxid, scriptPubKey, combinedsigs[0]]) +ret = rpc.cclib("spend", "18", tmp) + +if ret['result'] != "success": + print(ret) + sys.exit('Could not create spend transaction.') + +try: + ret = rpc.sendrawtransaction(ret['hex']) +except: + sys.exit('Could not send transaction.') + +print('Spent txid: ' + ret) diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 0ed2f866c..0e0ab9906 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -5308,7 +5308,7 @@ UniValue setpubkey(const UniValue& params, bool fHelp) char Raddress[64]; uint8_t pubkey33[33]; - if ( NOTARY_PUBKEY33[0] == 0 ) + if ( NOTARY_PUBKEY33[0] == 0 || (strcmp(ASSETCHAINS_SYMBOL, "MUSIG") == 0) ) { if (strlen(params[0].get_str().c_str()) == 66) { From 4d4a74d917c80d4dc2fa46bdf40348049ef3ec8d Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 22:44:40 -1100 Subject: [PATCH 380/390] Cashout prints --- src/cc/dilithium.c | 1 + src/cc/rogue_rpc.cpp | 65 ++++++++++++++++++++++++++++++-------------- 2 files changed, 46 insertions(+), 20 deletions(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index ab8ca9ae5..c0ff8f274 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -3232,6 +3232,7 @@ UniValue dilithium_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params bool dilithium_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { CPubKey destpub33; std::string handle; uint256 hashBlock,destpubtxid,checktxid; CTransaction vintx; int32_t numvouts,mlen,smlen=CRYPTO_BYTES+32; std::vector sig; uint8_t msg[32],msg2[CRYPTO_BYTES+32],pk[CRYPTO_PUBLICKEYBYTES]; + // if all dilithium tx -> do multispend/send, else: if ( tx.vout.size() != 2 ) return eval->Invalid("numvouts != 2"); else if ( tx.vin.size() != 1 ) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 1a4f7c1cd..3d9b02115 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -894,7 +894,7 @@ char *rogue_extractgame(int32_t makefiles,char *str,int32_t *numkeysp,std::vecto } else { - sprintf(str,"extracted $$$gold.%d hp.%d strength.%d/%d level.%d exp.%d dl.%d\n",endP.gold,endP.hitpoints,endP.strength&0xffff,endP.strength>>16,endP.level,endP.experience,endP.dungeonlevel); + sprintf(str,"extracted $$$gold.%d hp.%d strength.%d/%d level.%d exp.%d dl.%d",endP.gold,endP.hitpoints,endP.strength&0xffff,endP.strength>>16,endP.level,endP.experience,endP.dungeonlevel); fprintf(stderr,"%s\n",str); *numkeysp = numkeys; return(keystrokes); @@ -956,13 +956,11 @@ UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) return(result); } -int32_t rogue_playerdata_validate(uint256 &playertxid,struct CCcontract_info *cp,std::vector playerdata,uint256 gametxid,CPubKey pk) +int32_t rogue_playerdata_validate(int64_t *cashoutp,uint256 &playertxid,struct CCcontract_info *cp,std::vector playerdata,uint256 gametxid,CPubKey pk) { static uint32_t good,bad; static uint256 prevgame; - char str[512],*keystrokes,rogueaddr[64],str2[67]; int32_t i,numkeys; std::vector newdata; uint64_t seed; CPubKey roguepk; struct rogue_player P; - if ( gametxid == prevgame ) - return(0); - prevgame = gametxid; + char str[512],*keystrokes,rogueaddr[64],str2[67]; int32_t i,dungeonlevel,numkeys; std::vector newdata; uint64_t seed,mult = 10; CPubKey roguepk; struct rogue_player P; + *cashoutp = 0; roguepk = GetUnspendable(cp,0); GetCCaddress1of2(cp,rogueaddr,roguepk,pk); //fprintf(stderr,"call extractgame\n"); @@ -971,21 +969,35 @@ int32_t rogue_playerdata_validate(uint256 &playertxid,struct CCcontract_info *cp //fprintf(stderr,"numkeys.%d rogue_extractgame %s\n",numkeys,gametxid.GetHex().c_str()); free(keystrokes); //fprintf(stderr,"extracted.(%s)\n",str); + for (i=0; i no playerdata, good.%d bad.%d\n",good,bad); + } + *cashoutp = 0; return(0); } - fprintf(stderr,"zero value character was killed -> no playerdata, good.%d bad.%d\n",good,bad); } - bad++; - fprintf(stderr,"%s playerdata: gold.%d hp.%d strength.%d/%d level.%d exp.%d dl.%d\n",gametxid.GetHex().c_str(),P.gold,P.hitpoints,P.strength&0xffff,P.strength>>16,P.level,P.experience,P.dungeonlevel); - fprintf(stderr,"newdata[%d] != playerdata[%d], numkeys.%d %s pub.%s playertxid.%s good.%d bad.%d\n",(int32_t)newdata.size(),(int32_t)playerdata.size(),numkeys,rogueaddr,pubkey33_str(str2,(uint8_t *)&pk),playertxid.GetHex().c_str(),good,bad); + if ( gametxid != prevgame ) + { + prevgame = gametxid; + bad++; + fprintf(stderr,"%s playerdata: gold.%d hp.%d strength.%d/%d level.%d exp.%d dl.%d\n",gametxid.GetHex().c_str(),P.gold,P.hitpoints,P.strength&0xffff,P.strength>>16,P.level,P.experience,P.dungeonlevel); + fprintf(stderr,"newdata[%d] != playerdata[%d], numkeys.%d %s pub.%s playertxid.%s good.%d bad.%d\n",(int32_t)newdata.size(),(int32_t)playerdata.size(),numkeys,rogueaddr,pubkey33_str(str2,(uint8_t *)&pk),playertxid.GetHex().c_str(),good,bad); + } } //fprintf(stderr,"no keys rogue_extractgame %s\n",gametxid.GetHex().c_str()); return(-1); @@ -1308,7 +1329,7 @@ UniValue rogue_setname(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { - CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,maxplayers,decoded=0,regslot,ind,err,dispflag,gameheight,score,numvouts; CTransaction vintx,gametx; CPubKey pk; uint256 hashBlock,gametxid,tokenid,batontxid,playertxid,ptxid; int64_t buyin; std::vector playerdata,keystrokes; std::string symbol,pname; + CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,maxplayers,decoded=0,regslot,ind,err,dispflag,gameheight,score,numvouts; CTransaction vintx,gametx; CPubKey pk; uint256 hashBlock,gametxid,tokenid,batontxid,playertxid,ptxid; int64_t buyin,cashout; std::vector playerdata,keystrokes; std::string symbol,pname; if ( strcmp(ASSETCHAINS_SYMBOL,"ROGUE") == 0 && height < 21274 ) return(true); if ( (numvouts= tx.vout.size()) > 1 ) @@ -1393,10 +1414,14 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C // verify pk belongs to this tx if ( playerdata.size() > 0 ) { - if ( rogue_playerdata_validate(ptxid,cp,playerdata,gametxid,pk) < 0 ) + if ( rogue_playerdata_validate(&cashout,ptxid,cp,playerdata,gametxid,pk) < 0 ) { //fprintf(stderr,"ht.%d gametxid.%s player.%s invalid playerdata[%d]\n",height,gametxid.GetHex().c_str(),ptxid.GetHex().c_str(),(int32_t)playerdata.size()); - } //else fprintf(stderr,"ht.%d playertxid.%s validated\n",height,ptxid.GetHex().c_str()); + } + if ( funcid == 'H' ) + cashout *= 2; + if ( tx.vout.size() > 2 ) + fprintf(stderr,"ht.%d playertxid.%s cashout %.8f vs vout2 %.8f\n",height,ptxid.GetHex().c_str(),(double)cashout/COIN,(double)tx.vout[2].nValue/COIN); } if ( funcid == 'Q' ) { From 4a09d29d0ddb199b94ddb3a35352343085409487 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 22:57:10 -1100 Subject: [PATCH 381/390] +print --- src/cc/rogue_rpc.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 3d9b02115..f2b6b7986 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -518,7 +518,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke if ( active == zeroid || rogue_playerdata(cp,origplayergame,tid,pk,playerdata,symbol,pname,active) == 0 ) { txid = matchtx.GetHash(); - //fprintf(stderr,"scan forward active.%s spenttxid.%s\n",active.GetHex().c_str(),txid.GetHex().c_str()); + fprintf(stderr,"scan forward active.%s spenttxid.%s\n",active.GetHex().c_str(),txid.GetHex().c_str()); n = 0; while ( CCgettxout(txid,0,1) < 0 ) { @@ -532,6 +532,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke return(-2); } txid = spenttxid; + fprintf(stderr,"next txid.%s/v%d\n",txid.GetHex().c_str(),spentvini); if ( spentvini != 0 ) return(-3); if ( keystrokesp != 0 && myGetTransaction(spenttxid,spenttx,hashBlock) != 0 && spenttx.vout.size() >= 2 ) From c8d3d0c13b79ed62e56aeb51c2b377b3cc1b6f03 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 22:59:31 -1100 Subject: [PATCH 382/390] Test --- src/cc/rogue_rpc.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index f2b6b7986..23204e225 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -505,7 +505,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke } if ( matches == 1 ) { - if ( myIsutxo_spent(spenttxid,gametxid,maxplayers+i+1) < 0 ) + if ( 1 || myIsutxo_spent(spenttxid,gametxid,maxplayers+i+1) < 0 ) { numvouts = matchtx.vout.size(); //fprintf(stderr,"matchtxid.%s matches.%d numvouts.%d\n",matchtx.GetHash().GetHex().c_str(),matches,numvouts); @@ -576,7 +576,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke else { fprintf(stderr,"already played\n"); - return(-5); + return(-6); } } return(-1); From 957343c1f4fbf420f3ff534c34b3cd2604fb9239 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 23:01:02 -1100 Subject: [PATCH 383/390] Fix can't find baton error --- src/cc/rogue_rpc.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 23204e225..305b6cd8f 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -518,7 +518,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke if ( active == zeroid || rogue_playerdata(cp,origplayergame,tid,pk,playerdata,symbol,pname,active) == 0 ) { txid = matchtx.GetHash(); - fprintf(stderr,"scan forward active.%s spenttxid.%s\n",active.GetHex().c_str(),txid.GetHex().c_str()); + //fprintf(stderr,"scan forward active.%s spenttxid.%s\n",active.GetHex().c_str(),txid.GetHex().c_str()); n = 0; while ( CCgettxout(txid,0,1) < 0 ) { @@ -532,7 +532,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke return(-2); } txid = spenttxid; - fprintf(stderr,"next txid.%s/v%d\n",txid.GetHex().c_str(),spentvini); + //fprintf(stderr,"next txid.%s/v%d\n",txid.GetHex().c_str(),spentvini); if ( spentvini != 0 ) return(-3); if ( keystrokesp != 0 && myGetTransaction(spenttxid,spenttx,hashBlock) != 0 && spenttx.vout.size() >= 2 ) From 8fa093fad2fce1a3470f9374418493864c30620b Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 23:06:30 -1100 Subject: [PATCH 384/390] Test --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 305b6cd8f..4ce8a4748 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1417,7 +1417,7 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C { if ( rogue_playerdata_validate(&cashout,ptxid,cp,playerdata,gametxid,pk) < 0 ) { - //fprintf(stderr,"ht.%d gametxid.%s player.%s invalid playerdata[%d]\n",height,gametxid.GetHex().c_str(),ptxid.GetHex().c_str(),(int32_t)playerdata.size()); + fprintf(stderr,"ht.%d gametxid.%s player.%s invalid playerdata[%d]\n",height,gametxid.GetHex().c_str(),ptxid.GetHex().c_str(),(int32_t)playerdata.size()); } if ( funcid == 'H' ) cashout *= 2; From 9340287d340f9625e25f807d89858792161523d7 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 23:08:08 -1100 Subject: [PATCH 385/390] txid --- src/cc/rogue_rpc.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 4ce8a4748..d6a325fa1 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1330,11 +1330,12 @@ UniValue rogue_setname(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { - CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,maxplayers,decoded=0,regslot,ind,err,dispflag,gameheight,score,numvouts; CTransaction vintx,gametx; CPubKey pk; uint256 hashBlock,gametxid,tokenid,batontxid,playertxid,ptxid; int64_t buyin,cashout; std::vector playerdata,keystrokes; std::string symbol,pname; + CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,maxplayers,decoded=0,regslot,ind,err,dispflag,gameheight,score,numvouts; CTransaction vintx,gametx; CPubKey pk; uint256 hashBlock,gametxid,txid,tokenid,batontxid,playertxid,ptxid; int64_t buyin,cashout; std::vector playerdata,keystrokes; std::string symbol,pname; if ( strcmp(ASSETCHAINS_SYMBOL,"ROGUE") == 0 && height < 21274 ) return(true); if ( (numvouts= tx.vout.size()) > 1 ) { + txid = tx.GetHash(); scriptPubKey = tx.vout[numvouts-1].scriptPubKey; GetOpReturnData(scriptPubKey,vopret); if ( vopret.size() > 2 ) @@ -1422,7 +1423,7 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C if ( funcid == 'H' ) cashout *= 2; if ( tx.vout.size() > 2 ) - fprintf(stderr,"ht.%d playertxid.%s cashout %.8f vs vout2 %.8f\n",height,ptxid.GetHex().c_str(),(double)cashout/COIN,(double)tx.vout[2].nValue/COIN); + fprintf(stderr,"ht.%d txid.%s cashout %.8f vs vout2 %.8f\n",height,txid.GetHex().c_str(),(double)cashout/COIN,(double)tx.vout[2].nValue/COIN); } if ( funcid == 'Q' ) { From 9a9204085bbce2aa2441c0ed55e358ef7772c59d Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 23:18:35 -1100 Subject: [PATCH 386/390] -print --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index d6a325fa1..c8e37d161 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1422,7 +1422,7 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C } if ( funcid == 'H' ) cashout *= 2; - if ( tx.vout.size() > 2 ) + if ( tx.vout.size() > 3 ) // orig of 't' has 0 cashout fprintf(stderr,"ht.%d txid.%s cashout %.8f vs vout2 %.8f\n",height,txid.GetHex().c_str(),(double)cashout/COIN,(double)tx.vout[2].nValue/COIN); } if ( funcid == 'Q' ) From 208aff399794b5eecc5f4c4ac79d7b9536d8391e Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 25 Feb 2019 01:58:46 -1100 Subject: [PATCH 387/390] Skip revalidating playertxid for asset tx --- src/cc/rogue_rpc.cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index c8e37d161..d98a77711 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1406,6 +1406,16 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C break; } } + else // this is asset transaction, which means playerdata txid already confirmed + { + switch ( funcid ) + { + case 'H': // win + case 'Q': // bailout + return(true); + break; + } + } switch ( funcid ) { case 'R': // register From b711cfaee314f503d5897f14c1cf882eea5b450d Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 25 Feb 2019 02:18:53 -1100 Subject: [PATCH 388/390] Test --- src/cc/dilithium.c | 5 ++++- src/cc/rogue_rpc.cpp | 8 +++++--- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index c0ff8f274..9a9c4de71 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -3231,8 +3231,11 @@ UniValue dilithium_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params bool dilithium_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { - CPubKey destpub33; std::string handle; uint256 hashBlock,destpubtxid,checktxid; CTransaction vintx; int32_t numvouts,mlen,smlen=CRYPTO_BYTES+32; std::vector sig; uint8_t msg[32],msg2[CRYPTO_BYTES+32],pk[CRYPTO_PUBLICKEYBYTES]; + CPubKey destpub33; std::string handle; uint256 hashBlock,destpubtxid,checktxid; CTransaction vintx; int32_t numvouts,numvins,mlen,smlen=CRYPTO_BYTES+32; std::vector sig; uint8_t msg[32],msg2[CRYPTO_BYTES+32],pk[CRYPTO_PUBLICKEYBYTES]; // if all dilithium tx -> do multispend/send, else: + numvouts = tx.vout.size(); + numvins = tx.vin.size(); + if ( tx.vout.size() != 2 ) return eval->Invalid("numvouts != 2"); else if ( tx.vin.size() != 1 ) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index d98a77711..9accfe7f7 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1330,7 +1330,7 @@ UniValue rogue_setname(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { - CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,maxplayers,decoded=0,regslot,ind,err,dispflag,gameheight,score,numvouts; CTransaction vintx,gametx; CPubKey pk; uint256 hashBlock,gametxid,txid,tokenid,batontxid,playertxid,ptxid; int64_t buyin,cashout; std::vector playerdata,keystrokes; std::string symbol,pname; + CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid,tokentx=0; int32_t i,maxplayers,decoded=0,regslot,ind,err,dispflag,gameheight,score,numvouts; CTransaction vintx,gametx; CPubKey pk; uint256 hashBlock,gametxid,txid,tokenid,batontxid,playertxid,ptxid; int64_t buyin,cashout; std::vector playerdata,keystrokes; std::string symbol,pname; if ( strcmp(ASSETCHAINS_SYMBOL,"ROGUE") == 0 && height < 21274 ) return(true); if ( (numvouts= tx.vout.size()) > 1 ) @@ -1344,6 +1344,7 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C funcid = script[1]; if ( (e= script[0]) == EVAL_TOKENS ) { + tokentx = 1; if ( (funcid= rogue_highlanderopretdecode(gametxid,tokenid,regslot,pk,playerdata,symbol,pname,scriptPubKey)) == 0 ) { if ( (funcid= rogue_registeropretdecode(gametxid,tokenid,playertxid,scriptPubKey)) == 0 ) @@ -1408,13 +1409,14 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C } else // this is asset transaction, which means playerdata txid already confirmed { - switch ( funcid ) + fprintf(stderr,"ht.%d tokentx.%d funcid.(%c)\n",height,tokentx,funcid); + /*switch ( funcid ) { case 'H': // win case 'Q': // bailout return(true); break; - } + }*/ } switch ( funcid ) { From 6e51ad8984a21a9e6e34b6bd96012f47978a2b4a Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 25 Feb 2019 02:24:59 -1100 Subject: [PATCH 389/390] -print --- src/cc/rogue_rpc.cpp | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 9accfe7f7..88b669799 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1407,17 +1407,6 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C break; } } - else // this is asset transaction, which means playerdata txid already confirmed - { - fprintf(stderr,"ht.%d tokentx.%d funcid.(%c)\n",height,tokentx,funcid); - /*switch ( funcid ) - { - case 'H': // win - case 'Q': // bailout - return(true); - break; - }*/ - } switch ( funcid ) { case 'R': // register From 3ac0038a15b63d913863981a068dfe4bd6097a03 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 25 Feb 2019 02:41:02 -1100 Subject: [PATCH 390/390] Rescue cancelled warriors --- src/cc/rogue_rpc.cpp | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 88b669799..aee151530 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -472,12 +472,25 @@ int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,uint int32_t rogue_playerdataspend(CMutableTransaction &mtx,uint256 playertxid,int32_t vout,uint256 origplayergame) { - int64_t txfee = 10000; + int64_t txfee = 10000; CTransaction tx; uint256 hashBlock; if ( CCgettxout(playertxid,vout,1) == 1 ) // not sure if this is enough validation { mtx.vin.push_back(CTxIn(playertxid,vout,CScript())); return(0); - } else return(-1); + } + else + { + vout = 0; + if ( myGetTransaction(playertxid,tx,hashBlock) != 0 && tx.vout[vout].nValue == 1 && tx.vout[vout].scriptPubKey.IsPayToCryptoCondition() != 0 ) + { + if ( CCgettxout(playertxid,vout,1) == 1 ) // not sure if this is enough validation + { + mtx.vin.push_back(CTxIn(playertxid,vout,CScript())); + return(0); + } + } + return(-1); + } } int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **keystrokesp,int32_t &numkeys,int32_t ®slot,std::vector &playerdata,uint256 &batontxid,int32_t &batonvout,int64_t &batonvalue,int32_t &batonht,uint256 gametxid,CTransaction gametx,int32_t maxplayers,char *destaddr,int32_t &numplayers,std::string &symbol,std::string &pname)