Merge pull request #1113 from jl777/FSM

FSM
This commit is contained in:
jl777
2018-12-18 08:46:54 -11:00
committed by GitHub
16 changed files with 408 additions and 266 deletions

2
.gitignore vendored
View File

@@ -124,3 +124,5 @@ src/komodo-tx.exe
#output during builds, symbol tables?
*.dSYM
src/cryptoconditions/compile

View File

@@ -25,7 +25,7 @@ std::string ChannelOpen(uint64_t txfee,CPubKey destpub,int32_t numpayments,int64
std::string ChannelPayment(uint64_t txfee,uint256 opentxid,int64_t amount, uint256 secret);
std::string ChannelClose(uint64_t txfee,uint256 opentxid);
std::string ChannelRefund(uint64_t txfee,uint256 opentxid,uint256 closetxid);
UniValue ChannelsList();
// CCcustom
UniValue ChannelsInfo(uint256 opentxid);

View File

@@ -75,11 +75,11 @@ int64_t IsChannelsvout(struct CCcontract_info *cp,const CTransaction& tx,CPubKey
return(0);
}
int64_t IsChannelsMarkervout(struct CCcontract_info *cp,const CTransaction& tx,CPubKey srcpub,int32_t v)
int64_t IsChannelsMarkervout(struct CCcontract_info *cp,const CTransaction& tx,CPubKey pubkey,int32_t v)
{
char destaddr[65],ccaddr[65];
GetCCaddress(cp,ccaddr,srcpub);
GetCCaddress(cp,ccaddr,pubkey);
if ( tx.vout[v].scriptPubKey.IsPayToCryptoCondition() != 0 )
{
if ( Getscriptaddress(destaddr,tx.vout[v].scriptPubKey) > 0 && strcmp(destaddr,ccaddr) == 0 )
@@ -207,11 +207,11 @@ bool ChannelsValidate(struct CCcontract_info *cp,Eval* eval,const CTransaction &
return eval->Invalid("vin.1 is CC for channelPayment!");
else if ( IsCCInput(tx.vin[2].scriptSig) == 0 )
return eval->Invalid("vin.2 is CC for channelPayment!");
else if ( tx.vout[0].scriptPubKey.IsPayToCryptoCondition() == 0 )
else if ( IsChannelsvout(cp,tx,srcpub,destpub,0)==0 )
return eval->Invalid("vout.0 is CC for channelPayment!");
else if ( tx.vout[1].scriptPubKey.IsPayToCryptoCondition() == 0 )
else if ( IsChannelsMarkervout(cp,tx,srcpub,1)==0 )
return eval->Invalid("vout.1 is CC for channelPayment (marker to srcPub)!");
else if ( tx.vout[2].scriptPubKey.IsPayToCryptoCondition() == 0 )
else if ( IsChannelsMarkervout(cp,tx,destpub,2)==0 )
return eval->Invalid("vout.2 is CC for channelPayment (marker to dstPub)!");
else if ( tx.vout[3].scriptPubKey.IsPayToCryptoCondition() != 0 )
return eval->Invalid("vout.3 is normal for channelPayment!");
@@ -269,11 +269,11 @@ bool ChannelsValidate(struct CCcontract_info *cp,Eval* eval,const CTransaction &
return eval->Invalid("vin.1 is CC for channelClose!");
else if ( IsCCInput(tx.vin[2].scriptSig) == 0 )
return eval->Invalid("vin.2 is CC for channelClose!");
else if ( tx.vout[0].scriptPubKey.IsPayToCryptoCondition() == 0 )
else if ( IsChannelsvout(cp,tx,srcpub,destpub,0)==0 )
return eval->Invalid("vout.0 is CC for channelClose!");
else if ( tx.vout[1].scriptPubKey.IsPayToCryptoCondition() == 0 )
else if ( IsChannelsMarkervout(cp,tx,srcpub,1)==0 )
return eval->Invalid("vout.1 is CC for channelClose (marker to srcPub)!");
else if ( tx.vout[2].scriptPubKey.IsPayToCryptoCondition() == 0 )
else if ( IsChannelsMarkervout(cp,tx,destpub,2)==0 )
return eval->Invalid("vout.2 is CC for channelClose (marker to dstPub)!");
else if ( param1 > CHANNELS_MAXPAYMENTS)
return eval->Invalid("too many payment increments!");
@@ -314,9 +314,9 @@ bool ChannelsValidate(struct CCcontract_info *cp,Eval* eval,const CTransaction &
return eval->Invalid("vin.1 is CC for channelRefund!");
else if ( IsCCInput(tx.vin[2].scriptSig) == 0 )
return eval->Invalid("vin.2 is CC for channelRefund!");
else if ( tx.vout[0].scriptPubKey.IsPayToCryptoCondition() == 0 )
else if ( IsChannelsMarkervout(cp,tx,srcpub,0)==0 )
return eval->Invalid("vout.0 is CC for channelRefund (marker to srcPub)!");
else if ( tx.vout[1].scriptPubKey.IsPayToCryptoCondition() == 0 )
else if ( IsChannelsMarkervout(cp,tx,destpub,1)==0 )
return eval->Invalid("vout.1 is CC for channelRefund (marker to dstPub)!");
else if ( tx.vout[2].scriptPubKey.IsPayToCryptoCondition() != 0 )
return eval->Invalid("vout.2 is normal for channelRefund!");
@@ -366,12 +366,12 @@ bool ChannelsValidate(struct CCcontract_info *cp,Eval* eval,const CTransaction &
// helper functions for rpc calls in rpcwallet.cpp
int64_t AddChannelsInputs(struct CCcontract_info *cp,CMutableTransaction &mtx, CTransaction openTx, uint256 &prevtxid)
int64_t AddChannelsInputs(struct CCcontract_info *cp,CMutableTransaction &mtx, CTransaction openTx, uint256 &prevtxid, CPubKey mypk)
{
char coinaddr[65]; int64_t param2,totalinputs = 0,numvouts; uint256 txid=zeroid,tmp_txid,hashBlock,param3; CTransaction tx; int32_t param1;
char coinaddr[65]; int64_t param2,totalinputs = 0,numvouts; uint256 txid=zeroid,tmp_txid,hashBlock,param3; CTransaction tx; int32_t marker,param1;
std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> > unspentOutputs;
CPubKey srcpub,destpub;
uint8_t myprivkey[32];
uint8_t myprivkey[32];
if ((numvouts=openTx.vout.size()) > 0 && DecodeChannelsOpRet(openTx.vout[numvouts-1].scriptPubKey,tmp_txid,srcpub,destpub,param1,param2,param3)=='O')
{
@@ -383,14 +383,15 @@ int64_t AddChannelsInputs(struct CCcontract_info *cp,CMutableTransaction &mtx, C
fprintf(stderr,"invalid channel open txid\n");
return 0;
}
if (srcpub==mypk) marker=1;
else marker=2;
for (std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++)
{
if ( (int32_t)it->first.index==0 && GetTransaction(it->first.txhash,tx,hashBlock,false) != 0 && (numvouts=tx.vout.size()) > 0)
{
if (DecodeChannelsOpRet(tx.vout[numvouts-1].scriptPubKey,tmp_txid,srcpub,destpub,param1,param2,param3)!=0 &&
(tmp_txid==openTx.GetHash() || tx.GetHash()==openTx.GetHash()) &&
(totalinputs=IsChannelsvout(cp,tx,srcpub,destpub,0)+IsChannelsMarkervout(cp,tx,srcpub,1))>0)
(totalinputs=IsChannelsvout(cp,tx,srcpub,destpub,0)+IsChannelsMarkervout(cp,tx,srcpub,marker))>0)
{
txid = it->first.txhash;
break;
@@ -419,7 +420,7 @@ int64_t AddChannelsInputs(struct CCcontract_info *cp,CMutableTransaction &mtx, C
{
prevtxid=txid;
mtx.vin.push_back(CTxIn(txid,0,CScript()));
mtx.vin.push_back(CTxIn(txid,1,CScript()));
mtx.vin.push_back(CTxIn(txid,marker,CScript()));
Myprivkey(myprivkey);
CCaddr2set(cp,EVAL_CHANNELS,srcpub,myprivkey,coinaddr);
CCaddr3set(cp,EVAL_CHANNELS,destpub,myprivkey,coinaddr);
@@ -483,7 +484,7 @@ std::string ChannelPayment(uint64_t txfee,uint256 opentxid,int64_t amount, uint2
}
if (AddNormalinputs(mtx,mypk,2*txfee,3) > 0)
{
if ((funds=AddChannelsInputs(cp,mtx,channelOpenTx,prevtxid)) !=0 && (change=funds-amount-txfee)>=0)
if ((funds=AddChannelsInputs(cp,mtx,channelOpenTx,prevtxid,mypk)) !=0 && (change=funds-amount-txfee)>=0)
{
if ((numvouts=channelOpenTx.vout.size()) > 0 && DecodeChannelsOpRet(channelOpenTx.vout[numvouts-1].scriptPubKey, txid, srcpub, destpub, totalnumpayments, payment, hashchain)=='O')
{
@@ -553,11 +554,11 @@ std::string ChannelPayment(uint64_t txfee,uint256 opentxid,int64_t amount, uint2
fprintf(stderr, "invalid channel open tx\n");
return ("");
}
mtx.vout.push_back(MakeCC1of2vout(EVAL_CHANNELS, change, mypk, destpub));
mtx.vout.push_back(MakeCC1vout(EVAL_CHANNELS,txfee,mypk));
mtx.vout.push_back(MakeCC1of2vout(EVAL_CHANNELS, change, srcpub, destpub));
mtx.vout.push_back(MakeCC1vout(EVAL_CHANNELS,txfee,srcpub));
mtx.vout.push_back(MakeCC1vout(EVAL_CHANNELS,txfee,destpub));
mtx.vout.push_back(CTxOut(amount, CScript() << ParseHex(HexStr(destpub)) << OP_CHECKSIG));
return (FinalizeCCTx(0, cp, mtx, mypk, txfee, EncodeChannelsOpRet('P', opentxid, mypk, destpub, prevdepth-numpayments, numpayments, secret)));
return (FinalizeCCTx(0, cp, mtx, mypk, txfee, EncodeChannelsOpRet('P', opentxid, srcpub, destpub, prevdepth-numpayments, numpayments, secret)));
}
else
{
@@ -600,12 +601,12 @@ std::string ChannelClose(uint64_t txfee,uint256 opentxid)
}
if ( AddNormalinputs(mtx,mypk,2*txfee,3) > 0 )
{
if ((funds=AddChannelsInputs(cp,mtx,channelOpenTx,prevtxid)) !=0 && funds-txfee>0)
if ((funds=AddChannelsInputs(cp,mtx,channelOpenTx,prevtxid,mypk)) !=0 && funds-txfee>0)
{
mtx.vout.push_back(MakeCC1of2vout(EVAL_CHANNELS, funds-txfee, mypk, destpub));
mtx.vout.push_back(MakeCC1vout(EVAL_CHANNELS,txfee,mypk));
mtx.vout.push_back(MakeCC1vout(EVAL_CHANNELS,txfee,destpub));
return(FinalizeCCTx(0,cp,mtx,mypk,txfee,EncodeChannelsOpRet('C',opentxid,mypk,destpub,funds/payment,payment,zeroid)));
return(FinalizeCCTx(0,cp,mtx,mypk,txfee,EncodeChannelsOpRet('C',opentxid,mypk,destpub,(funds-txfee)/payment,payment,zeroid)));
}
else
{
@@ -664,7 +665,7 @@ std::string ChannelRefund(uint64_t txfee,uint256 opentxid,uint256 closetxid)
}
if ( AddNormalinputs(mtx,mypk,2*txfee,3) > 0 )
{
if ((funds=AddChannelsInputs(cp,mtx,channelOpenTx,prevtxid)) !=0 && funds-txfee>0)
if ((funds=AddChannelsInputs(cp,mtx,channelOpenTx,prevtxid,mypk)) !=0 && funds-txfee>0)
{
if ((GetTransaction(prevtxid,prevTx,hashblock,false) != 0) && (numvouts=prevTx.vout.size()) > 0 &&
DecodeChannelsOpRet(prevTx.vout[numvouts-1].scriptPubKey, txid, srcpub, destpub, param1, param2, param3) != 0)
@@ -696,84 +697,117 @@ std::string ChannelRefund(uint64_t txfee,uint256 opentxid,uint256 closetxid)
}
return("");
}
UniValue ChannelsInfo(uint256 channeltxid)
UniValue ChannelsList()
{
UniValue result(UniValue::VOBJ); CTransaction tx,opentx; uint256 txid,tmp_txid,hashBlock,param3,opentxid,hashchain,prevtxid;
struct CCcontract_info *cp,C; char myCCaddr[65],addr[65],str1[512],str2[256]; int32_t vout,numvouts,param1,numpayments;
int64_t nValue,param2,payment; CPubKey srcpub,destpub,mypk;
std::vector<std::pair<CAddressIndexKey, CAmount> > txids;
UniValue result(UniValue::VOBJ); std::vector<std::pair<CAddressIndexKey, CAmount> > txids; struct CCcontract_info *cp,C; uint256 txid,hashBlock,tmp_txid,param3;
CTransaction tx; char myCCaddr[65],addr[65],str[256]; CPubKey mypk,srcpub,destpub; int32_t vout,numvouts,param1;
int64_t nValue,param2;
result.push_back(Pair("result","success"));
cp = CCinit(&C,EVAL_CHANNELS);
mypk = pubkey2pk(Mypubkey());
if (channeltxid==zeroid)
GetCCaddress(cp,myCCaddr,mypk);
SetCCtxids(txids,myCCaddr);
result.push_back(Pair("result","success"));
result.push_back(Pair("name","Channels List"));
for (std::vector<std::pair<CAddressIndexKey, CAmount> >::const_iterator it=txids.begin(); it!=txids.end(); it++)
{
result.push_back(Pair("name","Channels Info"));
GetCCaddress(cp,myCCaddr,mypk);
SetCCtxids(txids,myCCaddr);
for (std::vector<std::pair<CAddressIndexKey, CAmount> >::const_iterator it=txids.begin(); it!=txids.end(); it++)
txid = it->first.txhash;
vout = (int32_t)it->first.index;
nValue = (int64_t)it->second;
if ( (vout == 1 || vout == 2) && nValue == 10000 && GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size()) > 0 )
{
//int height = it->first.blockHeight;
txid = it->first.txhash;
vout = (int32_t)it->first.index;
nValue = (int64_t)it->second;
if ( (vout == 1 || vout == 2) && nValue == 10000 && GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size()) > 0 )
{
if (DecodeChannelsOpRet(tx.vout[numvouts-1].scriptPubKey,tmp_txid,srcpub,destpub,param1,param2,param3) == 'O')
{
GetCCaddress1of2(cp,addr,srcpub,destpub);
sprintf(str1,"%s - %lld payments of %lld satoshi - %s",addr,(long long)param1,(long long)param2,tx.GetHash().ToString().c_str());
result.push_back(Pair("Channel", str1));
}
}
}
}
else
{
if (GetTransaction(channeltxid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size()) > 0 &&
(DecodeChannelsOpRet(tx.vout[numvouts-1].scriptPubKey,opentxid,srcpub,destpub,param1,param2,param3) == 'O'))
{
GetCCaddress1of2(cp,addr,srcpub,destpub);
sprintf(str1,"Channel %s",addr);
result.push_back(Pair("name",str1));
SetCCtxids(txids,addr);
prevtxid=zeroid;
for (std::vector<std::pair<CAddressIndexKey, CAmount> >::const_iterator it=txids.begin(); it!=txids.end(); it++)
{
txid = it->first.txhash;
if (txid!=prevtxid && GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size()) > 0 )
{
if (DecodeChannelsOpRet(tx.vout[numvouts-1].scriptPubKey,tmp_txid,srcpub,destpub,param1,param2,param3) == 'O' && tx.GetHash()==channeltxid)
{
sprintf(str1,"%lld payments of %lld satoshi",(long long)param1,(long long)param2);
result.push_back(Pair("Open", str1));
}
else if (DecodeChannelsOpRet(tx.vout[numvouts-1].scriptPubKey,opentxid,srcpub,destpub,param1,param2,param3) == 'P' && opentxid==channeltxid)
{
if (GetTransaction(opentxid,opentx,hashBlock,false) != 0 && (numvouts=opentx.vout.size()) > 0 &&
DecodeChannelsOpRet(opentx.vout[numvouts-1].scriptPubKey,tmp_txid,srcpub,destpub,numpayments,payment,hashchain) == 'O')
{
Getscriptaddress(str2,tx.vout[3].scriptPubKey);
sprintf(str1,"%lld satoshi to %s, %lld payments left",(long long)(param2*payment),str2,(long long)param1);
result.push_back(Pair("Payment",str1));
}
}
else if (DecodeChannelsOpRet(tx.vout[numvouts-1].scriptPubKey,opentxid,srcpub,destpub,param1,param2,param3) == 'C' && opentxid==channeltxid)
{
result.push_back(Pair("Close","channel"));
}
else if (DecodeChannelsOpRet(tx.vout[numvouts-1].scriptPubKey,opentxid,srcpub,destpub,param1,param2,param3) == 'R' && opentxid==channeltxid)
{
Getscriptaddress(str2,tx.vout[2].scriptPubKey);
sprintf(str1,"%lld satoshi back to %s",(long long)(param1*param2),str2);
result.push_back(Pair("Refund",str1));
}
}
prevtxid=txid;
if (DecodeChannelsOpRet(tx.vout[numvouts-1].scriptPubKey,tmp_txid,srcpub,destpub,param1,param2,param3) == 'O')
{
GetCCaddress1of2(cp,addr,srcpub,destpub);
sprintf(str,"%s - %lld payments of %lld satoshi",addr,(long long)param1,(long long)param2);
result.push_back(Pair(txid.GetHex().data(),str));
}
}
}
return(result);
}
UniValue ChannelsInfo(uint256 channeltxid)
{
UniValue result(UniValue::VOBJ),array(UniValue::VARR); CTransaction tx,opentx; uint256 txid,tmp_txid,hashBlock,param3,opentxid,hashchain,prevtxid;
struct CCcontract_info *cp,C; char CCaddr[65],addr[65],str[512]; int32_t vout,numvouts,param1,numpayments;
int64_t nValue,param2,payment; CPubKey srcpub,destpub,mypk;
std::vector<std::pair<CAddressIndexKey, CAmount> > addressIndex; std::vector<uint256> txids;
cp = CCinit(&C,EVAL_CHANNELS);
mypk = pubkey2pk(Mypubkey());
if (GetTransaction(channeltxid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size()) > 0 &&
(DecodeChannelsOpRet(tx.vout[numvouts-1].scriptPubKey,opentxid,srcpub,destpub,param1,param2,param3) == 'O'))
{
GetCCaddress(cp,CCaddr,mypk);
Getscriptaddress(addr,CScript() << ParseHex(HexStr(destpub)) << OP_CHECKSIG);
result.push_back(Pair("result","success"));
result.push_back(Pair("Channel CC address",CCaddr));
result.push_back(Pair("Destination address",addr));
result.push_back(Pair("Number of payments",param1));
result.push_back(Pair("Denomination",param2));
result.push_back(Pair("Amount",i64tostr(param1*param2)+" satoshi"));
SetCCtxids(addressIndex,CCaddr);
for (std::vector<std::pair<CAddressIndexKey, CAmount> >::const_iterator it=addressIndex.begin(); it!=addressIndex.end(); it++)
{
if (GetTransaction(it->first.txhash,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size()) > 0 )
if (DecodeChannelsOpRet(tx.vout[numvouts-1].scriptPubKey,tmp_txid,srcpub,destpub,param1,param2,param3)!=0 && (tmp_txid==channeltxid || tx.GetHash()==channeltxid))
txids.push_back(it->first.txhash);
}
BOOST_FOREACH(const CTxMemPoolEntry &e, mempool.mapTx)
{
const CTransaction &txmempool = e.GetTx();
const uint256 &hash = txmempool.GetHash();
if ((numvouts=txmempool.vout.size()) > 0 && DecodeChannelsOpRet(txmempool.vout[numvouts-1].scriptPubKey,tmp_txid,srcpub,destpub,param1,param2,param3) == 'P' && tmp_txid==channeltxid)
txids.push_back(hash);
}
prevtxid=zeroid;
for (std::vector<uint256>::const_iterator it=txids.begin(); it!=txids.end(); it++)
{
txid=*it;
if (txid!=prevtxid && GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size()) > 0 )
{
UniValue obj(UniValue::VOBJ);
if (DecodeChannelsOpRet(tx.vout[numvouts-1].scriptPubKey,tmp_txid,srcpub,destpub,param1,param2,param3) == 'O' && tx.GetHash()==channeltxid)
{
obj.push_back(Pair("Open",txid.GetHex().data()));
}
else if (DecodeChannelsOpRet(tx.vout[numvouts-1].scriptPubKey,opentxid,srcpub,destpub,param1,param2,param3) == 'P' && opentxid==channeltxid)
{
if (GetTransaction(opentxid,opentx,hashBlock,false) != 0 && (numvouts=opentx.vout.size()) > 0 &&
DecodeChannelsOpRet(opentx.vout[numvouts-1].scriptPubKey,tmp_txid,srcpub,destpub,numpayments,payment,hashchain) == 'O')
{
Getscriptaddress(str,tx.vout[3].scriptPubKey);
obj.push_back(Pair("Payment",txid.GetHex().data()));
obj.push_back(Pair("Number",param2));
obj.push_back(Pair("Amount",param2*payment));
obj.push_back(Pair("Destination",str));
obj.push_back(Pair("Secret",param3.ToString().c_str()));
}
}
else if (DecodeChannelsOpRet(tx.vout[numvouts-1].scriptPubKey,opentxid,srcpub,destpub,param1,param2,param3) == 'C' && opentxid==channeltxid)
{
obj.push_back(Pair("Close",txid.GetHex().data()));
}
else if (DecodeChannelsOpRet(tx.vout[numvouts-1].scriptPubKey,opentxid,srcpub,destpub,param1,param2,param3) == 'R' && opentxid==channeltxid)
{
Getscriptaddress(str,tx.vout[2].scriptPubKey);
obj.push_back(Pair("Refund",txid.GetHex().data()));
obj.push_back(Pair("Amount",param1*param2));
obj.push_back(Pair("Destination",str));
}
array.push_back(obj);
}
prevtxid=txid;
}
result.push_back(Pair("Transactions",array));
}
else
{
result.push_back(Pair("result","error"));
result.push_back(Pair("Error","Channel not found!"));
}
return(result);
}

View File

@@ -647,6 +647,25 @@ int64_t z_getbalance(char *refcoin,char *acname,char *coinaddr)
return (amount);
}
int32_t z_exportkey(char *privkey,char *refcoin,char *acname,char *zaddr)
{
cJSON *retjson; char *retstr,cmpstr[64]; int64_t amount=0;
privkey[0] = 0;
if ( (retjson= get_komodocli(refcoin,&retstr,acname,"z_exportkey",zaddr,"","","")) != 0 )
{
fprintf(stderr,"z_exportkey.(%s) %s returned json!\n",refcoin,acname);
free_json(retjson);
return(-1);
}
else if ( retstr != 0 )
{
//printf("retstr %s -> %.8f\n",retstr,dstr(amount));
strcpy(privkey,retstr);
free(retstr);
return(0);
}
}
int32_t getnewaddress(char *coinaddr,char *refcoin,char *acname)
{
cJSON *retjson; char *retstr; int64_t amount=0;
@@ -664,6 +683,23 @@ int32_t getnewaddress(char *coinaddr,char *refcoin,char *acname)
}
}
int32_t z_getnewaddress(char *coinaddr,char *refcoin,char *acname,char *typestr)
{
cJSON *retjson; char *retstr; int64_t amount=0;
if ( (retjson= get_komodocli(refcoin,&retstr,acname,"z_getnewaddress",typestr,"","","")) != 0 )
{
fprintf(stderr,"z_getnewaddress.(%s) %s returned json!\n",refcoin,acname);
free_json(retjson);
return(-1);
}
else if ( retstr != 0 )
{
strcpy(coinaddr,retstr);
free(retstr);
return(0);
}
}
int64_t find_onetime_amount(char *coinstr,char *coinaddr)
{
cJSON *array,*item; int32_t i,n; char *addr; int64_t amount = 0;
@@ -751,6 +787,39 @@ int32_t z_sendmany(char *opidstr,char *coinstr,char *acname,char *srcaddr,char *
}
}
int32_t z_mergetoaddress(char *opidstr,char *coinstr,char *acname,char *destaddr)
{
cJSON *retjson; char *retstr,addr[128],*opstr; int32_t retval = -1;
sprintf(addr,"[\\\"ANY_SPROUT\\\"]");
//printf("z_sendmany from.(%s) -> %s\n",addr,destaddr);
if ( (retjson= get_komodocli(coinstr,&retstr,acname,"z_mergetoaddress",addr,destaddr,"","")) != 0 )
{
/*{
"remainingUTXOs": 0,
"remainingTransparentValue": 0.00000000,
"remainingNotes": 222,
"remainingShieldedValue": 5413.39093055,
"mergingUTXOs": 0,
"mergingTransparentValue": 0.00000000,
"mergingNotes": 10,
"mergingShieldedValue": 822.47447172,
"opid": "opid-f28f6261-4120-436c-aca5-859870a40a70"
}*/
if ( (opstr= jstr(retjson,"opid")) != 0 )
strcpy(opidstr,opstr);
retval = jint(retjson,"remainingNotes");
fprintf(stderr,"%s\n",jprint(retjson,0));
free_json(retjson);
}
else if ( retstr != 0 )
{
fprintf(stderr,"z_mergetoaddress.(%s) -> opid.(%s)\n",coinstr,retstr);
strcpy(opidstr,retstr);
free(retstr);
}
return(retval);
}
int32_t empty_mempool(char *coinstr,char *acname)
{
cJSON *array; int32_t n;
@@ -907,10 +976,25 @@ int32_t main(int32_t argc,char **argv)
}
zsaddr = clonestr(argv[2]);
printf("%s: %s %s\n",REFCOIN_CLI,coinstr,zsaddr);
uint32_t lastopid; char coinaddr[64],zcaddr[128],opidstr[128]; int32_t finished; int64_t amount,stdamount,txfee;
uint32_t lastopid; char coinaddr[64],privkey[1024],zcaddr[128],opidstr[128]; int32_t finished; int64_t amount,stdamount,txfee;
//stdamount = 500 * SATOSHIDEN;
txfee = 10000;
again:
if ( z_getnewaddress(zcaddr,coinstr,"","sprout") == 0 )
{
z_exportkey(privkey,coinstr,"",zcaddr);
printf("zcaddr.(%s) -> z_exportkey.(%s)\n",zcaddr,privkey);
while ( 1 )
{
if ( have_pending_opid(coinstr,0) != 0 )
{
sleep(10);
continue;
}
if ( z_mergetoaddress(opidstr,coinstr,"",zcaddr) <= 0 )
break;
}
}
printf("start processing zmigrate\n");
lastopid = (uint32_t)time(NULL);
finished = 0;

View File

@@ -76,6 +76,7 @@ using namespace std;
extern void ThreadSendAlert();
extern int32_t KOMODO_LOADINGBLOCKS;
extern bool VERUS_MINTBLOCKS;
extern char ASSETCHAINS_SYMBOL[];
ZCJoinSplit* pzcashParams = NULL;
@@ -195,7 +196,10 @@ void Shutdown()
/// for example if the data directory was found to be locked.
/// Be sure that anything that writes files or flushes caches only does this if the respective
/// module was initialized.
RenameThread("verus-shutoff");
static char shutoffstr[128];
sprintf(shutoffstr,"%s-shutoff",ASSETCHAINS_SYMBOL);
//RenameThread("verus-shutoff");
RenameThread(shutoffstr);
mempool.AddTransactionsUpdated(1);
StopHTTPRPC();

View File

@@ -90,7 +90,7 @@ struct pax_transaction *komodo_paxmark(int32_t height,uint256 txid,uint16_t vout
pax->marked = mark;
//if ( height > 214700 || pax->height > 214700 )
// printf("mark ht.%d %.8f %.8f\n",pax->height,dstr(pax->komodoshis),dstr(pax->fiatoshis));
}
pthread_mutex_unlock(&komodo_mutex);
return(pax);
@@ -203,9 +203,9 @@ int32_t komodo_issued_opreturn(char *base,uint256 *txids,uint16_t *vouts,int64_t
// return(0);
incr = 34 + (iskomodo * (2*sizeof(fiatoshis) + 2*sizeof(height) + 20 + 4));
//41e77b91cb68dc2aa02fa88550eae6b6d44db676a7e935337b6d1392d9718f03cb0200305c90660400000000fbcbeb1f000000bde801006201000058e7945ad08ddba1eac9c9b6c8e1e97e8016a2d152
// 41e94d736ec69d88c08b5d238abeeca609c02357a8317e0d56c328bcb1c259be5d0200485bc80200000000404b4c000000000059470200b80b000061f22ba7d19fe29ac3baebd839af8b7127d1f9075553440046bb4cc7a3b5cd39dffe7206507a3482a00780e617f68b273cce9817ed69298d02001069ca1b0000000080f0fa02000000005b470200b90b000061f22ba7d19fe29ac3baebd839af8b7127d1f90755
//for (i=0; i<opretlen; i++)
// printf("%02x",opretbuf[i]);
//printf(" opretlen.%d (%s)\n",opretlen,base);
@@ -688,7 +688,7 @@ int32_t komodo_check_deposit(int32_t height,const CBlock& block,uint32_t prevtim
}
}
// we don't want these checks in VRSC, leave it at the Sapling upgrade
if ( ASSETCHAINS_SYMBOL[0] == 0 ||
if ( ASSETCHAINS_SYMBOL[0] == 0 ||
(ASSETCHAINS_COMMISSION != 0 && height > 1) ||
NetworkUpgradeActive(height, Params().GetConsensus(), Consensus::UPGRADE_SAPLING) )
{
@@ -740,6 +740,11 @@ int32_t komodo_check_deposit(int32_t height,const CBlock& block,uint32_t prevtim
else if ( height > 814000 )
{
script = (uint8_t *)&block.vtx[0].vout[0].scriptPubKey[0];
//int32_t notary = komodo_electednotary(&num,script+1,height,0);
//if ( (-1 * (komodo_electednotary(&num,script+1,height,0) >= 0) * (height > 1000000)) < 0 )
// fprintf(stderr, ">>>>>>> FAILED BLOCK.%d notary.%d insync.%d\n",height,notary,KOMODO_INSYNC);
//else
// fprintf(stderr, "<<<<<<< VALID BLOCK.%d notary.%d insync.%d\n",height,notary,KOMODO_INSYNC);
return(-1 * (komodo_electednotary(&num,script+1,height,0) >= 0) * (height > 1000000));
}
}
@@ -774,7 +779,7 @@ int32_t komodo_check_deposit(int32_t height,const CBlock& block,uint32_t prevtim
const char *komodo_opreturn(int32_t height,uint64_t value,uint8_t *opretbuf,int32_t opretlen,uint256 txid,uint16_t vout,char *source)
{
uint8_t rmd160[20],rmd160s[64*20],addrtype,shortflag,pubkey33[33]; int32_t didstats,i,j,n,kvheight,len,tokomodo,kmdheight,otherheights[64],kmdheights[64]; int8_t baseids[64]; char base[4],coinaddr[64],destaddr[64]; uint256 txids[64]; uint16_t vouts[64]; uint64_t convtoshis,seed; int64_t fee,fiatoshis,komodoshis,checktoshis,values[64],srcvalues[64]; struct pax_transaction *pax,*pax2; struct komodo_state *basesp; double diff;
uint8_t rmd160[20],rmd160s[64*20],addrtype,shortflag,pubkey33[33]; int32_t didstats,i,j,n,kvheight,len,tokomodo,kmdheight,otherheights[64],kmdheights[64]; int8_t baseids[64]; char base[4],coinaddr[64],destaddr[64]; uint256 txids[64]; uint16_t vouts[64]; uint64_t convtoshis,seed; int64_t fee,fiatoshis,komodoshis,checktoshis,values[64],srcvalues[64]; struct pax_transaction *pax,*pax2; struct komodo_state *basesp; double diff;
const char *typestr = "unknown";
if ( ASSETCHAINS_SYMBOL[0] != 0 && komodo_baseid(ASSETCHAINS_SYMBOL) < 0 && opretbuf[0] != 'K' )
{
@@ -1187,7 +1192,7 @@ void komodo_stateind_set(struct komodo_state *sp,uint32_t *inds,int32_t n,uint8_
printf("numR.%d numV.%d numN.%d count.%d\n",numR,numV,numN,count);
/*else if ( func == 'K' ) // KMD height: stop after 1st
else if ( func == 'T' ) // KMD height+timestamp: stop after 1st
else if ( func == 'N' ) // notarization, scan backwards 1440+ blocks;
else if ( func == 'V' ) // price feed: can stop after 1440+
else if ( func == 'R' ) // opreturn:*/
@@ -1521,4 +1526,3 @@ void komodo_passport_iteration()
printf("READY for %s RPC calls at %u! done PASSPORT %s refid.%d\n",ASSETCHAINS_SYMBOL,(uint32_t)time(NULL),ASSETCHAINS_SYMBOL,refid);
}
}

View File

@@ -4710,7 +4710,7 @@ bool CheckBlock(int32_t *futureblockp,int32_t height,CBlockIndex *pindex,const C
CValidationState state;
CTransaction Tx;
const CTransaction &tx = (CTransaction)block.vtx[i];
if (tx.IsCoinBase() || (!tx.vjoinsplit.empty() && !tx.vShieldedSpend.empty()) || ((i == (block.vtx.size() - 1)) && (ASSETCHAINS_STAKED && komodo_isPoS((CBlock *)&block) != 0)))
if (tx.IsCoinBase() || !tx.vjoinsplit.empty() || !tx.vShieldedSpend.empty() || ((i == (block.vtx.size() - 1)) && (ASSETCHAINS_STAKED && komodo_isPoS((CBlock *)&block) != 0)))
continue;
Tx = tx;
if ( myAddtomempool(Tx, &state, true) == false ) // happens with out of order tx in block on resync
@@ -4757,7 +4757,7 @@ bool CheckBlock(int32_t *futureblockp,int32_t height,CBlockIndex *pindex,const C
if (nSigOps > MAX_BLOCK_SIGOPS)
return state.DoS(100, error("CheckBlock: out-of-bounds SigOpCount"),
REJECT_INVALID, "bad-blk-sigops", true);
if ( komodo_check_deposit(height,block,(pindex==0||pindex->pprev==0)?0:pindex->pprev->nTime) < 0 )
if ( fCheckPOW && komodo_check_deposit(height,block,(pindex==0||pindex->pprev==0)?0:pindex->pprev->nTime) < 0 )
{
//static uint32_t counter;
//if ( counter++ < 100 && ASSETCHAINS_STAKED == 0 )

View File

@@ -1441,7 +1441,7 @@ void static BitcoinMiner()
#ifdef ENABLE_WALLET
// notaries always default to staking
CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey, pindexPrev->GetHeight()+1, gpucount, ASSETCHAINS_STAKED != 0 && GetArg("-genproclimit", 0) == 0);
CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey, pindexPrev->GetHeight()+1, gpucount, ASSETCHAINS_STAKED != 0 && GetArg("-genproclimit", -1) == 0);
#else
CBlockTemplate *ptr = CreateNewBlockWithKey();
#endif
@@ -1831,7 +1831,7 @@ void static BitcoinMiner()
}
//fprintf(stderr,"nThreads.%d fGenerate.%d\n",(int32_t)nThreads,fGenerate);
if ( ASSETCHAINS_STAKED > 0 && nThreads == 0 )
if ( ASSETCHAINS_STAKED > 0 && nThreads == 0 && fGenerate )
{
if ( pwallet != NULL )
nThreads = 1;

View File

@@ -339,22 +339,25 @@ UniValue setgenerate(const UniValue& params, bool fHelp)
//if (nGenProcLimit == 0)
// fGenerate = false;
}
if (fGenerate && !nGenProcLimit)
if ( ASSETCHAINS_LWMAPOS != 0 )
{
VERUS_MINTBLOCKS = 1;
fGenerate = GetBoolArg("-gen", false);
if ( ASSETCHAINS_STAKED == 0 )
nGenProcLimit = KOMODO_MININGTHREADS;
else
if (fGenerate && !nGenProcLimit)
{
VERUS_MINTBLOCKS = 1;
fGenerate = GetBoolArg("-gen", false);
KOMODO_MININGTHREADS = nGenProcLimit;
}
else if (!fGenerate)
{
VERUS_MINTBLOCKS = 0;
KOMODO_MININGTHREADS = 0;
}
else KOMODO_MININGTHREADS = (int32_t)nGenProcLimit;
}
else if (!fGenerate)
else
{
VERUS_MINTBLOCKS = 0;
KOMODO_MININGTHREADS = 0;
KOMODO_MININGTHREADS = (int32_t)nGenProcLimit;
}
else KOMODO_MININGTHREADS = (int32_t)nGenProcLimit;
mapArgs["-gen"] = (fGenerate ? "1" : "0");
mapArgs ["-genproclimit"] = itostr(KOMODO_MININGTHREADS);

View File

@@ -394,6 +394,7 @@ static const CRPCCommand vRPCCommands[] =
// Channels
{ "channels", "channelsaddress", &channelsaddress, true },
{ "channels", "channelslist", &channelslist, true },
{ "channels", "channelsinfo", &channelsinfo, true },
{ "channels", "channelsopen", &channelsopen, true },
{ "channels", "channelspayment", &channelspayment, true },

View File

@@ -271,6 +271,7 @@ extern UniValue gatewaysmarkdone(const UniValue& params, bool fHelp);
extern UniValue gatewayspending(const UniValue& params, bool fHelp);
extern UniValue gatewaysprocessed(const UniValue& params, bool fHelp);
extern UniValue gatewaysmultisig(const UniValue& params, bool fHelp);
extern UniValue channelslist(const UniValue& params, bool fHelp);
extern UniValue channelsinfo(const UniValue& params, bool fHelp);
extern UniValue channelsopen(const UniValue& params, bool fHelp);
extern UniValue channelspayment(const UniValue& params, bool fHelp);

View File

@@ -42,7 +42,7 @@ int mta_find_output(UniValue obj, int n)
if (!outputMapValue.isArray()) {
throw JSONRPCError(RPC_WALLET_ERROR, "Missing outputmap for JoinSplit operation");
}
UniValue outputMap = outputMapValue.get_array();
assert(outputMap.size() == ZC_NUM_JS_OUTPUTS);
for (size_t i = 0; i < outputMap.size(); i++) {
@@ -50,7 +50,7 @@ int mta_find_output(UniValue obj, int n)
return i;
}
}
throw std::logic_error("n is not present in outputmap");
}
@@ -69,33 +69,33 @@ saplingNoteInputs_(saplingNoteInputs), recipient_(recipient), fee_(fee), context
if (fee < 0 || fee > MAX_MONEY) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Fee is out of range");
}
if (utxoInputs.empty() && sproutNoteInputs.empty() && saplingNoteInputs.empty()) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "No inputs");
}
if (std::get<0>(recipient).size() == 0) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Recipient parameter missing");
}
if (sproutNoteInputs.size() > 0 && saplingNoteInputs.size() > 0) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot send from both Sprout and Sapling addresses using z_mergetoaddress");
}
if (sproutNoteInputs.size() > 0 && builder) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Sprout notes are not supported by the TransactionBuilder");
}
isUsingBuilder_ = false;
if (builder) {
isUsingBuilder_ = true;
builder_ = builder.get();
}
toTaddr_ = DecodeDestination(std::get<0>(recipient));
isToTaddr_ = IsValidDestination(toTaddr_);
isToZaddr_ = false;
if (!isToTaddr_) {
auto address = DecodePaymentAddress(std::get<0>(recipient));
if (IsValidPaymentAddress(address)) {
@@ -105,18 +105,18 @@ saplingNoteInputs_(saplingNoteInputs), recipient_(recipient), fee_(fee), context
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid recipient address");
}
}
// Log the context info i.e. the call parameters to z_mergetoaddress
if (LogAcceptCategory("zrpcunsafe")) {
LogPrint("zrpcunsafe", "%s: z_mergetoaddress initialized (params=%s)\n", getId(), contextInfo.write());
} else {
LogPrint("zrpc", "%s: z_mergetoaddress initialized\n", getId());
}
// Lock UTXOs
lock_utxos();
lock_notes();
// Enable payment disclosure if requested
paymentDisclosureMode = fExperimentalMode && GetBoolArg("-paymentdisclosure", true);
}
@@ -132,12 +132,12 @@ void AsyncRPCOperation_mergetoaddress::main()
unlock_notes();
return;
}
set_state(OperationStatus::EXECUTING);
start_execution_clock();
bool success = false;
#ifdef ENABLE_MINING
#ifdef ENABLE_WALLET
GenerateBitcoins(false, NULL, 0);
@@ -145,7 +145,7 @@ void AsyncRPCOperation_mergetoaddress::main()
GenerateBitcoins(false, 0);
#endif
#endif
try {
success = main_impl();
} catch (const UniValue& objError) {
@@ -166,7 +166,7 @@ void AsyncRPCOperation_mergetoaddress::main()
set_error_code(-2);
set_error_message("unknown error");
}
#ifdef ENABLE_MINING
#ifdef ENABLE_WALLET
GenerateBitcoins(GetBoolArg("-gen", false), pwalletMain, GetArg("-genproclimit", 1));
@@ -174,15 +174,15 @@ void AsyncRPCOperation_mergetoaddress::main()
GenerateBitcoins(GetBoolArg("-gen", false), GetArg("-genproclimit", 1));
#endif
#endif
stop_execution_clock();
if (success) {
set_state(OperationStatus::SUCCESS);
} else {
set_state(OperationStatus::FAILED);
}
std::string s = strprintf("%s: z_mergetoaddress finished (status=%s", getId(), getStateAsString());
if (success) {
s += strprintf(", txid=%s)\n", tx_.GetHash().ToString());
@@ -190,10 +190,10 @@ void AsyncRPCOperation_mergetoaddress::main()
s += strprintf(", error=%s)\n", getErrorMessage());
}
LogPrintf("%s", s);
unlock_utxos(); // clean up
unlock_notes(); // clean up
// !!! Payment disclosure START
if (success && paymentDisclosureMode && paymentDisclosureData_.size() > 0) {
uint256 txidhash = tx_.GetHash();
@@ -216,12 +216,12 @@ void AsyncRPCOperation_mergetoaddress::main()
bool AsyncRPCOperation_mergetoaddress::main_impl()
{
assert(isToTaddr_ != isToZaddr_);
bool isPureTaddrOnlyTx = (sproutNoteInputs_.empty() && saplingNoteInputs_.empty() && isToTaddr_);
CAmount minersFee = fee_;
size_t numInputs = utxoInputs_.size();
// Check mempooltxinputlimit to avoid creating a transaction which the local mempool rejects
size_t limit = (size_t)GetArg("-mempooltxinputlimit", 0);
{
@@ -235,31 +235,31 @@ bool AsyncRPCOperation_mergetoaddress::main_impl()
strprintf("Number of transparent inputs %d is greater than mempooltxinputlimit of %d",
numInputs, limit));
}
CAmount t_inputs_total = 0;
for (MergeToAddressInputUTXO& t : utxoInputs_) {
t_inputs_total += std::get<1>(t);
}
CAmount z_inputs_total = 0;
for (const MergeToAddressInputSproutNote& t : sproutNoteInputs_) {
z_inputs_total += std::get<2>(t);
}
for (const MergeToAddressInputSaplingNote& t : saplingNoteInputs_) {
z_inputs_total += std::get<2>(t);
}
CAmount targetAmount = z_inputs_total + t_inputs_total;
if (targetAmount <= minersFee) {
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS,
strprintf("Insufficient funds, have %s and miners fee is %s",
FormatMoney(targetAmount), FormatMoney(minersFee)));
}
CAmount sendAmount = targetAmount - minersFee;
// update the transaction with the UTXO inputs and output (if any)
if (!isUsingBuilder_) {
CMutableTransaction rawTx(tx_);
@@ -274,7 +274,7 @@ bool AsyncRPCOperation_mergetoaddress::main_impl()
}
tx_ = CTransaction(rawTx);
}
LogPrint(isPureTaddrOnlyTx ? "zrpc" : "zrpcunsafe", "%s: spending %s to send %s with fee %s\n",
getId(), FormatMoney(targetAmount), FormatMoney(sendAmount), FormatMoney(minersFee));
LogPrint("zrpc", "%s: transparent input: %s\n", getId(), FormatMoney(t_inputs_total));
@@ -285,13 +285,13 @@ bool AsyncRPCOperation_mergetoaddress::main_impl()
LogPrint("zrpcunsafe", "%s: private output: %s\n", getId(), FormatMoney(sendAmount));
}
LogPrint("zrpc", "%s: fee: %s\n", getId(), FormatMoney(minersFee));
// Grab the current consensus branch ID
{
LOCK(cs_main);
consensusBranchId_ = CurrentEpochBranchId(chainActive.Height() + 1, Params().GetConsensus());
}
/**
* SCENARIO #0
*
@@ -301,15 +301,15 @@ bool AsyncRPCOperation_mergetoaddress::main_impl()
*/
if (isUsingBuilder_) {
builder_.SetFee(minersFee);
for (const MergeToAddressInputUTXO& t : utxoInputs_) {
COutPoint outPoint = std::get<0>(t);
CAmount amount = std::get<1>(t);
CScript scriptPubKey = std::get<2>(t);
builder_.AddTransparentInput(outPoint, scriptPubKey, amount);
}
boost::optional<uint256> ovk;
// Select Sapling notes
std::vector<SaplingOutPoint> saplingOPs;
@@ -324,7 +324,7 @@ bool AsyncRPCOperation_mergetoaddress::main_impl()
ovk = expsk.full_viewing_key().ovk;
}
}
// Fetch Sapling anchor and witnesses
uint256 anchor;
std::vector<boost::optional<SaplingWitness>> witnesses;
@@ -332,7 +332,7 @@ bool AsyncRPCOperation_mergetoaddress::main_impl()
LOCK2(cs_main, pwalletMain->cs_wallet);
pwalletMain->GetSaplingNoteWitnesses(saplingOPs, witnesses, anchor);
}
// Add Sapling spends
for (size_t i = 0; i < saplingNotes.size(); i++) {
if (!witnesses[i]) {
@@ -340,7 +340,7 @@ bool AsyncRPCOperation_mergetoaddress::main_impl()
}
assert(builder_.AddSaplingSpend(expsks[i], saplingNotes[i], anchor, witnesses[i].get()));
}
if (isToTaddr_) {
if (!builder_.AddTransparentOutput(toTaddr_, sendAmount)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid output address, not a valid taddr.");
@@ -372,15 +372,15 @@ bool AsyncRPCOperation_mergetoaddress::main_impl()
}
builder_.AddSaplingOutput(ovk.get(), *saplingPaymentAddress, sendAmount, hexMemo);
}
// Build the transaction
auto maybe_tx = builder_.Build();
if (!maybe_tx) {
throw JSONRPCError(RPC_WALLET_ERROR, "Failed to build transaction.");
}
tx_ = maybe_tx.get();
// Send the transaction
// TODO: Use CWallet::CommitTransaction instead of sendrawtransaction
auto signedtxn = EncodeHexTx(tx_);
@@ -391,9 +391,9 @@ bool AsyncRPCOperation_mergetoaddress::main_impl()
if (sendResultValue.isNull()) {
throw JSONRPCError(RPC_WALLET_ERROR, "sendrawtransaction did not return an error or a txid.");
}
auto txid = sendResultValue.get_str();
UniValue o(UniValue::VOBJ);
o.push_back(Pair("txid", txid));
set_result(o);
@@ -405,14 +405,14 @@ bool AsyncRPCOperation_mergetoaddress::main_impl()
o.push_back(Pair("hex", signedtxn));
set_result(o);
}
return true;
}
/**
* END SCENARIO #0
*/
/**
* SCENARIO #1
*
@@ -429,16 +429,16 @@ bool AsyncRPCOperation_mergetoaddress::main_impl()
/**
* END SCENARIO #1
*/
// Prepare raw transaction to handle JoinSplits
CMutableTransaction mtx(tx_);
crypto_sign_keypair(joinSplitPubKey_.begin(), joinSplitPrivKey_);
mtx.joinSplitPubKey = joinSplitPubKey_;
tx_ = CTransaction(mtx);
std::string hexMemo = std::get<1>(recipient_);
/**
* SCENARIO #2
*
@@ -451,13 +451,13 @@ bool AsyncRPCOperation_mergetoaddress::main_impl()
MergeToAddressJSInfo info;
info.vpub_old = sendAmount;
info.vpub_new = 0;
JSOutput jso = JSOutput(boost::get<libzcash::SproutPaymentAddress>(toPaymentAddress_), sendAmount);
if (hexMemo.size() > 0) {
jso.memo = get_memo_from_hex_string(hexMemo);
}
info.vjsout.push_back(jso);
UniValue obj(UniValue::VOBJ);
obj = perform_joinsplit(info);
sign_send_raw_transaction(obj);
@@ -466,14 +466,14 @@ bool AsyncRPCOperation_mergetoaddress::main_impl()
/**
* END SCENARIO #2
*/
// Copy zinputs to more flexible containers
std::deque<MergeToAddressInputSproutNote> zInputsDeque;
for (const auto& o : sproutNoteInputs_) {
zInputsDeque.push_back(o);
}
// When spending notes, take a snapshot of note witnesses and anchors as the treestate will
// change upon arrival of new blocks which contain joinsplit transactions. This is likely
// to happen as creating a chained joinsplit transaction can take longer than the block interval.
@@ -488,7 +488,7 @@ bool AsyncRPCOperation_mergetoaddress::main_impl()
jsopWitnessAnchorMap[jso.ToString()] = MergeToAddressWitnessAnchorData{vInputWitnesses[0], inputAnchor};
}
}
/**
* SCENARIO #3
*
@@ -507,12 +507,12 @@ bool AsyncRPCOperation_mergetoaddress::main_impl()
int changeOutputIndex = -1; // this is updated after each joinsplit if jsChange > 0
bool vpubOldProcessed = false; // updated when vpub_old for taddr inputs is set in first joinsplit
bool vpubNewProcessed = false; // updated when vpub_new for miner fee and taddr outputs is set in last joinsplit
// At this point, we are guaranteed to have at least one input note.
// Use address of first input note as the temporary change address.
SproutSpendingKey changeKey = std::get<3>(zInputsDeque.front());
SproutPaymentAddress changeAddress = changeKey.address();
CAmount vpubOldTarget = 0;
CAmount vpubNewTarget = 0;
if (isToTaddr_) {
@@ -524,16 +524,16 @@ bool AsyncRPCOperation_mergetoaddress::main_impl()
vpubOldTarget = t_inputs_total - minersFee;
}
}
// Keep track of treestate within this transaction
boost::unordered_map<uint256, SproutMerkleTree, CCoinsKeyHasher> intermediates;
std::vector<uint256> previousCommitments;
while (!vpubNewProcessed) {
MergeToAddressJSInfo info;
info.vpub_old = 0;
info.vpub_new = 0;
// Set vpub_old in the first joinsplit
if (!vpubOldProcessed) {
if (t_inputs_total < vpubOldTarget) {
@@ -544,30 +544,30 @@ bool AsyncRPCOperation_mergetoaddress::main_impl()
info.vpub_old += vpubOldTarget; // funds flowing from public pool
vpubOldProcessed = true;
}
CAmount jsInputValue = 0;
uint256 jsAnchor;
std::vector<boost::optional<SproutWitness>> witnesses;
JSDescription prevJoinSplit;
// Keep track of previous JoinSplit and its commitments
if (tx_.vjoinsplit.size() > 0) {
prevJoinSplit = tx_.vjoinsplit.back();
}
// If there is no change, the chain has terminated so we can reset the tracked treestate.
if (jsChange == 0 && tx_.vjoinsplit.size() > 0) {
intermediates.clear();
previousCommitments.clear();
}
//
// Consume change as the first input of the JoinSplit.
//
if (jsChange > 0) {
LOCK2(cs_main, pwalletMain->cs_wallet);
// Update tree state with previous joinsplit
SproutMerkleTree tree;
auto it = intermediates.find(prevJoinSplit.anchor);
@@ -576,7 +576,7 @@ bool AsyncRPCOperation_mergetoaddress::main_impl()
} else if (!pcoinsTip->GetSproutAnchorAt(prevJoinSplit.anchor, tree)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Could not find previous JoinSplit anchor");
}
assert(changeOutputIndex != -1);
boost::optional<SproutWitness> changeWitness;
int n = 0;
@@ -594,7 +594,7 @@ bool AsyncRPCOperation_mergetoaddress::main_impl()
}
jsAnchor = tree.root();
intermediates.insert(std::make_pair(tree.root(), tree)); // chained js are interstitial (found in between block boundaries)
// Decrypt the change note's ciphertext to retrieve some data we need
ZCNoteDecryption decryptor(changeKey.receiving_key());
auto hSig = prevJoinSplit.h_sig(*pzcashParams, tx_.joinSplitPubKey);
@@ -605,23 +605,23 @@ bool AsyncRPCOperation_mergetoaddress::main_impl()
prevJoinSplit.ephemeralKey,
hSig,
(unsigned char)changeOutputIndex);
SproutNote note = plaintext.note(changeAddress);
info.notes.push_back(note);
info.zkeys.push_back(changeKey);
jsInputValue += plaintext.value();
LogPrint("zrpcunsafe", "%s: spending change (amount=%s)\n",
getId(),
FormatMoney(plaintext.value()));
} catch (const std::exception& e) {
throw JSONRPCError(RPC_WALLET_ERROR, strprintf("Error decrypting output note of previous JoinSplit: %s", e.what()));
}
}
//
// Consume spendable non-change notes
//
@@ -638,7 +638,7 @@ bool AsyncRPCOperation_mergetoaddress::main_impl()
CAmount noteFunds = std::get<2>(t);
SproutSpendingKey zkey = std::get<3>(t);
zInputsDeque.pop_front();
MergeToAddressWitnessAnchorData wad = jsopWitnessAnchorMap[jso.ToString()];
vInputWitnesses.push_back(wad.witness);
if (inputAnchor.IsNull()) {
@@ -646,13 +646,13 @@ bool AsyncRPCOperation_mergetoaddress::main_impl()
} else if (inputAnchor != wad.anchor) {
throw JSONRPCError(RPC_WALLET_ERROR, "Selected input notes do not share the same anchor");
}
vOutPoints.push_back(jso);
vInputNotes.push_back(note);
vInputZKeys.push_back(zkey);
jsInputValue += noteFunds;
int wtxHeight = -1;
int wtxDepth = -1;
{
@@ -674,13 +674,13 @@ bool AsyncRPCOperation_mergetoaddress::main_impl()
wtxHeight,
wtxDepth);
}
// Add history of previous commitments to witness
if (vInputNotes.size() > 0) {
if (vInputWitnesses.size() == 0) {
throw JSONRPCError(RPC_WALLET_ERROR, "Could not find witness for note commitment");
}
for (auto& optionalWitness : vInputWitnesses) {
if (!optionalWitness) {
throw JSONRPCError(RPC_WALLET_ERROR, "Witness for note commitment is null");
@@ -696,20 +696,20 @@ bool AsyncRPCOperation_mergetoaddress::main_impl()
}
witnesses.push_back(w);
}
// The jsAnchor is null if this JoinSplit is at the start of a new chain
if (jsAnchor.IsNull()) {
jsAnchor = inputAnchor;
}
// Add spendable notes as inputs
std::copy(vInputNotes.begin(), vInputNotes.end(), std::back_inserter(info.notes));
std::copy(vInputZKeys.begin(), vInputZKeys.end(), std::back_inserter(info.zkeys));
}
// Accumulate change
jsChange = jsInputValue + info.vpub_old;
// Set vpub_new in the last joinsplit (when there are no more notes to spend)
if (zInputsDeque.empty()) {
assert(!vpubNewProcessed);
@@ -724,10 +724,10 @@ bool AsyncRPCOperation_mergetoaddress::main_impl()
// If we are merging to a t-addr, there should be no change
if (isToTaddr_) assert(jsChange == 0);
}
// create dummy output
info.vjsout.push_back(JSOutput()); // dummy output while we accumulate funds into a change note for vpub_new
// create output for any change
if (jsChange > 0) {
std::string outputType = "change";
@@ -741,24 +741,24 @@ bool AsyncRPCOperation_mergetoaddress::main_impl()
}
}
info.vjsout.push_back(jso);
LogPrint("zrpcunsafe", "%s: generating note for %s (amount=%s)\n",
getId(),
outputType,
FormatMoney(jsChange));
}
obj = perform_joinsplit(info, witnesses, jsAnchor);
if (jsChange > 0) {
changeOutputIndex = mta_find_output(obj, 1);
}
}
// Sanity check in case changes to code block above exits loop by invoking 'break'
assert(zInputsDeque.size() == 0);
assert(vpubNewProcessed);
sign_send_raw_transaction(obj);
return true;
}
@@ -778,7 +778,7 @@ void AsyncRPCOperation_mergetoaddress::sign_send_raw_transaction(UniValue obj)
throw JSONRPCError(RPC_WALLET_ERROR, "Missing hex data for raw transaction");
}
std::string rawtxn = rawtxnValue.get_str();
UniValue params = UniValue(UniValue::VARR);
params.push_back(rawtxn);
UniValue signResultValue = signrawtransaction(params, false);
@@ -789,13 +789,13 @@ void AsyncRPCOperation_mergetoaddress::sign_send_raw_transaction(UniValue obj)
// TODO: #1366 Maybe get "errors" and print array vErrors into a string
throw JSONRPCError(RPC_WALLET_ENCRYPTION_FAILED, "Failed to sign transaction");
}
UniValue hexValue = find_value(signResultObject, "hex");
if (hexValue.isNull()) {
throw JSONRPCError(RPC_WALLET_ERROR, "Missing hex data for signed transaction");
}
std::string signedtxn = hexValue.get_str();
// Send the signed transaction
if (!testmode) {
params.clear();
@@ -805,26 +805,26 @@ void AsyncRPCOperation_mergetoaddress::sign_send_raw_transaction(UniValue obj)
if (sendResultValue.isNull()) {
throw JSONRPCError(RPC_WALLET_ERROR, "Send raw transaction did not return an error or a txid.");
}
std::string txid = sendResultValue.get_str();
UniValue o(UniValue::VOBJ);
o.push_back(Pair("txid", txid));
set_result(o);
} else {
// Test mode does not send the transaction to the network.
CDataStream stream(ParseHex(signedtxn), SER_NETWORK, PROTOCOL_VERSION);
CTransaction tx;
stream >> tx;
UniValue o(UniValue::VOBJ);
o.push_back(Pair("test", 1));
o.push_back(Pair("txid", tx.GetHash().ToString()));
o.push_back(Pair("hex", signedtxn));
set_result(o);
}
// Keep the signed transaction so we can hash to the same txid
CDataStream stream(ParseHex(signedtxn), SER_NETWORK, PROTOCOL_VERSION);
CTransaction tx;
@@ -864,52 +864,52 @@ UniValue AsyncRPCOperation_mergetoaddress::perform_joinsplit(
if (anchor.IsNull()) {
throw std::runtime_error("anchor is null");
}
if (witnesses.size() != info.notes.size()) {
throw runtime_error("number of notes and witnesses do not match");
}
if (info.notes.size() != info.zkeys.size()) {
throw runtime_error("number of notes and spending keys do not match");
}
for (size_t i = 0; i < witnesses.size(); i++) {
if (!witnesses[i]) {
throw runtime_error("joinsplit input could not be found in tree");
}
info.vjsin.push_back(JSInput(*witnesses[i], info.notes[i], info.zkeys[i]));
}
// Make sure there are two inputs and two outputs
while (info.vjsin.size() < ZC_NUM_JS_INPUTS) {
info.vjsin.push_back(JSInput());
}
while (info.vjsout.size() < ZC_NUM_JS_OUTPUTS) {
info.vjsout.push_back(JSOutput());
}
if (info.vjsout.size() != ZC_NUM_JS_INPUTS || info.vjsin.size() != ZC_NUM_JS_OUTPUTS) {
throw runtime_error("unsupported joinsplit input/output counts");
}
CMutableTransaction mtx(tx_);
LogPrint("zrpcunsafe", "%s: creating joinsplit at index %d (vpub_old=%s, vpub_new=%s, in[0]=%s, in[1]=%s, out[0]=%s, out[1]=%s)\n",
getId(),
tx_.vjoinsplit.size(),
FormatMoney(info.vpub_old), FormatMoney(info.vpub_new),
FormatMoney(info.vjsin[0].note.value()), FormatMoney(info.vjsin[1].note.value()),
FormatMoney(info.vjsout[0].value), FormatMoney(info.vjsout[1].value));
// Generate the proof, this can take over a minute.
std::array<libzcash::JSInput, ZC_NUM_JS_INPUTS> inputs{info.vjsin[0], info.vjsin[1]};
std::array<libzcash::JSOutput, ZC_NUM_JS_OUTPUTS> outputs{info.vjsout[0], info.vjsout[1]};
std::array<size_t, ZC_NUM_JS_INPUTS> inputMap;
std::array<size_t, ZC_NUM_JS_OUTPUTS> outputMap;
uint256 esk; // payment disclosure - secret
JSDescription jsdesc = JSDescription::Randomized(
mtx.fOverwintered && (mtx.nVersion >= SAPLING_TX_VERSION),
*pzcashParams,
@@ -929,34 +929,34 @@ UniValue AsyncRPCOperation_mergetoaddress::perform_joinsplit(
throw std::runtime_error("error verifying joinsplit");
}
}
mtx.vjoinsplit.push_back(jsdesc);
// Empty output script.
CScript scriptCode;
CTransaction signTx(mtx);
uint256 dataToBeSigned = SignatureHash(scriptCode, signTx, NOT_AN_INPUT, SIGHASH_ALL, 0, consensusBranchId_);
// Add the signature
if (!(crypto_sign_detached(&mtx.joinSplitSig[0], NULL,
dataToBeSigned.begin(), 32,
joinSplitPrivKey_) == 0)) {
throw std::runtime_error("crypto_sign_detached failed");
}
// Sanity check
if (!(crypto_sign_verify_detached(&mtx.joinSplitSig[0],
dataToBeSigned.begin(), 32,
mtx.joinSplitPubKey.begin()) == 0)) {
throw std::runtime_error("crypto_sign_verify_detached failed");
}
CTransaction rawTx(mtx);
tx_ = rawTx;
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << rawTx;
std::string encryptedNote1;
std::string encryptedNote2;
{
@@ -965,7 +965,7 @@ UniValue AsyncRPCOperation_mergetoaddress::perform_joinsplit(
ss2 << jsdesc.ephemeralKey;
ss2 << jsdesc.ciphertexts[0];
ss2 << jsdesc.h_sig(*pzcashParams, joinSplitPubKey_);
encryptedNote1 = HexStr(ss2.begin(), ss2.end());
}
{
@@ -974,10 +974,10 @@ UniValue AsyncRPCOperation_mergetoaddress::perform_joinsplit(
ss2 << jsdesc.ephemeralKey;
ss2 << jsdesc.ciphertexts[1];
ss2 << jsdesc.h_sig(*pzcashParams, joinSplitPubKey_);
encryptedNote2 = HexStr(ss2.begin(), ss2.end());
}
UniValue arrInputMap(UniValue::VARR);
UniValue arrOutputMap(UniValue::VARR);
for (size_t i = 0; i < ZC_NUM_JS_INPUTS; i++) {
@@ -986,8 +986,8 @@ UniValue AsyncRPCOperation_mergetoaddress::perform_joinsplit(
for (size_t i = 0; i < ZC_NUM_JS_OUTPUTS; i++) {
arrOutputMap.push_back(static_cast<uint64_t>(outputMap[i]));
}
// !!! Payment disclosure START
unsigned char buffer[32] = {0};
memcpy(&buffer[0], &joinSplitPrivKey_[0], 32); // private key in first half of 64 byte buffer
@@ -1003,11 +1003,11 @@ UniValue AsyncRPCOperation_mergetoaddress::perform_joinsplit(
libzcash::SproutPaymentAddress zaddr = output.addr; // randomized output
PaymentDisclosureInfo pdInfo = {PAYMENT_DISCLOSURE_VERSION_EXPERIMENTAL, esk, joinSplitPrivKey, zaddr};
paymentDisclosureData_.push_back(PaymentDisclosureKeyInfo(pdKey, pdInfo));
LogPrint("paymentdisclosure", "%s: Payment Disclosure: js=%d, n=%d, zaddr=%s\n", getId(), js_index, int(mapped_index), EncodePaymentAddress(zaddr));
}
// !!! Payment disclosure END
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("encryptednote1", encryptedNote1));
obj.push_back(Pair("encryptednote2", encryptedNote2));
@@ -1020,19 +1020,19 @@ UniValue AsyncRPCOperation_mergetoaddress::perform_joinsplit(
std::array<unsigned char, ZC_MEMO_SIZE> AsyncRPCOperation_mergetoaddress::get_memo_from_hex_string(std::string s)
{
std::array<unsigned char, ZC_MEMO_SIZE> memo = {{0x00}};
std::vector<unsigned char> rawMemo = ParseHex(s.c_str());
// If ParseHex comes across a non-hex char, it will stop but still return results so far.
size_t slen = s.length();
if (slen % 2 != 0 || (slen > 0 && rawMemo.size() != slen / 2)) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Memo must be in hexadecimal format");
}
if (rawMemo.size() > ZC_MEMO_SIZE) {
throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Memo size of %d is too big, maximum allowed is %d", rawMemo.size(), ZC_MEMO_SIZE));
}
// copy vector into boost array
int lenMemo = rawMemo.size();
for (int i = 0; i < ZC_MEMO_SIZE && i < lenMemo; i++) {
@@ -1050,7 +1050,7 @@ UniValue AsyncRPCOperation_mergetoaddress::getStatus() const
if (contextinfo_.isNull()) {
return v;
}
UniValue obj = v.get_obj();
obj.push_back(Pair("method", "z_mergetoaddress"));
obj.push_back(Pair("params", contextinfo_));

View File

@@ -169,9 +169,9 @@ void AsyncRPCOperation_sendmany::main() {
#ifdef ENABLE_MINING
#ifdef ENABLE_WALLET
GenerateBitcoins(GetBoolArg("-gen",false), pwalletMain, GetArg("-genproclimit", 0));
GenerateBitcoins(GetBoolArg("-gen",false), pwalletMain, GetArg("-genproclimit", 1));
#else
GenerateBitcoins(GetBoolArg("-gen",false), GetArg("-genproclimit", 0));
GenerateBitcoins(GetBoolArg("-gen",false), GetArg("-genproclimit", 1));
#endif
#endif
@@ -807,9 +807,9 @@ bool AsyncRPCOperation_sendmany::main_impl() {
vOutPoints.push_back(jso);
vInputNotes.push_back(note);
jsInputValue += noteFunds;
int wtxHeight = -1;
int wtxDepth = -1;
{
@@ -832,14 +832,14 @@ bool AsyncRPCOperation_sendmany::main_impl() {
wtxDepth
);
}
// Add history of previous commitments to witness
if (vInputNotes.size() > 0) {
if (vInputWitnesses.size()==0) {
throw JSONRPCError(RPC_WALLET_ERROR, "Could not find witness for note commitment");
}
for (auto & optionalWitness : vInputWitnesses) {
if (!optionalWitness) {
throw JSONRPCError(RPC_WALLET_ERROR, "Witness for note commitment is null");
@@ -1061,7 +1061,7 @@ bool AsyncRPCOperation_sendmany::find_utxos(bool fAcceptCoinbase=false) {
continue;
CAmount nValue = out.tx->vout[out.i].nValue;
SendManyInputUTXO utxo(out.tx->GetHash(), out.i, nValue, isCoinbase, dest);
t_inputs_.push_back(utxo);
}
@@ -1368,7 +1368,7 @@ void AsyncRPCOperation_sendmany::add_taddr_change_output_to_tx(CBitcoinAddress *
std::array<unsigned char, ZC_MEMO_SIZE> AsyncRPCOperation_sendmany::get_memo_from_hex_string(std::string s) {
// initialize to default memo (no_memo), see section 5.5 of the protocol spec
std::array<unsigned char, ZC_MEMO_SIZE> memo = {{0xF6}};
std::vector<unsigned char> rawMemo = ParseHex(s.c_str());
// If ParseHex comes across a non-hex char, it will stop but still return results so far.

View File

@@ -141,9 +141,9 @@ void AsyncRPCOperation_shieldcoinbase::main() {
#ifdef ENABLE_MINING
#ifdef ENABLE_WALLET
GenerateBitcoins(GetBoolArg("-gen",false), pwalletMain, GetArg("-genproclimit", 0));
GenerateBitcoins(GetBoolArg("-gen",false), pwalletMain, GetArg("-genproclimit", 1));
#else
GenerateBitcoins(GetBoolArg("-gen",false), GetArg("-genproclimit", 0));
GenerateBitcoins(GetBoolArg("-gen",false), GetArg("-genproclimit", 1));
#endif
#endif

View File

@@ -4788,9 +4788,9 @@ UniValue z_mergetoaddress(const UniValue& params, bool fHelp)
if (useAnySprout || useAnySapling || zaddrs.size() > 0) {
// Get available notes
std::vector<CSproutNotePlaintextEntry> sproutEntries;
std::vector<SaplingNoteEntry> saplingEntries;
pwalletMain->GetFilteredNotes(sproutEntries, saplingEntries, zaddrs);
std::vector<CSproutNotePlaintextEntry> sproutEntries,skipsprout;
std::vector<SaplingNoteEntry> saplingEntries,skipsapling;
pwalletMain->GetFilteredNotes(sproutEntries, useAnySprout == 0 ? saplingEntries : skipsapling, zaddrs);
// If Sapling is not active, do not allow sending from a sapling addresses.
if (!saplingActive && saplingEntries.size() > 0) {
@@ -5672,6 +5672,15 @@ UniValue tokenaddress(const UniValue& params, bool fHelp)
return(CCaddress(cp,(char *)"Assets",pubkey));
}
UniValue channelslist(const UniValue& params, bool fHelp)
{
if ( fHelp || params.size() > 0 )
throw runtime_error("channelsinfo\n");
if ( ensure_CCrequirements() < 0 )
throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n");
return(ChannelsList());
}
UniValue channelsinfo(const UniValue& params, bool fHelp)
{
uint256 opentxid;

View File

@@ -63,8 +63,8 @@ void post_wallet_load(){
#ifdef ENABLE_MINING
// Generate coins in the background
if (pwalletMain || !GetArg("-mineraddress", "").empty())
GenerateBitcoins(GetBoolArg("-gen", false), pwalletMain, GetArg("-genproclimit", 0));
#endif
GenerateBitcoins(GetBoolArg("-gen", false), pwalletMain, GetArg("-genproclimit", 1));
#endif
}