Browse Source

Merge branch 'dev' into master

pull/4/head
Asher Dawes 6 years ago
committed by GitHub
parent
commit
64cdd60ea3
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 1
      COPYING
  2. 32
      README-mac.md
  3. 2
      README.md
  4. 140
      contrib/debian/examples/komodo.conf
  5. 885
      contrib/seeds/nodes_main.txt
  6. 4
      darwin.host.mk.patch
  7. 8
      darwin.mk.patch
  8. 8
      depends/builders/darwin.mk
  9. 4
      depends/hosts/darwin.mk
  10. 2
      depends/packages/libgmp.mk
  11. 1
      depends/packages/librustzcash.mk
  12. 2
      libsnark.mk.patch
  13. 61
      migratecoin.md
  14. 22
      src/Makefile.am
  15. 6
      src/Makefile.ktest.include
  16. 1
      src/Makefile.test.include
  17. 2
      src/ac/dsec
  18. 2
      src/ac/eql
  19. 2
      src/ac/glxt
  20. 2
      src/amount.cpp
  21. 63
      src/assetchains
  22. 135
      src/assetchains.json
  23. 72
      src/assetchains.old
  24. 41
      src/assetchains_stop
  25. 12
      src/bitcoind.cpp
  26. 65
      src/cc/CCassets.h
  27. 478
      src/cc/CCassetsCore.cpp
  28. 472
      src/cc/CCassetstx.cpp
  29. 30
      src/cc/CCauction.h
  30. 195
      src/cc/CCcustom.cpp
  31. 17
      src/cc/CCcustom.inc
  32. 32
      src/cc/CCdice.h
  33. 30
      src/cc/CCfaucet.h
  34. 82
      src/cc/CCinclude.h
  35. 29
      src/cc/CClotto.h
  36. 29
      src/cc/CCponzi.h
  37. 33
      src/cc/CCrewards.h
  38. 235
      src/cc/CCtx.cpp
  39. 298
      src/cc/CCutils.cpp
  40. 367
      src/cc/assets.cpp
  41. 203
      src/cc/auction.cpp
  42. 164
      src/cc/betprotocol.cpp
  43. 27
      src/cc/betprotocol.h
  44. 512
      src/cc/dice.cpp
  45. 84
      src/cc/disputepayout.cpp
  46. 149
      src/cc/eval.cpp
  47. 197
      src/cc/eval.h
  48. 190
      src/cc/faucet.cpp
  49. 90
      src/cc/import.cpp
  50. 76
      src/cc/importpayout.cpp
  51. 183
      src/cc/lotto.cpp
  52. 183
      src/cc/ponzi.cpp
  53. 553
      src/cc/rewards.cpp
  54. 0
      src/cc/utils.cpp
  55. 49
      src/cc/utils.h
  56. 5
      src/chain.h
  57. 16
      src/chainparams.cpp
  58. 6
      src/chainparamsseeds.h
  59. 13
      src/coins.cpp
  60. 336
      src/crosschain.cpp
  61. 21
      src/crosschain.h
  62. 14
      src/cryptoconditions/src/anon.c
  63. 15
      src/cryptoconditions/src/cryptoconditions.c
  64. 15
      src/cryptoconditions/src/ed25519.c
  65. 15
      src/cryptoconditions/src/eval.c
  66. 15
      src/cryptoconditions/src/internal.h
  67. 15
      src/cryptoconditions/src/json_rpc.c
  68. 14
      src/cryptoconditions/src/prefix.c
  69. 14
      src/cryptoconditions/src/preimage.c
  70. 14
      src/cryptoconditions/src/threshold.c
  71. 15
      src/cryptoconditions/src/utils.c
  72. 8
      src/deprecation.h
  73. 11
      src/dpowassets
  74. 36
      src/fiat-cli
  75. 2
      src/fiat/dsec
  76. 2
      src/fiat/eql
  77. 2
      src/fiat/glxt
  78. 2
      src/fiat/rfox
  79. 2
      src/fiat/sec
  80. 2
      src/fiat/vrsc
  81. 2
      src/fiat/zilla
  82. 121
      src/importcoin.cpp
  83. 28
      src/importcoin.h
  84. 15
      src/init.cpp
  85. 59
      src/komodo.h
  86. 517
      src/komodo_bitcoind.h
  87. 46
      src/komodo_ccdata.h
  88. 2
      src/komodo_defs.h
  89. 6
      src/komodo_events.h
  90. 27
      src/komodo_gateway.h
  91. 10
      src/komodo_globals.h
  92. 4
      src/komodo_interest.h
  93. 2
      src/komodo_jumblr.h
  94. 15
      src/komodo_kv.h
  95. 23
      src/komodo_notary.h
  96. 4
      src/komodo_pax.h
  97. 20
      src/komodo_port.c
  98. 19
      src/komodo_utils.h
  99. 20
      src/listassetchainparams
  100. 10
      src/listassetchains
  101. 518
      src/main.cpp
  102. 5
      src/main.h
  103. 2
      src/metrics.cpp
  104. 426
      src/miner.cpp
  105. 5
      src/miner.h
  106. 45
      src/net.cpp
  107. 2
      src/net.h
  108. 84
      src/notarisationdb.cpp
  109. 27
      src/notarisationdb.h
  110. 12
      src/pow.cpp
  111. 44
      src/primitives/block.cpp
  112. 6
      src/primitives/block.h
  113. 17
      src/primitives/transaction.cpp
  114. 12
      src/primitives/transaction.h
  115. 7
      src/rest.cpp
  116. 306
      src/rpcblockchain.cpp
  117. 13
      src/rpcclient.cpp
  118. 253
      src/rpccrosschain.cpp
  119. 53
      src/rpcmining.cpp
  120. 169
      src/rpcmisc.cpp
  121. 5
      src/rpcnet.cpp
  122. 36
      src/rpcrawtransaction.cpp
  123. 72
      src/rpcserver.cpp
  124. 46
      src/rpcserver.h
  125. 3
      src/script/cc.h
  126. 14
      src/script/interpreter.cpp
  127. 1
      src/script/interpreter.h
  128. 21
      src/script/script.cpp
  129. 2
      src/script/script.h
  130. 18
      src/script/standard.cpp
  131. 8
      src/test-komodo/main.cpp
  132. 257
      src/test-komodo/test_coinimport.cpp
  133. 213
      src/test-komodo/test_crosschain.cpp
  134. 10
      src/test-komodo/test_cryptoconditions.cpp
  135. 6
      src/test-komodo/test_eval_bet.cpp
  136. 170
      src/test-komodo/test_eval_notarisation.cpp
  137. 54
      src/test-komodo/test_parse_notarisation.cpp
  138. 147
      src/test-komodo/testutils.cpp
  139. 16
      src/test-komodo/testutils.h
  140. 447
      src/test/alert_tests.cpp
  141. 30
      src/test/miner_tests.cpp
  142. 139
      src/txdb.cpp
  143. 2
      src/txdb.h
  144. 57
      src/txmempool.cpp
  145. 2
      src/verusd
  146. 4
      src/wallet/asyncrpcoperation_mergetoaddress.cpp
  147. 4
      src/wallet/asyncrpcoperation_sendmany.cpp
  148. 4
      src/wallet/asyncrpcoperation_shieldcoinbase.cpp
  149. 36
      src/wallet/rpcdump.cpp
  150. 1216
      src/wallet/rpcwallet.cpp
  151. 49
      src/wallet/wallet.cpp
  152. 2
      src/wallet/wallet.h
  153. 2
      src/zcbenchmarks.cpp
  154. 2
      toolchain-info.sh
  155. 6
      zcutil/build-mac.sh

1
COPYING

@ -1,3 +1,4 @@
Copyright (c) 2016-2018 The Komodo developers
Copyright (c) 2016-2017 The Zcash developers
Copyright (c) 2009-2017 The Bitcoin Core developers
Copyright (c) 2018 The VerusCoin developers

32
README-mac.md

@ -1,3 +1,4 @@
You will need Apple's Xcode (at least version 7, preferably 8.x) and the Xcode Command Line Tools:
https://itunes.apple.com/us/app/xcode/id497799835?mt=12
@ -12,17 +13,44 @@ Use the brewfile to install the necessary packages:
brew bundle
```
or
```shell
brew tap discoteq/discoteq; brew install flock autoconf autogen automake gcc@6 binutils protobuf coreutils wget
```
Get all that installed, then run:
```shell
git clone https://github.com/VerusCoin/VerusCoin.git
cd VerusCoin
./zcutil/build-mac.sh
./zcutil/fetch-params.sh
```
To build a distributable version of VerusCoin then run the makeReleaseMac.sh script after building. This will fix the dependency references and move the komodod and komodo-cli binaries to the kmd/mac/verus-cli directory along with the 6 libraries required for it to work properly.
When you are done building, you need to do a few things in the [Configuration](https://github.com/zcash/zcash/wiki/1.0-User-Guide#configuration) section of the Zcash User Guide differently because we are on the Mac. All instances of `~/.zcash` need to be replaced by `~/Library/Application\ Support/Zcash`
The fetch-params.sh script, however, has already been altered to fetch the proving keys into the correct directory to conform to Mac specific naming conventions.
When you are done building, you need to create `Komodo.conf` the Mac way.
```shell
mkdir ~/Library/Application\ Support/Komodo
touch ~/Library/Application\ Support/Komodo/Komodo.conf
nano ~/Library/Application\ Support/Komodo/Komodo.conf
```
Add the following lines to the Komodo.conf file:
```shell
rpcuser=dontuseweakusernameoryougetrobbed
rpcpassword=dontuseweakpasswordoryougetrobbed
txindex=1
addnode=5.9.102.210
addnode=78.47.196.146
addnode=178.63.69.164
addnode=88.198.65.74
addnode=5.9.122.241
addnode=144.76.94.38
addnode=89.248.166.91
```
Happy Building

2
README.md

@ -21,7 +21,7 @@ The wallet downloads and stores the block chain or asset chain of the coin you s
- Support: [https://support.komodoplatform.com/support/home](https://support.komodoplatform.com/support/home)
- Knowledgebase & How-to: [https://komodoplatform.atlassian.net/wiki/spaces/KPSD/pages](https://komodoplatform.atlassian.net/wiki/spaces/KPSD/pages)
- API references: [http://docs.supernet.org/](http://docs.supernet.org/) #Not up to date.
- Whitepaper: [Komodo Whitepaper](https://komodoplatform.com/wp-content/uploads/2018/03/2018-03-12-Komodo-White-Paper-Full.pdf)
- Whitepaper: [Komodo Whitepaper](https://komodoplatform.com/wp-content/uploads/2018/06/Komodo-Whitepaper-June-3.pdf)
- Komodo Platform public material: [Komodo Platform public material](https://docs.google.com/document/d/1AbhWrtagu4vYdkl-vsWz-HSNyNvK-W-ZasHCqe7CZy0)
## List of Komodo Platform Technologies

140
contrib/debian/examples/komodo.conf

@ -0,0 +1,140 @@
##
## komodo.conf configuration file. Lines beginning with # are comments.
##
# Network-related settings:
# Run a regression test network
#regtest=0
# Connect via a SOCKS5 proxy
#proxy=127.0.0.1:9050
# Bind to given address and always listen on it. Use [host]:port notation for IPv6
#bind=<addr>
# Bind to given address and whitelist peers connecting to it. Use [host]:port notation for IPv6
#whitebind=<addr>
##############################################################
## Quick Primer on addnode vs connect ##
## Let's say for instance you use addnode=4.2.2.4 ##
## addnode will connect you to and tell you about the ##
## nodes connected to 4.2.2.4. In addition it will tell ##
## the other nodes connected to it that you exist so ##
## they can connect to you. ##
## connect will not do the above when you 'connect' to it. ##
## It will *only* connect you to 4.2.2.4 and no one else.##
## ##
## So if you're behind a firewall, or have other problems ##
## finding nodes, add some using 'addnode'. ##
## ##
## If you want to stay private, use 'connect' to only ##
## connect to "trusted" nodes. ##
## ##
## If you run multiple nodes on a LAN, there's no need for ##
## all of them to open lots of connections. Instead ##
## 'connect' them all to one node that is port forwarded ##
## and has lots of connections. ##
## Thanks goes to [Noodle] on Freenode. ##
##############################################################
# Use as many addnode= settings as you like to connect to specific peers
#addnode=69.164.218.197
#addnode=10.0.0.2:8233
# Alternatively use as many connect= settings as you like to connect ONLY to specific peers
#connect=69.164.218.197
#connect=10.0.0.1:8233
# Listening mode, enabled by default except when 'connect' is being used
#listen=1
# Maximum number of inbound+outbound connections.
#maxconnections=
#
# JSON-RPC options (for controlling a running Komodo/komodod process)
#
# server=1 tells komodod to accept JSON-RPC commands (set as default if not specified)
#server=1
# Bind to given address to listen for JSON-RPC connections. Use [host]:port notation for IPv6.
# This option can be specified multiple times (default: bind to all interfaces)
#rpcbind=<addr>
# You must set rpcuser and rpcpassword to secure the JSON-RPC api
#rpcuser=Ulysses
#rpcpassword=YourSuperGreatPasswordNumber_DO_NOT_USE_THIS_OR_YOU_WILL_GET_ROBBED_385593
# How many seconds komodo will wait for a complete RPC HTTP request.
# after the HTTP connection is established.
#rpcclienttimeout=30
# By default, only RPC connections from localhost are allowed.
# Specify as many rpcallowip= settings as you like to allow connections from other hosts,
# either as a single IPv4/IPv6 or with a subnet specification.
# NOTE: opening up the RPC port to hosts outside your local trusted network is NOT RECOMMENDED,
# because the rpcpassword is transmitted over the network unencrypted and also because anyone
# that can authenticate on the RPC port can steal your keys + take over the account running komodod
# For more information see https://github.com/zcash/zcash/issues/1497
#rpcallowip=10.1.1.34/255.255.255.0
#rpcallowip=1.2.3.4/24
#rpcallowip=2001:db8:85a3:0:0:8a2e:370:7334/96
# Listen for RPC connections on this TCP port:
#rpcport=8232
# You can use Komodo or komodod to send commands to Komodo/komodod
# running on another host using this option:
#rpcconnect=127.0.0.1
# Transaction Fee
# Send transactions as zero-fee transactions if possible (default: 0)
#sendfreetransactions=0
# Create transactions that have enough fees (or priority) so they are likely to # begin confirmation within n blocks (default: 1).
# This setting is overridden by the -paytxfee option.
#txconfirmtarget=n
# Miscellaneous options
# Enable attempt to mine komodo.
#gen=0
# Set the number of threads to be used for mining komodo (-1 = all cores).
#genproclimit=1
# Specify a different Equihash solver (e.g. "tromp") to try to mine komodo
# faster when gen=1.
#equihashsolver=default
# Pre-generate this many public/private key pairs, so wallet backups will be valid for
# both prior transactions and several dozen future transactions.
#keypool=100
# Pay an optional transaction fee every time you send komodo. Transactions with fees
# are more likely than free transactions to be included in generated blocks, so may
# be validated sooner. This setting does not affect private transactions created with
# 'z_sendmany'.
#paytxfee=0.00
#Rewind the chain to specific block height. This is useful for creating snapshots at a given block height.
#rewind=777777
#Stop the chain a specific block height. This is useful for creating snapshots at a given block height.
#stopat=1000000
#Set an address to use as change address for all transactions. This value must be set to a 33 byte pubkey. All mined coins will also be sent to this address.
#pubkey=027dc7b5cfb5efca96674b45e9fda18df069d040b9fd9ff32c35df56005e330392
#Forfeit all user rewards to miners. Set this to explicitly not claim user rewards.
#exchange=1
#Donate all user rewards to a a specific address. This value must be set to a 33 byte pubkey.
#donation=027dc7b5cfb5efca96674b45e9fda18df069d040b9fd9ff32c35df56005e330392

885
contrib/seeds/nodes_main.txt

@ -1,879 +1,6 @@
1.34.168.128:8333
1.202.128.218:8333
2.30.0.210:8333
5.9.96.203:8333
5.45.71.130:8333
5.45.98.141:8333
5.102.145.68:8333
5.135.160.77:8333
5.189.134.246:8333
5.199.164.132:8333
5.249.135.102:8333
8.19.44.110:8333
8.22.230.8:8333
14.200.200.145:8333
18.228.0.188:8333
18.228.0.200:8333
23.24.168.97:8333
23.28.35.227:8333
23.92.76.170:8333
23.99.64.119:8333
23.228.166.128:8333
23.229.45.32:8333
24.8.105.128:8333
24.16.69.137:8333
24.94.98.96:8333
24.102.118.7:8333
24.118.166.228:8333
24.122.133.49:8333
24.166.97.162:8333
24.213.235.242:8333
24.226.107.64:8333
24.228.192.171:8333
27.140.133.18:8333
31.41.40.25:8333
31.43.101.59:8333
31.184.195.181:8333
31.193.139.66:8333
37.200.70.102:8333
37.205.10.151:8333
42.3.106.227:8333
42.60.133.106:8333
45.56.85.231:8333
45.56.102.228:8333
45.79.130.235:8333
46.28.204.61:11101
46.38.235.229:8333
46.59.2.74:8333
46.101.132.37:8333
46.101.168.50:8333
46.163.76.230:8333
46.166.161.103:8333
46.182.132.100:8333
46.223.36.94:8333
46.227.66.132:8333
46.227.66.138:8333
46.239.107.74:8333
46.249.39.100:8333
46.250.98.108:8333
50.7.37.114:8333
50.81.53.151:8333
50.115.43.253:8333
50.116.20.87:8333
50.116.33.92:8333
50.125.167.245:8333
50.143.9.51:8333
50.188.192.133:8333
54.77.162.76:8333
54.153.97.109:8333
54.165.192.125:8333
58.96.105.85:8333
59.167.196.135:8333
60.29.227.163:8333
61.35.225.19:8333
62.43.130.178:8333
62.109.49.26:8333
62.202.0.97:8333
62.210.66.227:8333
62.210.192.169:8333
64.74.98.205:8333
64.156.193.100:8333
64.203.102.86:8333
64.229.142.48:8333
65.96.193.165:8333
66.30.3.7:8333
66.114.33.49:8333
66.118.133.194:8333
66.135.10.126:8333
66.172.10.4:8333
66.194.38.250:8333
66.194.38.253:8333
66.215.192.104:8333
67.60.98.115:8333
67.164.35.36:8333
67.191.162.244:8333
67.207.195.77:8333
67.219.233.140:8333
67.221.193.55:8333
67.228.162.228:8333
68.50.67.199:8333
68.62.3.203:8333
68.65.205.226:9000
68.106.42.191:8333
68.150.181.198:8333
68.196.196.106:8333
68.224.194.81:8333
69.46.5.194:8333
69.50.171.238:8333
69.64.43.152:8333
69.65.41.13:8333
69.90.132.200:8333
69.143.1.243:8333
69.146.98.216:8333
69.165.246.38:8333
69.207.6.135:8333
69.251.208.26:8333
70.38.1.101:8333
70.38.9.66:8333
70.90.2.18:8333
71.58.228.226:8333
71.199.11.189:8333
71.199.193.202:8333
71.205.232.181:8333
71.236.200.162:8333
72.24.73.186:8333
72.52.130.110:8333
72.53.111.37:8333
72.235.38.70:8333
73.31.171.149:8333
73.32.137.72:8333
73.137.133.238:8333
73.181.192.103:8333
73.190.2.60:8333
73.195.192.137:8333
73.222.35.117:8333
74.57.199.180:8333
74.82.233.205:8333
74.85.66.82:8333
74.101.224.127:8333
74.113.69.16:8333
74.122.235.68:8333
74.193.68.141:8333
74.208.164.219:8333
75.100.37.122:8333
75.145.149.169:8333
75.168.34.20:8333
76.20.44.240:8333
76.100.70.17:8333
76.168.3.239:8333
76.186.140.103:8333
77.92.68.221:8333
77.109.101.142:8333
77.110.11.86:8333
77.242.108.18:8333
78.46.96.150:9020
78.84.100.95:8333
79.132.230.144:8333
79.133.43.63:8333
79.160.76.153:8333
79.169.34.24:8333
79.188.7.78:8333
80.217.226.25:8333
80.223.100.179:8333
80.240.129.221:8333
81.1.173.243:8333
81.7.11.50:8333
81.7.16.17:8333
81.66.111.3:8333
81.80.9.71:8333
81.140.43.138:8333
81.171.34.37:8333
81.174.247.50:8333
81.181.155.53:8333
81.184.5.253:8333
81.187.69.130:8333
81.230.3.84:8333
82.42.128.51:8333
82.74.226.21:8333
82.142.75.50:8333
82.199.102.10:8333
82.200.205.30:8333
82.221.108.21:8333
82.221.128.35:8333
82.238.124.41:8333
82.242.0.245:8333
83.76.123.110:8333
83.150.9.196:8333
83.162.196.192:8333
83.162.234.224:8333
83.170.104.91:8333
83.255.66.118:8334
84.2.34.104:8333
84.45.98.91:8333
84.47.161.150:8333
84.212.192.131:8333
84.215.169.101:8333
84.238.140.176:8333
84.245.71.31:8333
85.17.4.212:8333
85.114.128.134:8333
85.159.237.191:8333
85.166.130.189:8333
85.199.4.228:8333
85.214.66.168:8333
85.214.195.210:8333
85.229.0.73:8333
86.21.96.45:8333
87.48.42.199:8333
87.81.143.82:8333
87.81.251.72:8333
87.104.24.185:8333
87.104.168.104:8333
87.117.234.71:8333
87.118.96.197:8333
87.145.12.57:8333
87.159.170.190:8333
88.150.168.160:8333
88.208.0.79:8333
88.208.0.149:8333
88.214.194.226:8343
89.1.11.32:8333
89.36.235.108:8333
89.67.96.2:15321
89.98.16.41:8333
89.108.72.195:8333
89.156.35.157:8333
89.163.227.28:8333
89.212.33.237:8333
89.212.160.165:8333
89.231.96.83:8333
89.248.164.64:8333
90.149.193.199:8333
91.77.239.245:8333
91.106.194.97:8333
91.126.77.77:8333
91.134.38.195:8333
91.156.97.181:8333
91.207.68.144:8333
91.209.77.101:8333
91.214.200.205:8333
91.220.131.242:8333
91.220.163.18:8333
91.233.23.35:8333
92.13.96.93:8333
92.14.74.114:8333
92.27.7.209:8333
92.221.228.13:8333
92.255.207.73:8333
93.72.167.148:8333
93.74.163.234:8333
93.123.174.66:8333
93.152.166.29:8333
93.181.45.188:8333
94.19.12.244:8333
94.190.227.112:8333
94.198.135.29:8333
94.224.162.65:8333
94.226.107.86:8333
94.242.198.161:8333
95.31.10.209:8333
95.65.72.244:8333
95.84.162.95:8333
95.90.139.46:8333
95.183.49.27:8005
95.215.47.133:8333
96.23.67.85:8333
96.44.166.190:8333
97.93.225.74:8333
98.26.0.34:8333
98.27.225.102:8333
98.229.117.229:8333
98.249.68.125:8333
98.255.5.155:8333
99.101.240.114:8333
101.100.174.138:8333
101.251.203.6:8333
103.3.60.61:8333
103.30.42.189:8333
103.224.165.48:8333
104.36.83.233:8333
104.37.129.22:8333
104.54.192.251:8333
104.128.228.252:8333
104.128.230.185:8334
104.130.161.47:8333
104.131.33.60:8333
104.143.0.156:8333
104.156.111.72:8333
104.167.111.84:8333
104.193.40.248:8333
104.197.7.174:8333
104.197.8.250:8333
104.223.1.133:8333
104.236.97.140:8333
104.238.128.214:8333
104.238.130.182:8333
106.38.234.84:8333
106.185.36.204:8333
107.6.4.145:8333
107.150.2.6:8333
107.150.40.234:8333
107.155.108.130:8333
107.161.182.115:8333
107.170.66.231:8333
107.190.128.226:8333
107.191.106.115:8333
108.16.2.61:8333
109.70.4.168:8333
109.162.35.196:8333
109.163.235.239:8333
109.190.196.220:8333
109.191.39.60:8333
109.234.106.191:8333
109.238.81.82:8333
114.76.147.27:8333
115.28.224.127:8333
115.68.110.82:18333
118.97.79.218:8333
118.189.207.197:8333
119.228.96.233:8333
120.147.178.81:8333
121.41.123.5:8333
121.67.5.230:8333
122.107.143.110:8333
123.2.170.98:8333
123.110.65.94:8333
123.193.139.19:8333
125.239.160.41:8333
128.101.162.193:8333
128.111.73.10:8333
128.140.229.73:8333
128.175.195.31:8333
128.199.107.63:8333
128.199.192.153:8333
128.253.3.193:20020
129.123.7.7:8333
130.89.160.234:8333
131.72.139.164:8333
131.191.112.98:8333
133.1.134.162:8333
134.19.132.53:8333
137.226.34.42:8333
141.41.2.172:8333
141.255.128.204:8333
142.217.12.106:8333
143.215.129.126:8333
146.0.32.101:8337
147.229.13.199:8333
149.210.133.244:8333
149.210.162.187:8333
150.101.163.241:8333
151.236.11.189:8333
153.121.66.211:8333
154.20.2.139:8333
159.253.23.132:8333
162.209.106.123:8333
162.210.198.184:8333
162.218.65.121:8333
162.222.161.49:8333
162.243.132.6:8333
162.243.132.58:8333
162.248.99.164:53011
162.248.102.117:8333
163.158.35.110:8333
164.15.10.189:8333
164.40.134.171:8333
166.230.71.67:8333
167.160.161.199:8333
168.103.195.250:8333
168.144.27.112:8333
168.158.129.29:8333
170.75.162.86:8333
172.90.99.174:8333
172.245.5.156:8333
173.23.166.47:8333
173.32.11.194:8333
173.34.203.76:8333
173.171.1.52:8333
173.175.136.13:8333
173.230.228.139:8333
173.247.193.70:8333
174.49.132.28:8333
174.52.202.72:8333
174.53.76.87:8333
174.109.33.28:8333
176.28.12.169:8333
176.35.182.214:8333
176.36.33.113:8333
176.36.33.121:8333
176.58.96.173:8333
176.121.76.84:8333
178.62.70.16:8333
178.62.111.26:8333
178.76.169.59:8333
178.79.131.32:8333
178.162.199.216:8333
178.175.134.35:8333
178.248.111.4:8333
178.254.1.170:8333
178.254.34.161:8333
179.43.143.120:8333
179.208.156.198:8333
180.200.128.58:8333
183.78.169.108:8333
183.96.96.152:8333
184.68.2.46:8333
184.73.160.160:8333
184.94.227.58:8333
184.152.68.163:8333
185.7.35.114:8333
185.28.76.179:8333
185.31.160.202:8333
185.45.192.129:8333
185.66.140.15:8333
186.2.167.23:8333
186.220.101.142:8333
188.26.5.33:8333
188.75.136.146:8333
188.120.194.140:8333
188.121.5.150:8333
188.138.0.114:8333
188.138.33.239:8333
188.166.0.82:8333
188.182.108.129:8333
188.191.97.208:8333
188.226.198.102:8001
190.10.9.217:8333
190.75.143.144:8333
190.139.102.146:8333
191.237.64.28:8333
192.3.131.61:8333
192.99.225.3:8333
192.110.160.122:8333
192.146.137.1:8333
192.183.198.204:8333
192.203.228.71:8333
193.0.109.3:8333
193.12.238.204:8333
193.91.200.85:8333
193.234.225.156:8333
194.6.233.38:8333
194.63.143.136:8333
194.126.100.246:8333
195.134.99.195:8333
195.159.111.98:8333
195.159.226.139:8333
195.197.175.190:8333
198.48.199.108:8333
198.57.208.134:8333
198.57.210.27:8333
198.62.109.223:8333
198.167.140.8:8333
198.167.140.18:8333
199.91.173.234:8333
199.127.226.245:8333
199.180.134.116:8333
200.7.96.99:8333
201.160.106.86:8333
202.55.87.45:8333
202.60.68.242:8333
202.60.69.232:8333
202.124.109.103:8333
203.30.197.77:8333
203.88.160.43:8333
203.151.140.14:8333
203.219.14.204:8333
205.147.40.62:8333
207.235.39.214:8333
207.244.73.8:8333
208.12.64.225:8333
208.76.200.200:8333
209.40.96.121:8333
209.126.107.176:8333
209.141.40.149:8333
209.190.75.59:8333
209.208.111.142:8333
210.54.34.164:8333
211.72.66.229:8333
212.51.144.42:8333
212.112.33.157:8333
212.116.72.63:8333
212.126.14.122:8333
213.66.205.194:8333
213.111.196.21:8333
213.122.107.102:8333
213.136.75.175:8333
213.155.7.24:8333
213.163.64.31:8333
213.163.64.208:8333
213.165.86.136:8333
213.184.8.22:8333
216.15.78.182:8333
216.55.143.154:8333
216.115.235.32:8333
216.126.226.166:8333
216.145.67.87:8333
216.169.141.169:8333
216.249.92.230:8333
216.250.138.230:8333
217.20.171.43:8333
217.23.2.71:8333
217.23.2.242:8333
217.25.9.76:8333
217.40.226.169:8333
217.123.98.9:8333
217.155.36.62:8333
217.172.32.18:20993
218.61.196.202:8333
218.231.205.41:8333
220.233.77.200:8333
223.18.226.85:8333
223.197.203.82:8333
223.255.166.142:8333
[2001:1291:2bf:1::100]:8333
[2001:1418:100:5c2::2]:8333
[2001:16d8:dd24:0:86c9:681e:f931:256]:8333
[2001:19f0:1624:e6::579d:9428]:8333
[2001:19f0:300:1340:225:90ff:fec9:2b6d]:8333
[2001:19f0:4009:1405::64]:8333
[2001:1b40:5000:2e::3fb0:6571]:8333
[2001:410:a000:4050:8463:90b0:fffb:4e58]:8333
[2001:410:a002:cafe:8463:90b0:fffb:4e58]:8333
[2001:41d0:1:541e::1]:8333
[2001:41d0:1:6a34::3]:8333
[2001:41d0:1:6cd3::]:8333
[2001:41d0:1:8b26::1]:8333
[2001:41d0:1:a33d::1]:8333
[2001:41d0:1:b855::1]:8333
[2001:41d0:1:c139::1]:8333
[2001:41d0:1:c8d7::1]:8333
[2001:41d0:1:dd3f::1]:8333
[2001:41d0:1:e29d::1]:8333
[2001:41d0:1:f59f::33]:8333
[2001:41d0:1:f7cc::1]:8333
[2001:41d0:1:ff87::1]:8333
[2001:41d0:2:2f05::1]:8333
[2001:41d0:2:37c3::]:8200
[2001:41d0:2:3e13::1]:8333
[2001:41d0:2:8619::]:8333
[2001:41d0:2:9c94::1]:8333
[2001:41d0:2:a24f::]:8333
[2001:41d0:2:adbf::]:8333
[2001:41d0:2:b721::1]:8333
[2001:41d0:2:ee52::1]:8333
[2001:41d0:2:f1a5::]:8333
[2001:41d0:2:fa54::1]:8333
[2001:41d0:51:1::2036]:8333
[2001:41d0:52:a00::1a1]:8333
[2001:41d0:52:cff::6f5]:8333
[2001:41d0:52:d00::2c0]:8333
[2001:41d0:52:d00::cf2]:8333
[2001:41d0:8:1087::1]:8333
[2001:41d0:8:4a3c::b7c]:8333
[2001:41d0:8:6728::]:8333
[2001:41d0:8:b779::1]:8333
[2001:41d0:8:c30f::1]:8333
[2001:41d0:8:d2b2::1]:8333
[2001:41d0:8:d5c3::1]:8333
[2001:41d0:8:eb8b::]:8333
[2001:41d0:a:16d0::1]:8333
[2001:41d0:a:2b18::1]:8333
[2001:41d0:a:3a9c::1]:8333
[2001:41d0:a:4903::]:8333
[2001:41d0:a:57b::1]:8333
[2001:41d0:a:5c7a::]:8333
[2001:41d0:a:6c29::1]:8333
[2001:41d0:a:f482::1]:8333
[2001:41d0:b:854:b7c:b7c:b7c:b7c]:8333
[2001:41d0:d:111c::]:8333
[2001:44b8:4116:7801:4216:7eff:fe78:3fe4]:8333
[2001:470:1f08:837::2]:8333
[2001:470:1f08:c33::2]:8333
[2001:470:1f09:bca:218:7dff:fe10:be33]:8333
[2001:470:1f0f:22d::212:26]:8333
[2001:470:1f11:12d5::ae1:5611]:8333
[2001:470:1f14:57a::2]:8333
[2001:470:1f14:7d::2]:8333
[2001:470:1f15:57c::1]:8333
[2001:470:1f15:dda:3d9a:3f11:9a56:ed64]:8333
[2001:470:25:482::2]:8333
[2001:470:25:e4::2]:8333
[2001:470:4:26b::2]:8333
[2001:470:5f:5f::232]:8333
[2001:470:66:119::2]:8333
[2001:470:67:39d::71]:8333
[2001:470:6c4f::cafe]:8333
[2001:470:8:2e1::43]:8333
[2001:470:90a7:96::afe:6021]:8333
[2001:470:95c1::2]:8333
[2001:470:b1d0:ffff::1000]:8333
[2001:470:c1f2:3::201]:8333
[2001:470:d00d:0:3664:a9ff:fe9a:5150]:8333
[2001:470:e250:0:211:11ff:feb9:924c]:8333
[2001:4800:7817:101:be76:4eff:fe04:dc52]:8333
[2001:4800:7819:104:be76:4eff:fe04:7809]:8333
[2001:4800:7819:104:be76:4eff:fe05:c828]:8333
[2001:4802:7800:2:30d7:1775:ff20:1858]:8333
[2001:4802:7802:101:be76:4eff:fe20:256]:8333
[2001:4802:7802:103:be76:4eff:fe20:2de8]:8333
[2001:4830:1100:2e8::2]:8333
[2001:4ba0:fff7:181:dead::1]:8333
[2001:4ba0:fffa:5d::93]:8333
[2001:4ba0:ffff:1be:1:1005:0:1]:8335
[2001:4c48:110:101:216:3eff:fe24:1162]:8333
[2001:4dd0:f101::32]:8333
[2001:4dd0:ff00:867f::3]:8333
[2001:4dd0:ff00:9a67::9]:8333
[2001:4dd0:ff00:9c55:c23f:d5ff:fe6c:7ee9]:8333
[2001:5c0:1400:b::3cc7]:8333
[2001:5c0:1400:b::3d01]:8333
[2001:5c0:1400:b::8df]:8333
[2001:5c0:1501:300::3]:8333
[2001:610:1b19::3]:8333
[2001:620:500:fff0:f21f:afff:fecf:91cc]:8333
[2001:67c:1220:80c:ad:8de2:f7e2:c784]:8333
[2001:67c:21ec:1000::b]:8333
[2001:6f8:1296:0:76d4:35ff:feba:1d26]:8333
[2001:840:f000:4250:3e4a:92ff:fe6d:145f]:8333
[2001:8d8:840:500::39:1ae]:8333
[2001:980:efd8:0:21:de4a:2709:912]:8333
[2001:981:46:1::3]:8333
[2001:981:9319:2:c0:a8:c8:8]:8333
[2001:9d8:cafe:3::91]:8333
[2001:ad0:1:1:26be:5ff:fe25:959d]:8333
[2001:ba8:1f1:f34c::2]:8333
[2001:bc8:381c:100::1]:8333
[2002:175c:4caa::175c:4caa]:8333
[2002:4404:82f1:0:8d55:8fbb:15fa:f4e0]:8333
[2002:4475:2233:0:21f:5bff:fe33:9f70]:8333
[2002:596c:48c3::596c:48c3]:8333
[2002:8c6d:6521:9617:12bf:48ff:fed8:1724]:8333
[2002:a646:5e6a::1:2]:8333
[2002:b009:20c5::b009:20c5]:8333
[2400:8900::f03c:91ff:fe6e:823e]:8333
[2400:8900::f03c:91ff:fe70:d164]:8333
[2400:8901::f03c:91ff:fe37:9761]:8333
[2403:4200:403:2::ff]:8333
[2403:b800:1000:64:40a:e9ff:fe5f:94c1]:8333
[2403:b800:1000:64:9879:17ff:fe6a:a59f]:8333
[2600:3c00::f03c:91ff:fe18:59b2]:8333
[2600:3c00::f03c:91ff:fe37:a4b1]:8333
[2600:3c00::f03c:91ff:fe56:2973]:8333
[2600:3c00::f03c:91ff:fe6e:7297]:8333
[2600:3c00::f03c:91ff:fe84:8a6e]:8333
[2600:3c01::f03c:91ff:fe18:6adf]:8333
[2600:3c01::f03c:91ff:fe18:e217]:8333
[2600:3c01::f03c:91ff:fe33:1b31]:8333
[2600:3c01::f03c:91ff:fe33:2fe1]:8333
[2600:3c01::f03c:91ff:fe33:a03f]:8333
[2600:3c01::f03c:91ff:fe50:5e06]:8333
[2600:3c01::f03c:91ff:fe56:d645]:8333
[2600:3c01::f03c:91ff:fe6e:a3dc]:8333
[2600:3c01::f03c:91ff:fe89:a659]:8333
[2600:3c02::f03c:91ff:fe6e:6f0b]:8333
[2600:3c03::f03c:91ff:fe33:f6fb]:8333
[2600:3c03::f03c:91ff:fe50:5fa7]:8333
[2600:3c03::f03c:91ff:fe6e:1803]:8333
[2600:3c03::f03c:91ff:fe6e:4ac0]:8333
[2601:6:4800:47f:1e4e:1f4d:332c:3bf6]:8333
[2601:d:5400:fed:8d54:c1e8:7ed7:d45e]:8333
[2602:100:4b8f:6d2a:20c:29ff:feaf:c4c2]:8333
[2602:ffc5:1f::1f:2d61]:8333
[2602:ffc5:1f::1f:9211]:8333
[2602:ffc5::ffc5:b844]:8333
[2602:ffe8:100:2::457:936b]:8333
[2602:ffea:1001:125::2ad4]:8333
[2602:ffea:1001:6ff::837d]:8333
[2602:ffea:1001:72b::578b]:8333
[2602:ffea:1001:77a::9cae]:8333
[2602:ffea:1:2fe::6bc8]:8333
[2602:ffea:1:701::7968]:8333
[2602:ffea:1:70d::82ec]:8333
[2602:ffea:1:9ff::e957]:8333
[2602:ffea:1:a5d::4acb]:8333
[2602:ffea:a::24c4:d9fd]:8333
[2602:ffea:a::c06:ae32]:8333
[2604:0:c1:100:1ec1:deff:fe54:2235]:8333
[2604:180:1:1af::42a9]:8333
[2604:180::b208:398]:8333
[2604:2880::6072:aed]:8333
[2604:4080:1114:0:3285:a9ff:fe93:850c]:8333
[2604:7c00:17:3d0::5a4d]:8333
[2604:9a00:2100:a009:2::]:8333
[2604:a880:1:20::22a:4001]:8333
[2604:a880:800:10::752:f001]:8333
[2604:c00:88:32:216:3eff:fee4:fcca]:8333
[2604:c00:88:32:216:3eff:fef5:bc21]:8333
[2605:7980:1:2::1761:3d4e]:8333
[2605:e000:1417:4068:223:32ff:fe96:e2d]:8333
[2606:6000:a441:9903:5054:ff:fe78:66ff]:8333
[2606:df00:2::ae85:8fc6]:8333
[2607:5300:100:200::e7f]:8333
[2607:5300:10::a1]:8333
[2607:5300:60:116e::1]:8333
[2607:5300:60:1535::]:8333
[2607:5300:60:1b32::1]:8333
[2607:5300:60:2337::1]:8333
[2607:5300:60:2b90::1]:8333
[2607:5300:60:2d99::1]:8333
[2607:5300:60:3cb::1]:8333
[2607:5300:60:4a85::]:8333
[2607:5300:60:5112:0:2:4af5:63fe]:8333
[2607:5300:60:6dd5::]:8333
[2607:5300:60:a91::1]:8333
[2607:f1c0:820:1500::7f:3f44]:8333
[2607:f1c0:848:1000::48:943c]:8333
[2607:f948:0:1::7]:8333
[2607:fcd0:100:2300::4ad:e594]:8333
[2607:fcd0:100:2300::659e:9cb3]:8333
[2607:fcd0:100:2300::c74b:a8ae]:8333
[2607:fcd0:100:2300::d82:d8c2]:8333
[2607:fcd0:100:4300::8795:2fa8]:8333
[2607:fcd0:daaa:901::9561:e043]:8333
[2a00:1178:2:43:5054:ff:fee7:2eb6]:8333
[2a00:1328:e100:cc42:230:48ff:fe92:55d]:8333
[2a00:14f0:e000:80d2:cd1a::1]:8333
[2a00:16d8:c::5b6a:c261]:8333
[2a00:61e0:4083:6d01:6852:1376:e972:2091]:8333
[2a00:c98:2030:a02f:2::2]:8333
[2a01:1b0:7999:402::131]:8333
[2a01:1e8:e100:811c:700f:65f0:f72a:1084]:8333
[2a01:238:42da:c500:6546:1293:5422:ab40]:8333
[2a01:348:6:473::2]:8333
[2a01:368:e010:2::2]:8333
[2a01:430:17:1::ffff:549]:8333
[2a01:430:17:1::ffff:830]:8333
[2a01:488:66:1000:53a9:d04:0:1]:8333
[2a01:488:66:1000:57e6:578c:0:1]:8333
[2a01:488:66:1000:b01c:178d:0:1]:8333
[2a01:488:67:1000:523:fdce:0:1]:8333
[2a01:488:67:1000:b01c:30ab:0:1]:8333
[2a01:4f8:100:24aa::2]:8333
[2a01:4f8:100:44e7::2]:8333
[2a01:4f8:100:5128::2]:8333
[2a01:4f8:100:84a7::1:1]:8333
[2a01:4f8:110:516c::2]:8333
[2a01:4f8:110:536e::2]:8333
[2a01:4f8:120:62e6::2]:8333
[2a01:4f8:120:702e::2]:8333
[2a01:4f8:120:8005::2]:8333
[2a01:4f8:120:8203::2]:8333
[2a01:4f8:120:8422::2]:8333
[2a01:4f8:121:11eb::2]:8333
[2a01:4f8:121:261::2]:8333
[2a01:4f8:130:242b::10]:8333
[2a01:4f8:130:242b::5]:8333
[2a01:4f8:130:2468::3]:8333
[2a01:4f8:130:632c::2]:8333
[2a01:4f8:130:6366::2]:8333
[2a01:4f8:130:6426::2]:8333
[2a01:4f8:130:934f::2]:8333
[2a01:4f8:131:2070::2]:8333
[2a01:4f8:131:54a2::2]:8333
[2a01:4f8:140:80ad::2]:8333
[2a01:4f8:141:186::2]:8333
[2a01:4f8:150:210b::2]:8333
[2a01:4f8:150:2263::5]:8333
[2a01:4f8:150:2349::2]:8333
[2a01:4f8:150:61ee::2]:8333
[2a01:4f8:150:7088:5054:ff:fe45:bff2]:8333
[2a01:4f8:150:8324::2]:9001
[2a01:4f8:151:1d8::2]:8333
[2a01:4f8:151:5128::2]:8333
[2a01:4f8:151:6347::2]:9001
[2a01:4f8:161:526d::2]:8333
[2a01:4f8:161:9349::2]:8333
[2a01:4f8:162:23c6::2]:8333
[2a01:4f8:162:4348::2]:8333
[2a01:4f8:162:7345::2]:8333
[2a01:4f8:162:7383::2]:8333
[2a01:4f8:162:74e3::2]:8333
[2a01:4f8:190:6065::2]:8333
[2a01:4f8:190:6349::2]:8333
[2a01:4f8:190:64c9::2]:8333
[2a01:4f8:190:91ce::2]:8333
[2a01:4f8:191:2194::83]:8333
[2a01:4f8:191:40a1::2]:8333
[2a01:4f8:191:4a7::2]:8333
[2a01:4f8:191:63b4:5000::1]:8333
[2a01:4f8:191:7121::2]:8333
[2a01:4f8:191:83a2::2]:8333
[2a01:4f8:191:93c4::2]:8333
[2a01:4f8:192:60a9:0:1:5:2]:8333
[2a01:4f8:192:73b2::2]:8333
[2a01:4f8:192:8098::2]:8333
[2a01:4f8:192:db::2]:8333
[2a01:4f8:200:1012::2]:8333
[2a01:4f8:200:22e3::2]:8333
[2a01:4f8:200:414e::2]:8333
[2a01:4f8:200:63af::222]:8333
[2a01:4f8:200:71e3:78b4:f3ff:fead:e8cf]:8333
[2a01:4f8:201:5164::2]:8333
[2a01:4f8:201:6011::4]:8333
[2a01:4f8:201:60d5::2]:8333
[2a01:4f8:202:53c3::2]:8333
[2a01:4f8:210:24aa::2]:8333
[2a01:4f8:210:502f::2]:8333
[2a01:4f8:211:14cf::2]:8333
[2a01:4f8:211:1a59::2]:8333
[2a01:4f8:211:2ac1::2]:8333
[2a01:4f8:211:cca::2]:8333
[2a01:4f8:a0:22a5::2]:8333
[2a01:4f8:a0:5023::2]:8333
[2a01:4f8:a0:5243::2]:8333
[2a01:4f8:a0:74c8::2]:8333
[2a01:4f8:a0:8227::2]:8333
[2a01:4f8:a0:822d::2]:8333
[2a01:4f8:d13:2183::2]:8333
[2a01:608:ffff:a009:8bf5:879d:e51a:f837]:8333
[2a01:79d:469e:ed94:c23f:d5ff:fe65:20c5]:8333
[2a01:7c8:aab5:3e6:5054:ff:fed7:4e54]:8333
[2a01:7e00::f03c:91ff:fe18:301e]:8333
[2a01:7e00::f03c:91ff:fe18:7749]:8333
[2a01:7e00::f03c:91ff:fe33:2d67]:8333
[2a01:7e00::f03c:91ff:fe33:347c]:8333
[2a01:7e00::f03c:91ff:fe33:ae50]:8333
[2a01:7e00::f03c:91ff:fe56:6b5c]:8333
[2a01:7e00::f03c:91ff:fe56:bee6]:8333
[2a01:7e00::f03c:91ff:fe69:4895]:8333
[2a01:7e00::f03c:91ff:fe69:9912]:8333
[2a01:7e00::f03c:91ff:fe6e:26ee]:8333
[2a01:7e00::f03c:91ff:fe73:42f1]:8333
[2a01:7e00::f03c:91ff:fe84:434f]:8333
[2a01:7e00::f03c:91ff:fe84:b36b]:8333
[2a01:7e00::f03c:91ff:fe89:1faa]:8333
[2a01:7e00::f03c:91ff:fe98:816]:8333
[2a01:7e00::f03c:91ff:fedb:352e]:8333
[2a01:7e00::f03c:91ff:fedb:4a1d]:8333
[2a01:e34:edbb:6750:224:1dff:fe89:3897]:8333
[2a01:e35:2f1d:3fb0:7187:c7ba:bcfc:80ce]:8333
[2a01:e35:8787:96f0:9032:9297:39ae:496d]:8333
[2a01:e35:8a3f:47c0:c617:feff:fe3c:9fbd]:8333
[2a01:e35:8b66:6a0:4900:9dfd:d841:d025]:8333
[2a02:168:4a01::39]:8333
[2a02:168:5404:2:c23f:d5ff:fe6a:512e]:8333
[2a02:180:1:1::5b8f:538c]:8333
[2a02:2028:1016::2]:8333
[2a02:2528:503:2::14]:8333
[2a02:2528:503:2::15]:8333
[2a02:2528:ff00:81a6:21e:c5ff:fe8d:f9a5]:8333
[2a02:2770:5:0:21a:4aff:fee4:c7db]:8333
[2a02:2770:8:0:21a:4aff:fe7b:3dcd]:8333
[2a02:348:5e:5a29::1]:8333
[2a02:7aa0:1619::202f:c06a]:8333
[2a02:8109:8e40:35fc:ba27:ebff:feae:cf16]:8333
[2a02:af8:6:1500::1:130]:8333
[2a02:c200:0:10:1:0:6314:2222]:8333
[2a02:c200:0:10:2:3:3295:1]:8332
[2a02:c200:0:10:3:0:5449:1]:8333
[2a02:c200:1:10:2:3:5899:1]:8333
[2a02:c200:1:10::2705:1]:8333
[2a02:ce80:0:20::1]:8333
[2a02:fe0:c321:27e0:6ef0:49ff:fe11:a61d]:8333
[2a03:4000:2:496::8]:8333
[2a03:b0c0:0:1010::62:f001]:8333
[2a03:f80:ed16:ca7:ea75:b12d:2af:9e2a]:8333
3ffk7iumtx3cegbi.onion:8333
3hshaantu6ot4upz.onion:8333
45c5lc77qgpikafy.onion:8333
77mx2jsxaoyesz2p.onion:8333
7g7j54btiaxhtsiy.onion:8333
b6fr7dlbu2kpiysf.onion:8333
bitcoincfqcssig5.onion:8333
bitcoinostk4e4re.onion:8333
bmutjfrj5btseddb.onion:8333
drp4pvejybx2ejdr.onion:8333
gixnv56d63buypan.onion:8333
h2vlpudzphzqxutd.onion:8333
hhiv5pnxenvbf4am.onion:8333
lzxpkn6ptp3ohh63.onion:8333
msphsgfiqfq5stne.onion:8333
ncwk3lutemffcpc4.onion:8333
okdzjarwekbshnof.onion:8333
sjdomi4yb2dwkjbc.onion:8333
uvwozwxlihntigbb.onion:8333
v6ylz45dn5ybpk4d.onion:8333
vk3qjdehyy4dwcxw.onion:8333
vqpye2k5rcqvj5mq.onion:8333
xudkoztdfrsuyyou.onion:8333
z55v4ostefnwfy32.onion:8333
185.25.48.236:27485
185.25.48.236:27487
185.64.105.111:27485
185.64.105.111:27487
185.25.48.72:27485
185.25.48.72:27487

4
darwin.host.mk.patch

@ -5,8 +5,8 @@
OSX_SDK_VERSION=10.9
OSX_SDK=$(SDK_PATH)/MacOSX$(OSX_SDK_VERSION).sdk
LD64_VERSION=241.9
! darwin_CC=gcc-5 -target $(host) -mmacosx-version-min=$(OSX_MIN_VERSION) --sysroot $(OSX_SDK) -mlinker-version=$(LD64_VERSION)
! darwin_CXX=g++-5 -target $(host) -mmacosx-version-min=$(OSX_MIN_VERSION) --sysroot $(OSX_SDK) -mlinker-version=$(LD64_VERSION)
! darwin_CC=gcc-6 -target $(host) -mmacosx-version-min=$(OSX_MIN_VERSION) --sysroot $(OSX_SDK) -mlinker-version=$(LD64_VERSION)
! darwin_CXX=g++-6 -target $(host) -mmacosx-version-min=$(OSX_MIN_VERSION) --sysroot $(OSX_SDK) -mlinker-version=$(LD64_VERSION)
darwin_CFLAGS=-pipe
darwin_CXXFLAGS=$(darwin_CFLAGS)

8
darwin.mk.patch

@ -2,8 +2,8 @@
--- ../../komodo-jl777/depends/builders/darwin.mk 2017-01-03 09:48:21.646034937 +0000
***************
*** 1,5 ****
! build_darwin_CC = gcc-5
! build_darwin_CXX = g++-5
! build_darwin_CC = gcc-6
! build_darwin_CXX = g++-6
build_darwin_AR: = $(shell xcrun -f ar)
build_darwin_RANLIB: = $(shell xcrun -f ranlib)
build_darwin_STRIP: = $(shell xcrun -f strip)
@ -21,8 +21,8 @@
! build_darwin_DOWNLOAD = wget --timeout=$(DOWNLOAD_CONNECT_TIMEOUT) --tries=$(DOWNLOAD_RETRIES) -nv -O
#darwin host on darwin builder. overrides darwin host preferences.
! darwin_CC= gcc-5
! darwin_CXX= g++-5
! darwin_CC= gcc-6
! darwin_CXX= g++-6
darwin_AR:=$(shell xcrun -f ar)
darwin_RANLIB:=$(shell xcrun -f ranlib)
darwin_STRIP:=$(shell xcrun -f strip)

8
depends/builders/darwin.mk

@ -1,5 +1,5 @@
build_darwin_CC = gcc-5
build_darwin_CXX = g++-5
build_darwin_CC = gcc-6
build_darwin_CXX = g++-6
build_darwin_AR: = $(shell xcrun -f ar)
build_darwin_RANLIB: = $(shell xcrun -f ranlib)
build_darwin_STRIP: = $(shell xcrun -f strip)
@ -10,8 +10,8 @@ build_darwin_SHA256SUM = shasum -a 256
build_darwin_DOWNLOAD = curl --connect-timeout $(DOWNLOAD_CONNECT_TIMEOUT) --retry $(DOWNLOAD_RETRIES) -L -f -o
#darwin host on darwin builder. overrides darwin host preferences.
darwin_CC= gcc-5
darwin_CXX= g++-5
darwin_CC= gcc-6
darwin_CXX= g++-6
darwin_AR:=$(shell xcrun -f ar)
darwin_RANLIB:=$(shell xcrun -f ranlib)
darwin_STRIP:=$(shell xcrun -f strip)

4
depends/hosts/darwin.mk

@ -2,8 +2,8 @@ OSX_MIN_VERSION=10.8
OSX_SDK_VERSION=10.11
OSX_SDK=$(SDK_PATH)/MacOSX$(OSX_SDK_VERSION).sdk
LD64_VERSION=253.9
darwin_CC=gcc-5 -target $(host) -mmacosx-version-min=$(OSX_MIN_VERSION) --sysroot $(OSX_SDK) -mlinker-version=$(LD64_VERSION)
darwin_CXX=g++-5 -target $(host) -mmacosx-version-min=$(OSX_MIN_VERSION) --sysroot $(OSX_SDK) -mlinker-version=$(LD64_VERSION)
darwin_CC=gcc-6 -target $(host) -mmacosx-version-min=$(OSX_MIN_VERSION) --sysroot $(OSX_SDK) -mlinker-version=$(LD64_VERSION)
darwin_CXX=g++-6 -target $(host) -mmacosx-version-min=$(OSX_MIN_VERSION) --sysroot $(OSX_SDK) -mlinker-version=$(LD64_VERSION)
darwin_CFLAGS=-pipe
darwin_CXXFLAGS=$(darwin_CFLAGS)

2
depends/packages/libgmp.mk

@ -18,7 +18,7 @@ $(package)_dependencies=
$(package)_config_opts=--enable-cxx --disable-shared
else
$(package)_version=6.1.1
$(package)_download_path=https://ftp.gnu.org/pub/gnu/gmp
$(package)_download_path=https://supernetorg.bintray.com/misc
$(package)_file_name=gmp-$($(package)_version).tar.bz2
$(package)_sha256_hash=a8109865f2893f1373b0a8ed5ff7429de8db696fc451b1036bd7bdf95bbeffd6
$(package)_dependencies=

1
depends/packages/librustzcash.mk

@ -7,7 +7,6 @@ $(package)_sha256_hash=a5760a90d4a1045c8944204f29fa2a3cf2f800afee400f88bf89bbfe2
$(package)_git_commit=91348647a86201a9482ad4ad68398152dc3d635e
$(package)_dependencies=rust
ifeq ($(host_os),mingw32)
define $(package)_build_cmds
~/.cargo/bin/cargo build --release --target=x86_64-pc-windows-gnu --verbose

2
libsnark.mk.patch

@ -14,7 +14,7 @@
- ifeq ($(build_os),darwin)
- define $(package)_build_cmds
- CC=gcc-5 CXX=g++-5 CXXFLAGS="-arch x86_64 -DBINARY_OUTPUT -DNO_PT_COMPRESSION=1" $(MAKE) lib DEPINST=$(host_prefix) CURVE=ALT_BN128 MULTICORE=0 NO_PROCPS=1 NO_GTEST=1 NO_DOCS=1 STATIC=1 NO_SUPERCOP=1 FEATUREFLAGS=-DMONTGOMERY_OUTPUT
- CC=gcc-6 CXX=g++-6 CXXFLAGS="-arch x86_64 -DBINARY_OUTPUT -DNO_PT_COMPRESSION=1" $(MAKE) lib DEPINST=$(host_prefix) CURVE=ALT_BN128 MULTICORE=0 NO_PROCPS=1 NO_GTEST=1 NO_DOCS=1 STATIC=1 NO_SUPERCOP=1 FEATUREFLAGS=-DMONTGOMERY_OUTPUT
- endef
- else
define $(package)_build_cmds

61
migratecoin.md

@ -0,0 +1,61 @@
# MigrateCoin protocol
## ExportCoins tx:
```
vin:
[ any ]
vout:
- amount: {burnAmount}
script: OP_RETURN "send to ledger {id} {voutsHash}"
```
* ExportCoin is a standard tx which burns coins in an OP_RETURN
## ImportCoins tx:
```
vin:
- txid: 0000000000000000000000000000000000000000000000000000000000000000
idx: 0
script: CC_EVAL(EVAL_IMPORTCOINS, {momoProof},{exportCoin}) OP_CHECKCRYPTOCONDITION_UNILATERAL
vout:
- [ vouts matching voutsHash in exportCoin ]
```
* ImportCoin transaction has no signature
* ImportCoin is non malleable
* ImportCoin satisfies tx.IsCoinBase()
* ImportCoin uses a new opcode which allows a one sided check (no scriptPubKey)
* ImportCoin must contain CC opcode EVAL_IMPORTCOINS
* ImportCoin fees are equal to the difference between burnAmount in exportCoins and the sum of outputs.

22
src/Makefile.am

@ -263,11 +263,22 @@ libbitcoin_server_a_SOURCES = \
asyncrpcqueue.cpp \
bloom.cpp \
cc/eval.cpp \
cc/importpayout.cpp \
cc/disputepayout.cpp \
cc/import.cpp \
cc/CCassetsCore.cpp \
cc/CCcustom.cpp \
cc/CCtx.cpp \
cc/CCutils.cpp \
cc/assets.cpp \
cc/faucet.cpp \
cc/rewards.cpp \
cc/dice.cpp \
cc/lotto.cpp \
cc/ponzi.cpp \
cc/auction.cpp \
cc/betprotocol.cpp \
chain.cpp \
checkpoints.cpp \
crosschain.cpp \
crypto/haraka.h \
crypto/haraka_portable.h \
crypto/verus_hash.h \
@ -283,12 +294,14 @@ libbitcoin_server_a_SOURCES = \
miner.cpp \
net.cpp \
noui.cpp \
notarisationdb.cpp \
paymentdisclosure.cpp \
paymentdisclosuredb.cpp \
policy/fees.cpp \
pow.cpp \
rest.cpp \
rpcblockchain.cpp \
rpccrosschain.cpp \
rpcmining.cpp \
rpcmisc.cpp \
rpcnet.cpp \
@ -342,6 +355,8 @@ libbitcoin_wallet_a_SOURCES = \
paymentdisclosuredb.cpp \
wallet/rpcdisclosure.cpp \
wallet/rpcdump.cpp \
cc/CCassetstx.cpp \
cc/CCtx.cpp \
wallet/rpcwallet.cpp \
wallet/wallet.cpp \
wallet/wallet_ismine.cpp \
@ -413,6 +428,7 @@ libbitcoin_common_a_SOURCES = \
crypto/verus_hash.h \
crypto/verus_hash.cpp \
hash.cpp \
importcoin.cpp \
key.cpp \
keystore.cpp \
netbase.cpp \
@ -642,7 +658,7 @@ endif
libzcashconsensus_la_LDFLAGS = $(AM_LDFLAGS) -no-undefined $(RELDFLAGS)
libzcashconsensus_la_LIBADD = $(LIBSECP256K1)
libzcashconsensus_la_CPPFLAGS = $(AM_CPPFLAGS) -I$(builddir)/obj -I$(srcdir)/secp256k1/include -DBUILD_BITCOIN_INTERNAL
libzcashconsensus_la_CPPFLAGS = $(AM_CPPFLAGS) -I$(builddir)/obj -I$(srcdir)/secp256k1/include -I$(srcdir)/cryptoconditions/include -DBUILD_BITCOIN_INTERNAL
libzcashconsensus_la_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS)
endif

6
src/Makefile.ktest.include

@ -5,9 +5,13 @@ bin_PROGRAMS += komodo-test
# tool for generating our public parameters
komodo_test_SOURCES = \
test-komodo/main.cpp \
test-komodo/testutils.cpp \
test-komodo/test_cryptoconditions.cpp \
test-komodo/test_coinimport.cpp \
test-komodo/test_eval_bet.cpp \
test-komodo/test_eval_notarisation.cpp
test-komodo/test_eval_notarisation.cpp \
test-komodo/test_crosschain.cpp \
test-komodo/test_parse_notarisation.cpp
komodo_test_CPPFLAGS = $(komodod_CPPFLAGS)

1
src/Makefile.test.include

@ -45,7 +45,6 @@ BITCOIN_TESTS =\
test/arith_uint256_tests.cpp \
test/bignum.h \
test/addrman_tests.cpp \
test/alert_tests.cpp \
test/allocator_tests.cpp \
test/base32_tests.cpp \
test/base58_tests.cpp \

2
src/ac/dsec

@ -0,0 +1,2 @@
#!/bin/bash
./komodo-cli -ac_name=DSEC $1 $2 $3 $4 $5 $6

2
src/ac/eql

@ -0,0 +1,2 @@
#!/bin/bash
./komodo-cli -ac_name=EQL $1 $2 $3 $4 $5 $6

2
src/ac/glxt

@ -0,0 +1,2 @@
#!/bin/bash
./komodo-cli -ac_name=GLXT $1 $2 $3 $4 $5 $6

2
src/amount.cpp

@ -7,7 +7,7 @@
#include "tinyformat.h"
const std::string CURRENCY_UNIT = "ZEC";
const std::string CURRENCY_UNIT = "KMD";
CFeeRate::CFeeRate(const CAmount& nFeePaid, size_t nSize)
{

63
src/assetchains

@ -1,56 +1,19 @@
#!/bin/bash
set -eo pipefail
# You can now add delay line to pubkey.txt file
source pubkey.txt
args=("$@")
overide_args="$@"
seed_ip=`getent hosts zero.kolo.supernet.org | awk '{ print $1 }'`
komodo_binary='./komodod'
delay=20
function komodo_asset ()
{
if [ $[RANDOM % 10] == 1 ]
then
gen=" -gen"
else
gen=""
fi
if [ -n "$2" ]
then
supply=" -ac_supply=$2"
else
supply=" "
fi
$komodo_binary -pubkey=$pubkey -ac_name=$1 $supply -addnode=$seed_ip $gen $args &
sleep $delay
}
if [ -z "$delay" ]; then delay=20; fi
#set -x
./listassetchainparams | while read args; do
gen=""
if [ $[RANDOM % 10] == 1 ]; then
gen=" -gen"
fi
komodo_asset REVS 1300000
komodo_asset SUPERNET 816061
komodo_asset DEX 999999
komodo_asset PANGEA 999999
komodo_asset JUMBLR 999999
komodo_asset BET 999999
komodo_asset CRYPTO 999999
komodo_asset HODL 9999999
komodo_asset MSHARK 1400000
komodo_asset BOTS 999999
komodo_asset MGW 999999
komodo_asset COQUI 72000000
komodo_asset WLC 210000000
komodo_asset KV 1000000
komodo_asset CEAL 366666666
komodo_asset MESH 1000007
komodo_asset MNZ 257142858
komodo_asset AXO 200000000
komodo_asset ETOMIC 100000000
komodo_asset BTCH 20998641
komodo_asset PIZZA 100000000
komodo_asset BEER 100000000
komodo_asset NINJA 100000000
komodo_asset OOT 216000000
komodo_asset BNTN 500000000
komodo_asset CHAIN 999999
komodo_asset PRLPAY 500000000
./komodod $gen $args $overide_args -pubkey=$pubkey -addnode=$seed_ip &
sleep $delay
done

135
src/assetchains.json

@ -0,0 +1,135 @@
[
{
"ac_name": "REVS",
"ac_supply": "1300000"
},
{
"ac_name": "SUPERNET",
"ac_supply": "816061"
},
{
"ac_name": "DEX",
"ac_supply": "999999"
},
{
"ac_name": "PANGEA",
"ac_supply": "999999"
},
{
"ac_name": "JUMBLR",
"ac_supply": "999999"
},
{
"ac_name": "BET",
"ac_supply": "999999"
},
{
"ac_name": "CRYPTO",
"ac_supply": "999999"
},
{
"ac_name": "HODL",
"ac_supply": "9999999"
},
{
"ac_name": "MSHARK",
"ac_supply": "1400000"
},
{
"ac_name": "BOTS",
"ac_supply": "999999"
},
{
"ac_name": "MGW",
"ac_supply": "999999"
},
{
"ac_name": "COQUI",
"ac_supply": "72000000"
},
{
"ac_name": "WLC",
"ac_supply": "210000000"
},
{
"ac_name": "KV",
"ac_supply": "1000000"
},
{
"ac_name": "CEAL",
"ac_supply": "366666666"
},
{
"ac_name": "MESH",
"ac_supply": "1000007"
},
{
"ac_name": "MNZ",
"ac_supply": "257142858"
},
{
"ac_name": "AXO",
"ac_supply": "200000000"
},
{
"ac_name": "ETOMIC",
"ac_supply": "100000000"
},
{
"ac_name": "BTCH",
"ac_supply": "20998641"
},
{
"ac_name": "PIZZA",
"ac_supply": "100000000"
},
{
"ac_name": "BEER",
"ac_supply": "100000000"
},
{
"ac_name": "NINJA",
"ac_supply": "100000000"
},
{
"ac_name": "OOT",
"ac_supply": "216000000"
},
{
"ac_name": "BNTN",
"ac_supply": "500000000"
},
{
"ac_name": "CHAIN",
"ac_supply": "999999"
},
{
"ac_name": "PRLPAY",
"ac_supply": "500000000"
},
{
"ac_name": "DSEC",
"ac_supply": "7000000"
},
{
"ac_name": "GLXT",
"ac_supply": "10000000000"
},
{
"ac_name": "EQL",
"ac_supply": "500000000"
},
{
"ac_name": "ZILLA",
"ac_supply": "11000000"
},
{
"ac_name": "RFOX",
"ac_supply": "1000000000",
"ac_reward": "100000000"
},
{
"ac_name": "SEC",
"ac_supply": "1000000000"
}
]

72
src/assetchains.old

@ -31,68 +31,10 @@ echo $pubkey
./komodod -pubkey=$pubkey -ac_name=BNTN -ac_supply=500000000 -addnode=94.130.169.205 &
./komodod -pubkey=$pubkey -ac_name=CHAIN -ac_supply=999999 -addnode=78.47.146.222 &
./komodod -pubkey=$pubkey -ac_name=PRLPAY -ac_supply=500000000 -addnode=13.250.226.125 &
#sleep $delay
#./komodod -pubkey=$pubkey -ac_name=USD -addnode=78.47.196.146 $1 &
#sleep $delay
#./komodod -pubkey=$pubkey -ac_name=EUR -addnode=78.47.196.146 $1 &
#sleep $delay
#./komodod -pubkey=$pubkey -ac_name=JPY -addnode=78.47.196.146 $1 &
#sleep $delay
#./komodod -pubkey=$pubkey -ac_name=GBP -addnode=78.47.196.146 $1 &
#sleep $delay
#./komodod -pubkey=$pubkey -ac_name=AUD -addnode=78.47.196.146 $1 &
#sleep $delay
#./komodod -pubkey=$pubkey -ac_name=CAD -addnode=78.47.196.146 $1 &
#sleep $delay
#./komodod -pubkey=$pubkey -ac_name=CHF -addnode=78.47.196.146 $1 &
#sleep $delay
#./komodod -pubkey=$pubkey -ac_name=NZD -addnode=78.47.196.146 $1 &
#sleep $delay
#./komodod -pubkey=$pubkey -ac_name=CNY -addnode=78.47.196.146 $1 &
#sleep $delay
#./komodod -pubkey=$pubkey -ac_name=RUB -addnode=78.47.196.146 $1 &
#sleep $delay
#./komodod -pubkey=$pubkey -ac_name=MXN -addnode=78.47.196.146 $1 &
#sleep $delay
#./komodod -pubkey=$pubkey -ac_name=BRL -addnode=78.47.196.146 $1 &
#sleep $delay
#./komodod -pubkey=$pubkey -ac_name=INR -addnode=78.47.196.146 $1 &
#sleep $delay
#./komodod -pubkey=$pubkey -ac_name=HKD -addnode=78.47.196.146 $1 &
#sleep $delay
#./komodod -pubkey=$pubkey -ac_name=TRY -addnode=78.47.196.146 $1 &
#sleep $delay
#./komodod -pubkey=$pubkey -ac_name=ZAR -addnode=78.47.196.146 $1 &
#sleep $delay
#./komodod -pubkey=$pubkey -ac_name=PLN -addnode=78.47.196.146 $1 &
#sleep $delay
#./komodod -pubkey=$pubkey -ac_name=NOK -addnode=78.47.196.146 $1 &
#sleep $delay
#./komodod -pubkey=$pubkey -ac_name=SEK -addnode=78.47.196.146 $1 &
#sleep $delay
#./komodod -pubkey=$pubkey -ac_name=DKK -addnode=78.47.196.146 $1 &
#sleep $delay
#./komodod -pubkey=$pubkey -ac_name=CZK -addnode=78.47.196.146 $1 &
#sleep $delay
#./komodod -pubkey=$pubkey -ac_name=HUF -addnode=78.47.196.146 $1 &
#sleep $delay
#./komodod -pubkey=$pubkey -ac_name=ILS -addnode=78.47.196.146 $1 &
#sleep $delay
#./komodod -pubkey=$pubkey -ac_name=KRW -addnode=78.47.196.146 $1 &
#sleep $delay
#./komodod -pubkey=$pubkey -ac_name=MYR -addnode=78.47.196.146 $1 &
#sleep $delay
#./komodod -pubkey=$pubkey -ac_name=PHP -addnode=78.47.196.146 $1 &
#sleep $delay
#./komodod -pubkey=$pubkey -ac_name=RON -addnode=78.47.196.146 $1 &
#sleep $delay
#./komodod -pubkey=$pubkey -ac_name=SGD -addnode=78.47.196.146 $1 &
#sleep $delay
#./komodod -pubkey=$pubkey -ac_name=THB -addnode=78.47.196.146 $1 &
#sleep $delay
#./komodod -pubkey=$pubkey -ac_name=BGN -addnode=78.47.196.146 $1 &
#sleep $delay
#./komodod -pubkey=$pubkey -ac_name=IDR -addnode=78.47.196.146 $1 &
#sleep $delay
#./komodod -pubkey=$pubkey -ac_name=HRK -addnode=78.47.196.146 $1 &
./komodod -pubkey=$pubkey -ac_name=DSEC -ac_supply=7000000 -addnode=185.148.147.30 &
./komodod -pubkey=$pubkey -ac_name=GLXT -ac_supply=10000000000 -addnode=13.230.224.15 &
./komodod -pubkey=$pubkey -ac_name=EQL -ac_supply=500000000 -addnode=46.101.124.153 &
./komodod -pubkey=$pubkey -ac_name=ZILLA -ac_supply=11000000 -addnode=54.39.23.248 &
./komodod -pubkey=$pubkey -ac_name=RFOX -ac_supply=1000000000 -ac_reward=100000000 -addnode=78.47.196.146 &
~/VerusCoin/src/komodod -pubkey=$pubkey -ac_name=VRSC -ac_algo=verushash -ac_cc=1 -ac_veruspos=50 -ac_supply=0 -ac_eras=3 -ac_reward=0,38400000000,2400000000 -ac_halving=1,43200,1051920 -ac_decay=100000000,0,0 -ac_end=10080,226080,0 -ac_timelockgte=19200000000 -ac_timeunlockfrom=129600 -ac_timeunlockto=1180800 -addnode=185.25.48.236 -addnode=185.64.105.111 &
./komodod -pubkey=$pubkey -ac_name=SEC -ac_cc=333 -ac_supply=1000000000 -addnode=185.148.145.43 &

41
src/assetchains_stop

@ -1,39 +1,6 @@
#!/bin/bash
args=("$@")
komodo_cli='./komodo-cli'
delay=20
set -eo pipefail
function komodo_stop ()
{
$komodo_cli --ac_name=$1 stop
}
#set -x
komodo_stop REVS
komodo_stop SUPERNET
komodo_stop DEX
komodo_stop PANGEA
komodo_stop JUMBLR
komodo_stop BET
komodo_stop CRYPTO
komodo_stop HODL
komodo_stop MSHARK
komodo_stop BOTS
komodo_stop MGW
komodo_stop COQUI
komodo_stop WLC
komodo_stop KV
komodo_stop CEAL
komodo_stop MESH
komodo_stop MNZ
komodo_stop AXO
komodo_stop ETOMIC
komodo_stop BTCH
komodo_stop PIZZA
komodo_stop BEER
komodo_stop NINJA
komodo_stop OOT
komodo_stop BNTN
komodo_stop CHAIN
komodo_stop PRLPAY
./listassetchains | while read chain; do
./komodo-cli --ac_name=$chain stop
done

12
src/bitcoind.cpp

@ -144,21 +144,21 @@ bool AppInit(int argc, char* argv[])
ReadConfigFile(mapArgs, mapMultiArgs);
} catch (const missing_zcash_conf& e) {
fprintf(stderr,
(_("Before starting zcashd, you need to create a configuration file:\n"
(_("Before starting komodod, you need to create a configuration file:\n"
"%s\n"
"It can be completely empty! That indicates you are happy with the default\n"
"configuration of zcashd. But requiring a configuration file to start ensures\n"
"that zcashd won't accidentally compromise your privacy if there was a default\n"
"configuration of komodod. But requiring a configuration file to start ensures\n"
"that komodod won't accidentally compromise your privacy if there was a default\n"
"option you needed to change.\n"
"\n"
"You can look at the example configuration file for suggestions of default\n"
"options that you may want to change. It should be in one of these locations,\n"
"depending on how you installed Zcash:\n") +
"depending on how you installed Komodo:\n") +
_("- Source code: %s\n"
"- .deb package: %s\n")).c_str(),
GetConfigFile().string().c_str(),
"contrib/debian/examples/zcash.conf",
"/usr/share/doc/zcash/examples/zcash.conf");
"contrib/debian/examples/komodo.conf",
"/usr/share/doc/komodo/examples/komodo.conf");
return false;
} catch (const std::exception& e) {
fprintf(stderr,"Error reading configuration file: %s\n", e.what());

65
src/cc/CCassets.h

@ -0,0 +1,65 @@
/******************************************************************************
* Copyright © 2014-2018 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. *
* *
******************************************************************************/
/*
CCassetstx has the functions that create the EVAL_ASSETS transactions. It is expected that rpc calls would call these functions. For EVAL_ASSETS, the rpc functions are in rpcwallet.cpp
CCassetsCore has functions that are used in two contexts, both during rpc transaction create time and also during the blockchain validation. Using the identical functions is a good way to prevent them from being mismatched. The must match or the transaction will get rejected.
*/
#ifndef CC_ASSETS_H
#define CC_ASSETS_H
#include "CCinclude.h"
// CCcustom
bool AssetsValidate(struct CCcontract_info *cp,Eval* eval,const CTransaction &tx);
// CCassetsCore
//CTxOut MakeAssetsVout(CAmount nValue,CPubKey pk);
CScript EncodeAssetCreateOpRet(uint8_t funcid,std::vector<uint8_t> origpubkey,std::string name,std::string description);
CScript EncodeAssetOpRet(uint8_t funcid,uint256 assetid,uint256 assetid2,int64_t price,std::vector<uint8_t> origpubkey);
bool DecodeAssetCreateOpRet(const CScript &scriptPubKey,std::vector<uint8_t> &origpubkey,std::string &name,std::string &description);
uint8_t DecodeAssetOpRet(const CScript &scriptPubKey,uint256 &assetid,uint256 &assetid2,int64_t &price,std::vector<uint8_t> &origpubkey);
bool SetAssetOrigpubkey(std::vector<uint8_t> &origpubkey,int64_t &price,const CTransaction &tx);
int64_t IsAssetvout(int64_t &price,std::vector<uint8_t> &origpubkey,const CTransaction& tx,int32_t v,uint256 refassetid);
bool ValidateBidRemainder(int64_t remaining_price,int64_t remaining_nValue,int64_t orig_nValue,int64_t received_nValue,int64_t paidprice,int64_t totalprice);
bool ValidateAskRemainder(int64_t remaining_price,int64_t remaining_nValue,int64_t orig_nValue,int64_t received_nValue,int64_t paidprice,int64_t totalprice);
bool ValidateSwapRemainder(int64_t remaining_price,int64_t remaining_nValue,int64_t orig_nValue,int64_t received_nValue,int64_t paidprice,int64_t totalprice);
bool SetBidFillamounts(int64_t &paid,int64_t &remaining_price,int64_t orig_nValue,int64_t &received,int64_t totalprice);
bool SetAskFillamounts(int64_t &paid,int64_t &remaining_price,int64_t orig_nValue,int64_t &received,int64_t totalprice);
bool SetSwapFillamounts(int64_t &paid,int64_t &remaining_price,int64_t orig_nValue,int64_t &received,int64_t totalprice);
int64_t AssetValidateBuyvin(struct CCcontract_info *cp,Eval* eval,int64_t &tmpprice,std::vector<uint8_t> &tmporigpubkey,char *CCaddr,char *origaddr,const CTransaction &tx,uint256 refassetid);
int64_t AssetValidateSellvin(struct CCcontract_info *cp,Eval* eval,int64_t &tmpprice,std::vector<uint8_t> &tmporigpubkey,char *CCaddr,char *origaddr,const CTransaction &tx,uint256 assetid);
bool AssetExactAmounts(struct CCcontract_info *cp,int64_t &inputs,int32_t starti,int64_t &outputs,Eval* eval,const CTransaction &tx,uint256 assetid);
// CCassetstx
int64_t GetAssetBalance(CPubKey pk,uint256 tokenid);
int64_t AddAssetInputs(CMutableTransaction &mtx,CPubKey pk,uint256 assetid,int64_t total,int32_t maxinputs);
UniValue AssetOrders(uint256 tokenid);
UniValue AssetInfo(uint256 tokenid);
UniValue AssetList();
std::string CreateAsset(int64_t txfee,int64_t assetsupply,std::string name,std::string description);
std::string AssetTransfer(int64_t txfee,uint256 assetid,std::vector<uint8_t> destpubkey,int64_t total);
std::string CreateBuyOffer(int64_t txfee,int64_t bidamount,uint256 assetid,int64_t pricetotal);
std::string CancelBuyOffer(int64_t txfee,uint256 assetid,uint256 bidtxid);
std::string FillBuyOffer(int64_t txfee,uint256 assetid,uint256 bidtxid,int64_t fillamount);
std::string CreateSell(int64_t txfee,int64_t askamount,uint256 assetid,int64_t pricetotal);
std::string CreateSwap(int64_t txfee,int64_t askamount,uint256 assetid,uint256 assetid2,int64_t pricetotal);
std::string CancelSell(int64_t txfee,uint256 assetid,uint256 asktxid);
std::string FillSell(int64_t txfee,uint256 assetid,uint256 assetid2,uint256 asktxid,int64_t fillamount);
#endif

478
src/cc/CCassetsCore.cpp

@ -0,0 +1,478 @@
/******************************************************************************
* Copyright © 2014-2018 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 "CCassets.h"
/*
The SetAssetFillamounts() and ValidateAssetRemainder() work in tandem to calculate the vouts for a fill and to validate the vouts, respectively.
This pair of functions are critical to make sure the trading is correct and is the trickiest part of the assets contract.
//vin.0: normal input
//vin.1: unspendable.(vout.0 from buyoffer) buyTx.vout[0]
//vin.2+: valid CC output satisfies buyoffer (*tx.vin[2])->nValue
//vout.0: remaining amount of bid to unspendable
//vout.1: vin.1 value to signer of vin.2
//vout.2: vin.2 assetoshis to original pubkey
//vout.3: CC output for assetoshis change (if any)
//vout.4: normal output for change (if any)
//vout.n-1: opreturn [EVAL_ASSETS] ['B'] [assetid] [remaining asset required] [origpubkey]
ValidateAssetRemainder(remaining_price,tx.vout[0].nValue,nValue,tx.vout[1].nValue,tx.vout[2].nValue,totalunits);
Yes, this is quite confusing...
In ValudateAssetRemainder the naming convention is nValue is the coin/asset with the offer on the books and "units" is what it is being paid in. The high level check is to make sure we didnt lose any coins or assets, the harder to validate is the actual price paid as the "orderbook" is in terms of the combined nValue for the combined totalunits.
We assume that the effective unit cost in the orderbook is valid and that that amount was paid and also that any remainder will be close enough in effective unit cost to not matter. At the edge cases, this will probably be not true and maybe some orders wont be practically fillable when reduced to fractional state. However, the original pubkey that created the offer can always reclaim it.
*/
bool ValidateBidRemainder(int64_t remaining_units,int64_t remaining_nValue,int64_t orig_nValue,int64_t received_nValue,int64_t paidunits,int64_t totalunits)
{
int64_t unitprice,recvunitprice,newunitprice=0;
if ( orig_nValue == 0 || received_nValue == 0 || paidunits == 0 || totalunits == 0 )
{
fprintf(stderr,"ValidateAssetRemainder: orig_nValue == %llu || received_nValue == %llu || paidunits == %llu || totalunits == %llu\n",(long long)orig_nValue,(long long)received_nValue,(long long)paidunits,(long long)totalunits);
return(false);
}
else if ( totalunits != (remaining_units + paidunits) )
{
fprintf(stderr,"ValidateAssetRemainder: totalunits %llu != %llu (remaining_units %llu + %llu paidunits)\n",(long long)totalunits,(long long)(remaining_units + paidunits),(long long)remaining_units,(long long)paidunits);
return(false);
}
else if ( orig_nValue != (remaining_nValue + received_nValue) )
{
fprintf(stderr,"ValidateAssetRemainder: orig_nValue %llu != %llu (remaining_nValue %llu + %llu received_nValue)\n",(long long)orig_nValue,(long long)(remaining_nValue - received_nValue),(long long)remaining_nValue,(long long)received_nValue);
return(false);
}
else
{
unitprice = (orig_nValue * COIN) / totalunits;
recvunitprice = (received_nValue * COIN) / paidunits;
if ( remaining_units != 0 )
newunitprice = (remaining_nValue * COIN) / remaining_units;
if ( recvunitprice < unitprice )
{
fprintf(stderr,"error recvunitprice %.16f < %.16f unitprice, new unitprice %.16f\n",(double)recvunitprice/(COIN*COIN),(double)unitprice/(COIN*COIN),(double)newunitprice/(COIN*COIN));
return(false);
}
fprintf(stderr,"orig %llu total %llu, recv %llu paid %llu,recvunitprice %.16f >= %.16f unitprice, new unitprice %.16f\n",(long long)orig_nValue,(long long)totalunits,(long long)received_nValue,(long long)paidunits,(double)recvunitprice/(COIN*COIN),(double)unitprice/(COIN*COIN),(double)newunitprice/(COIN*COIN));
}
return(true);
}
bool SetBidFillamounts(int64_t &received_nValue,int64_t &remaining_units,int64_t orig_nValue,int64_t &paidunits,int64_t totalunits)
{
int64_t remaining_nValue,unitprice; double dprice;
if ( totalunits == 0 )
{
received_nValue = remaining_units = paidunits = 0;
return(false);
}
if ( paidunits >= totalunits )
{
paidunits = totalunits;
received_nValue = orig_nValue;
remaining_units = 0;
fprintf(stderr,"totally filled!\n");
return(true);
}
remaining_units = (totalunits - paidunits);
unitprice = (orig_nValue * COIN) / totalunits;
received_nValue = (paidunits * unitprice) / COIN;
if ( unitprice > 0 && received_nValue > 0 && received_nValue <= orig_nValue )
{
remaining_nValue = (orig_nValue - received_nValue);
printf("total.%llu - paid.%llu, remaining %llu <- %llu (%llu - %llu)\n",(long long)totalunits,(long long)paidunits,(long long)remaining_nValue,(long long)(orig_nValue - received_nValue),(long long)orig_nValue,(long long)received_nValue);
return(ValidateBidRemainder(remaining_units,remaining_nValue,orig_nValue,received_nValue,paidunits,totalunits));
} else return(false);
}
bool SetAskFillamounts(int64_t &received_assetoshis,int64_t &remaining_nValue,int64_t orig_assetoshis,int64_t &paid_nValue,int64_t total_nValue)
{
int64_t remaining_assetoshis; double dunitprice;
if ( total_nValue == 0 )
{
received_assetoshis = remaining_nValue = paid_nValue = 0;
return(false);
}
if ( paid_nValue >= total_nValue )
{
paid_nValue = total_nValue;
received_assetoshis = orig_assetoshis;
remaining_nValue = 0;
fprintf(stderr,"totally filled!\n");
return(true);
}
remaining_nValue = (total_nValue - paid_nValue);
dunitprice = ((double)total_nValue / orig_assetoshis);
received_assetoshis = (paid_nValue / dunitprice);
fprintf(stderr,"remaining_nValue %.8f (%.8f - %.8f)\n",(double)remaining_nValue/COIN,(double)total_nValue/COIN,(double)paid_nValue/COIN);
fprintf(stderr,"unitprice %.8f received_assetoshis %llu orig %llu\n",dunitprice/COIN,(long long)received_assetoshis,(long long)orig_assetoshis);
if ( fabs(dunitprice) > SMALLVAL && received_assetoshis > 0 && received_assetoshis <= orig_assetoshis )
{
remaining_assetoshis = (orig_assetoshis - received_assetoshis);
return(ValidateAskRemainder(remaining_nValue,remaining_assetoshis,orig_assetoshis,received_assetoshis,paid_nValue,total_nValue));
} else return(false);
}
bool ValidateAskRemainder(int64_t remaining_nValue,int64_t remaining_assetoshis,int64_t orig_assetoshis,int64_t received_assetoshis,int64_t paid_nValue,int64_t total_nValue)
{
int64_t unitprice,recvunitprice,newunitprice=0;
if ( orig_assetoshis == 0 || received_assetoshis == 0 || paid_nValue == 0 || total_nValue == 0 )
{
fprintf(stderr,"ValidateAssetRemainder: orig_assetoshis == %llu || received_assetoshis == %llu || paid_nValue == %llu || total_nValue == %llu\n",(long long)orig_assetoshis,(long long)received_assetoshis,(long long)paid_nValue,(long long)total_nValue);
return(false);
}
else if ( total_nValue != (remaining_nValue + paid_nValue) )
{
fprintf(stderr,"ValidateAssetRemainder: total_nValue %llu != %llu (remaining_nValue %llu + %llu paid_nValue)\n",(long long)total_nValue,(long long)(remaining_nValue + paid_nValue),(long long)remaining_nValue,(long long)paid_nValue);
return(false);
}
else if ( orig_assetoshis != (remaining_assetoshis + received_assetoshis) )
{
fprintf(stderr,"ValidateAssetRemainder: orig_assetoshis %llu != %llu (remaining_nValue %llu + %llu received_nValue)\n",(long long)orig_assetoshis,(long long)(remaining_assetoshis - received_assetoshis),(long long)remaining_assetoshis,(long long)received_assetoshis);
return(false);
}
else
{
unitprice = (total_nValue / orig_assetoshis);
recvunitprice = (paid_nValue / received_assetoshis);
if ( remaining_nValue != 0 )
newunitprice = (remaining_nValue / remaining_assetoshis);
if ( recvunitprice < unitprice )
{
fprintf(stderr,"error recvunitprice %.8f < %.8f unitprice, new unitprice %.8f\n",(double)recvunitprice/COIN,(double)unitprice/COIN,(double)newunitprice/COIN);
return(false);
}
fprintf(stderr,"got recvunitprice %.8f >= %.8f unitprice, new unitprice %.8f\n",(double)recvunitprice/COIN,(double)unitprice/COIN,(double)newunitprice/COIN);
}
return(true);
}
bool SetSwapFillamounts(int64_t &received_assetoshis,int64_t &remaining_assetoshis2,int64_t orig_assetoshis,int64_t &paid_assetoshis2,int64_t total_assetoshis2)
{
int64_t remaining_assetoshis; double dunitprice;
if ( total_assetoshis2 == 0 )
{
fprintf(stderr,"total_assetoshis2.0 origsatoshis.%llu paid_assetoshis2.%llu\n",(long long)orig_assetoshis,(long long)paid_assetoshis2);
received_assetoshis = remaining_assetoshis2 = paid_assetoshis2 = 0;
return(false);
}
if ( paid_assetoshis2 >= total_assetoshis2 )
{
paid_assetoshis2 = total_assetoshis2;
received_assetoshis = orig_assetoshis;
remaining_assetoshis2 = 0;
fprintf(stderr,"totally filled!\n");
return(true);
}
remaining_assetoshis2 = (total_assetoshis2 - paid_assetoshis2);
dunitprice = ((double)total_assetoshis2 / orig_assetoshis);
received_assetoshis = (paid_assetoshis2 / dunitprice);
fprintf(stderr,"remaining_assetoshis2 %llu (%llu - %llu)\n",(long long)remaining_assetoshis2/COIN,(long long)total_assetoshis2/COIN,(long long)paid_assetoshis2/COIN);
fprintf(stderr,"unitprice %.8f received_assetoshis %llu orig %llu\n",dunitprice/COIN,(long long)received_assetoshis,(long long)orig_assetoshis);
if ( fabs(dunitprice) > SMALLVAL && received_assetoshis > 0 && received_assetoshis <= orig_assetoshis )
{
remaining_assetoshis = (orig_assetoshis - received_assetoshis);
return(ValidateAskRemainder(remaining_assetoshis2,remaining_assetoshis,orig_assetoshis,received_assetoshis,paid_assetoshis2,total_assetoshis2));
} else return(false);
}
bool ValidateSwapRemainder(int64_t remaining_price,int64_t remaining_nValue,int64_t orig_nValue,int64_t received_nValue,int64_t paidunits,int64_t totalunits)
{
int64_t unitprice,recvunitprice,newunitprice=0;
if ( orig_nValue == 0 || received_nValue == 0 || paidunits == 0 || totalunits == 0 )
{
fprintf(stderr,"ValidateAssetRemainder: orig_nValue == %llu || received_nValue == %llu || paidunits == %llu || totalunits == %llu\n",(long long)orig_nValue,(long long)received_nValue,(long long)paidunits,(long long)totalunits);
return(false);
}
else if ( totalunits != (remaining_price + paidunits) )
{
fprintf(stderr,"ValidateAssetRemainder: totalunits %llu != %llu (remaining_price %llu + %llu paidunits)\n",(long long)totalunits,(long long)(remaining_price + paidunits),(long long)remaining_price,(long long)paidunits);
return(false);
}
else if ( orig_nValue != (remaining_nValue + received_nValue) )
{
fprintf(stderr,"ValidateAssetRemainder: orig_nValue %llu != %llu (remaining_nValue %llu + %llu received_nValue)\n",(long long)orig_nValue,(long long)(remaining_nValue - received_nValue),(long long)remaining_nValue,(long long)received_nValue);
return(false);
}
else
{
unitprice = (orig_nValue * COIN) / totalunits;
recvunitprice = (received_nValue * COIN) / paidunits;
if ( remaining_price != 0 )
newunitprice = (remaining_nValue * COIN) / remaining_price;
if ( recvunitprice < unitprice )
{
fprintf(stderr,"error recvunitprice %.16f < %.16f unitprice, new unitprice %.16f\n",(double)recvunitprice/(COIN*COIN),(double)unitprice/(COIN*COIN),(double)newunitprice/(COIN*COIN));
return(false);
}
fprintf(stderr,"recvunitprice %.16f >= %.16f unitprice, new unitprice %.16f\n",(double)recvunitprice/(COIN*COIN),(double)unitprice/(COIN*COIN),(double)newunitprice/(COIN*COIN));
}
return(true);
}
CScript EncodeAssetCreateOpRet(uint8_t funcid,std::vector<uint8_t> origpubkey,std::string name,std::string description)
{
CScript opret; uint8_t evalcode = EVAL_ASSETS;
opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << origpubkey << name << description);
return(opret);
}
CScript EncodeAssetOpRet(uint8_t funcid,uint256 assetid,uint256 assetid2,int64_t price,std::vector<uint8_t> origpubkey)
{
CScript opret; uint8_t evalcode = EVAL_ASSETS;
assetid = revuint256(assetid);
switch ( funcid )
{
case 't': case 'x': case 'o':
opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << assetid);
break;
case 's': case 'b': case 'S': case 'B':
opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << assetid << price << origpubkey);
break;
case 'E': case 'e':
assetid2 = revuint256(assetid2);
opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << assetid << assetid2 << price << origpubkey);
break;
default:
fprintf(stderr,"EncodeOpRet: illegal funcid.%02x\n",funcid);
opret << OP_RETURN;
break;
}
return(opret);
}
bool DecodeAssetCreateOpRet(const CScript &scriptPubKey,std::vector<uint8_t> &origpubkey,std::string &name,std::string &description)
{
std::vector<uint8_t> vopret; uint8_t evalcode,funcid,*script;
GetOpReturnData(scriptPubKey, vopret);
script = (uint8_t *)vopret.data();
if ( script != 0 && vopret.size() > 2 && script[0] == EVAL_ASSETS && script[1] == 'c' )
{
if ( E_UNMARSHAL(vopret,ss >> evalcode; ss >> funcid; ss >> origpubkey; ss >> name; ss >> description) != 0 )
return(true);
}
return(0);
}
uint8_t DecodeAssetOpRet(const CScript &scriptPubKey,uint256 &assetid,uint256 &assetid2,int64_t &price,std::vector<uint8_t> &origpubkey)
{
std::vector<uint8_t> vopret; uint8_t funcid=0,*script,e,f;
GetOpReturnData(scriptPubKey, vopret);
script = (uint8_t *)vopret.data();
memset(&assetid,0,sizeof(assetid));
memset(&assetid2,0,sizeof(assetid2));
price = 0;
if ( script != 0 && script[0] == EVAL_ASSETS )
{
funcid = script[1];
//fprintf(stderr,"decode.[%c]\n",funcid);
switch ( funcid )
{
case 'c': return(funcid);
break;
case 't': case 'x': case 'o':
if ( E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> assetid) != 0 )
{
assetid = revuint256(assetid);
return(funcid);
}
break;
case 's': case 'b': case 'S': case 'B':
if ( E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> assetid; ss >> price; ss >> origpubkey) != 0 )
{
assetid = revuint256(assetid);
//fprintf(stderr,"got price %llu\n",(long long)price);
return(funcid);
}
break;
case 'E': case 'e':
if ( E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> assetid; ss >> assetid2; ss >> price; ss >> origpubkey) != 0 )
{
//fprintf(stderr,"got price %llu\n",(long long)price);
assetid = revuint256(assetid);
assetid2 = revuint256(assetid2);
return(funcid);
}
break;
default:
fprintf(stderr,"DecodeAssetOpRet: illegal funcid.%02x\n",funcid);
funcid = 0;
break;
}
}
return(funcid);
}
bool SetAssetOrigpubkey(std::vector<uint8_t> &origpubkey,int64_t &price,const CTransaction &tx)
{
uint256 assetid,assetid2;
if ( tx.vout.size() > 0 && DecodeAssetOpRet(tx.vout[tx.vout.size()-1].scriptPubKey,assetid,assetid2,price,origpubkey) != 0 )
return(true);
else return(false);
}
bool GetAssetorigaddrs(struct CCcontract_info *cp,char *CCaddr,char *destaddr,const CTransaction& tx)
{
uint256 assetid,assetid2; int64_t price,nValue=0; int32_t n; uint8_t funcid; std::vector<uint8_t> origpubkey; CScript script;
n = tx.vout.size();
if ( n == 0 || (funcid= DecodeAssetOpRet(tx.vout[n-1].scriptPubKey,assetid,assetid2,price,origpubkey)) == 0 )
return(false);
if ( GetCCaddress(cp,CCaddr,pubkey2pk(origpubkey)) != 0 && Getscriptaddress(destaddr,CScript() << origpubkey << OP_CHECKSIG) != 0 )
return(true);
else return(false);
}
int64_t IsAssetvout(int64_t &price,std::vector<uint8_t> &origpubkey,const CTransaction& tx,int32_t v,uint256 refassetid)
{
uint256 assetid,assetid2; int64_t nValue=0; int32_t n; uint8_t funcid;
if ( tx.vout[v].scriptPubKey.IsPayToCryptoCondition() != 0 ) // maybe check address too?
{
n = tx.vout.size();
nValue = tx.vout[v].nValue;
//fprintf(stderr,"CC vout v.%d of n.%d %.8f\n",v,n,(double)nValue/COIN);
if ( v >= n-1 )
return(0);
if ( (funcid= DecodeAssetOpRet(tx.vout[n-1].scriptPubKey,assetid,assetid2,price,origpubkey)) == 0 )
{
fprintf(stderr,"null decodeopret\n");
return(0);
}
else if ( funcid == 'c' )
{
if ( refassetid == tx.GetHash() && v == 0 )
return(nValue);
}
else if ( (funcid == 'b' || funcid == 'B') && v == 0 ) // critical! 'b'/'B' vout0 is NOT asset
return(0);
else if ( funcid != 'E' )
{
if ( assetid == refassetid )
return(nValue);
}
else if ( funcid == 'E' )
{
if ( v < 2 && assetid == refassetid )
return(nValue);
else if ( v == 2 && assetid2 == refassetid )
return(nValue);
}
}
//fprintf(stderr,"Isassetvout: normal output v.%d %.8f\n",v,(double)tx.vout[v].nValue/COIN);
return(0);
}
int64_t AssetValidateCCvin(struct CCcontract_info *cp,Eval* eval,char *CCaddr,char *origaddr,const CTransaction &tx,int32_t vini,CTransaction &vinTx)
{
uint256 hashBlock; char destaddr[64];
origaddr[0] = destaddr[0] = CCaddr[0] = 0;
if ( tx.vin.size() < 2 )
return eval->Invalid("not enough for CC vins");
else if ( tx.vin[vini].prevout.n != 0 )
return eval->Invalid("vin1 needs to be buyvin.vout[0]");
else if ( eval->GetTxUnconfirmed(tx.vin[vini].prevout.hash,vinTx,hashBlock) == 0 )
{
int32_t z;
for (z=31; z>=0; z--)
fprintf(stderr,"%02x",((uint8_t *)&tx.vin[vini].prevout.hash)[z]);
fprintf(stderr," vini.%d\n",vini);
return eval->Invalid("always should find CCvin, but didnt");
}
else if ( Getscriptaddress(destaddr,vinTx.vout[tx.vin[vini].prevout.n].scriptPubKey) == 0 || strcmp(destaddr,(char *)cp->unspendableCCaddr) != 0 )
{
fprintf(stderr,"%s vs %s\n",destaddr,(char *)cp->unspendableCCaddr);
return eval->Invalid("invalid vin AssetsCCaddr");
}
//else if ( vinTx.vout[0].nValue < 10000 )
// return eval->Invalid("invalid dust for buyvin");
else if ( GetAssetorigaddrs(cp,CCaddr,origaddr,vinTx) == 0 )
return eval->Invalid("couldnt get origaddr for buyvin");
fprintf(stderr,"Got %.8f to origaddr.(%s)\n",(double)vinTx.vout[tx.vin[vini].prevout.n].nValue/COIN,origaddr);
if ( vinTx.vout[0].nValue == 0 )
return eval->Invalid("null value CCvin");
return(vinTx.vout[0].nValue);
}
int64_t AssetValidateBuyvin(struct CCcontract_info *cp,Eval* eval,int64_t &tmpprice,std::vector<uint8_t> &tmporigpubkey,char *CCaddr,char *origaddr,const CTransaction &tx,uint256 refassetid)
{
CTransaction vinTx; int64_t nValue; uint256 assetid,assetid2; uint8_t funcid;
CCaddr[0] = origaddr[0] = 0;
if ( (nValue= AssetValidateCCvin(cp,eval,CCaddr,origaddr,tx,1,vinTx)) == 0 )
return(0);
else if ( vinTx.vout[0].scriptPubKey.IsPayToCryptoCondition() == 0 )
return eval->Invalid("invalid normal vout0 for buyvin");
else
{
//fprintf(stderr,"have %.8f checking assetid origaddr.(%s)\n",(double)nValue/COIN,origaddr);
if ( vinTx.vout.size() > 0 && (funcid= DecodeAssetOpRet(vinTx.vout[vinTx.vout.size()-1].scriptPubKey,assetid,assetid2,tmpprice,tmporigpubkey)) != 'b' && funcid != 'B' )
return eval->Invalid("invalid opreturn for buyvin");
else if ( refassetid != assetid )
return eval->Invalid("invalid assetid for buyvin");
//int32_t i; for (i=31; i>=0; i--)
// fprintf(stderr,"%02x",((uint8_t *)&assetid)[i]);
//fprintf(stderr," AssetValidateBuyvin assetid for %s\n",origaddr);
}
return(nValue);
}
int64_t AssetValidateSellvin(struct CCcontract_info *cp,Eval* eval,int64_t &tmpprice,std::vector<uint8_t> &tmporigpubkey,char *CCaddr,char *origaddr,const CTransaction &tx,uint256 assetid)
{
CTransaction vinTx; int64_t nValue,assetoshis;
fprintf(stderr,"AssetValidateSellvin\n");
if ( (nValue= AssetValidateCCvin(cp,eval,CCaddr,origaddr,tx,1,vinTx)) == 0 )
return(0);
if ( (assetoshis= IsAssetvout(tmpprice,tmporigpubkey,vinTx,0,assetid)) == 0 )
return eval->Invalid("invalid missing CC vout0 for sellvin");
else return(assetoshis);
}
bool AssetExactAmounts(struct CCcontract_info *cp,int64_t &inputs,int32_t starti,int64_t &outputs,Eval* eval,const CTransaction &tx,uint256 assetid)
{
CTransaction vinTx; uint256 hashBlock; int32_t i,numvins,numvouts; int64_t assetoshis; std::vector<uint8_t> tmporigpubkey; int64_t tmpprice;
numvins = tx.vin.size();
numvouts = tx.vout.size();
inputs = outputs = 0;
for (i=starti; i<numvins; i++)
{
if ( (*cp->ismyvin)(tx.vin[i].scriptSig) != 0 )
{
if ( eval->GetTxUnconfirmed(tx.vin[i].prevout.hash,vinTx,hashBlock) == 0 )
{
fprintf(stderr,"i.%d starti.%d numvins.%d\n",i,starti,numvins);
return eval->Invalid("always should find vin, but didnt");
}
else if ( (assetoshis= IsAssetvout(tmpprice,tmporigpubkey,vinTx,tx.vin[i].prevout.n,assetid)) != 0 )
{
fprintf(stderr,"vin%d %llu, ",i,(long long)assetoshis);
inputs += assetoshis;
}
}
}
for (i=0; i<numvouts; i++)
{
if ( (assetoshis= IsAssetvout(tmpprice,tmporigpubkey,tx,i,assetid)) != 0 )
{
fprintf(stderr,"vout%d %llu, ",i,(long long)assetoshis);
outputs += assetoshis;
}
}
if ( inputs != outputs )
{
fprintf(stderr,"inputs %.8f vs %.8f outputs\n",(double)inputs/COIN,(double)outputs/COIN);
return(false);
}
else return(true);
}

472
src/cc/CCassetstx.cpp

@ -0,0 +1,472 @@
/******************************************************************************
* Copyright © 2014-2018 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 "CCassets.h"
// need allassets
// find asset
int64_t AddAssetInputs(struct CCcontract_info *cp,CMutableTransaction &mtx,CPubKey pk,uint256 assetid,int64_t total,int32_t maxinputs)
{
char coinaddr[64]; int64_t nValue,price,totalinputs = 0; uint256 txid,hashBlock; std::vector<uint8_t> origpubkey; CTransaction vintx; int32_t j,vout,n = 0;
std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> > unspentOutputs;
GetCCaddress(cp,coinaddr,pk);
SetCCunspents(unspentOutputs,coinaddr);
for (std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++)
{
txid = it->first.txhash;
vout = (int32_t)it->first.index;
for (j=0; j<mtx.vin.size(); j++)
if ( txid == mtx.vin[j].prevout.hash && vout == mtx.vin[j].prevout.n )
break;
if ( j != mtx.vin.size() )
continue;
if ( GetTransaction(txid,vintx,hashBlock,false) != 0 )
{
if ( (nValue= IsAssetvout(price,origpubkey,vintx,vout,assetid)) > 0 )
{
if ( total != 0 && maxinputs != 0 )
mtx.vin.push_back(CTxIn(txid,vout,CScript()));
nValue = it->second.satoshis;
totalinputs += nValue;
n++;
if ( (total > 0 && totalinputs >= total) || (maxinputs > 0 && n >= maxinputs) )
break;
}
}
}
return(totalinputs);
}
int64_t GetAssetBalance(CPubKey pk,uint256 tokenid)
{
CMutableTransaction mtx; struct CCcontract_info *cp,C;
cp = CCinit(&C,EVAL_ASSETS);
return(AddAssetInputs(cp,mtx,pk,tokenid,0,0));
}
UniValue AssetInfo(uint256 assetid)
{
UniValue result(UniValue::VOBJ); uint256 hashBlock; CTransaction vintx; std::vector<uint8_t> origpubkey; std::string name,description; char str[67],numstr[65];
if ( GetTransaction(assetid,vintx,hashBlock,false) == 0 )
{
fprintf(stderr,"cant find assetid\n");
result.push_back(Pair("error","cant find assetid"));
return(0);
}
if ( vintx.vout.size() > 0 && DecodeAssetCreateOpRet(vintx.vout[vintx.vout.size()-1].scriptPubKey,origpubkey,name,description) == 0 )
{
fprintf(stderr,"assetid isnt assetcreation txid\n");
result.push_back(Pair("error","assetid isnt assetcreation txid"));
}
result.push_back(Pair("result","success"));
result.push_back(Pair("tokenid",uint256_str(str,assetid)));
result.push_back(Pair("owner",pubkey33_str(str,origpubkey.data())));
result.push_back(Pair("name",name));
sprintf(numstr,"%.8f",(double)vintx.vout[0].nValue/COIN);
result.push_back(Pair("supply",numstr));
result.push_back(Pair("description",description));
return(result);
}
UniValue AssetList()
{
UniValue result(UniValue::VARR); std::vector<std::pair<CAddressIndexKey, CAmount> > addressIndex; struct CCcontract_info *cp,C; uint256 txid,hashBlock; CTransaction vintx; std::vector<uint8_t> origpubkey; std::string name,description; char str[65];
cp = CCinit(&C,EVAL_ASSETS);
SetCCtxids(addressIndex,cp->normaladdr);
for (std::vector<std::pair<CAddressIndexKey, CAmount> >::const_iterator it=addressIndex.begin(); it!=addressIndex.end(); it++)
{
txid = it->first.txhash;
if ( GetTransaction(txid,vintx,hashBlock,false) != 0 )
{
if ( vintx.vout.size() > 0 && DecodeAssetCreateOpRet(vintx.vout[vintx.vout.size()-1].scriptPubKey,origpubkey,name,description) != 0 )
{
result.push_back(uint256_str(str,txid));
}
}
}
return(result);
}
UniValue AssetOrders(uint256 refassetid)
{
static uint256 zero;
int64_t price; uint256 txid,hashBlock,assetid,assetid2; std::vector<uint8_t> origpubkey; CTransaction vintx; UniValue result(UniValue::VARR); std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> > unspentOutputs; uint8_t funcid; char numstr[32],funcidstr[16],origaddr[64],assetidstr[65]; struct CCcontract_info *cp,C;
cp = CCinit(&C,EVAL_ASSETS);
SetCCunspents(unspentOutputs,(char *)cp->unspendableCCaddr);
for (std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++)
{
txid = it->first.txhash;
if ( GetTransaction(txid,vintx,hashBlock,false) != 0 )
{
if ( vintx.vout.size() > 0 && (funcid= DecodeAssetOpRet(vintx.vout[vintx.vout.size()-1].scriptPubKey,assetid,assetid2,price,origpubkey)) != 0 )
{
if ( refassetid != zero && assetid != refassetid )
{
//int32_t z;
//for (z=31; z>=0; z--) fprintf(stderr,"%02x",((uint8_t *)&txid)[z]);
//fprintf(stderr," txid\n");
//for (z=31; z>=0; z--) fprintf(stderr,"%02x",((uint8_t *)&assetid)[z]);
//fprintf(stderr," assetid\n");
//for (z=31; z>=0; z--) fprintf(stderr,"%02x",((uint8_t *)&refassetid)[z]);
//fprintf(stderr," refassetid\n");
continue;
}
if ( vintx.vout[it->first.index].nValue == 0 )
continue;
UniValue item(UniValue::VOBJ);
funcidstr[0] = funcid;
funcidstr[1] = 0;
item.push_back(Pair("funcid", funcidstr));
item.push_back(Pair("txid", uint256_str(assetidstr,txid)));
item.push_back(Pair("vout", (int64_t)it->first.index));
if ( funcid == 'b' || funcid == 'B' )
{
sprintf(numstr,"%.8f",(double)vintx.vout[it->first.index].nValue/COIN);
item.push_back(Pair("amount",numstr));
sprintf(numstr,"%.8f",(double)vintx.vout[0].nValue/COIN);
item.push_back(Pair("bidamount",numstr));
}
else
{
sprintf(numstr,"%llu",(long long)vintx.vout[it->first.index].nValue);
item.push_back(Pair("amount",numstr));
sprintf(numstr,"%llu",(long long)vintx.vout[0].nValue);
item.push_back(Pair("askamount",numstr));
}
if ( origpubkey.size() == 33 )
{
GetCCaddress(cp,origaddr,pubkey2pk(origpubkey));
item.push_back(Pair("origaddress",origaddr));
}
if ( assetid != zeroid )
item.push_back(Pair("tokenid",uint256_str(assetidstr,assetid)));
if ( assetid2 != zeroid )
item.push_back(Pair("otherid",uint256_str(assetidstr,assetid2)));
if ( price > 0 )
{
if ( funcid == 's' || funcid == 'S' || funcid == 'e' || funcid == 'e' )
{
sprintf(numstr,"%.8f",(double)price / COIN);
item.push_back(Pair("totalrequired", numstr));
sprintf(numstr,"%.8f",(double)price / (COIN * vintx.vout[0].nValue));
item.push_back(Pair("price", numstr));
}
else
{
item.push_back(Pair("totalrequired", (int64_t)price));
sprintf(numstr,"%.8f",(double)vintx.vout[0].nValue / (price * COIN));
item.push_back(Pair("price",numstr));
}
}
result.push_back(item);
//fprintf(stderr,"func.(%c) %s/v%d %.8f\n",funcid,uint256_str(assetidstr,txid),(int32_t)it->first.index,(double)vintx.vout[it->first.index].nValue/COIN);
}
}
}
return(result);
}
std::string CreateAsset(int64_t txfee,int64_t assetsupply,std::string name,std::string description)
{
CMutableTransaction mtx; CPubKey mypk; struct CCcontract_info *cp,C;
if ( assetsupply < 0 )
{
fprintf(stderr,"negative assetsupply %lld\n",(long long)assetsupply);
return(0);
}
cp = CCinit(&C,EVAL_ASSETS);
if ( name.size() > 32 || description.size() > 4096 )
{
fprintf(stderr,"name.%d or description.%d is too big\n",(int32_t)name.size(),(int32_t)description.size());
return(0);
}
if ( txfee == 0 )
txfee = 10000;
mypk = pubkey2pk(Mypubkey());
if ( AddNormalinputs(mtx,mypk,assetsupply+2*txfee,64) > 0 )
{
mtx.vout.push_back(MakeCC1vout(EVAL_ASSETS,assetsupply,mypk));
mtx.vout.push_back(CTxOut(txfee,CScript() << ParseHex(cp->CChexstr) << OP_CHECKSIG));
return(FinalizeCCTx(0,cp,mtx,mypk,txfee,EncodeAssetCreateOpRet('c',Mypubkey(),name,description)));
}
return(0);
}
std::string AssetTransfer(int64_t txfee,uint256 assetid,std::vector<uint8_t> destpubkey,int64_t total)
{
CMutableTransaction mtx; CPubKey mypk; uint64_t mask; int64_t CCchange=0,inputs=0; struct CCcontract_info *cp,C;
if ( total < 0 )
{
fprintf(stderr,"negative total %lld\n",(long long)total);
return(0);
}
cp = CCinit(&C,EVAL_ASSETS);
if ( txfee == 0 )
txfee = 10000;
mypk = pubkey2pk(Mypubkey());
if ( AddNormalinputs(mtx,mypk,txfee,1) > 0 )
{
/*n = outputs.size();
if ( n == amounts.size() )
{
for (i=0; i<n; i++)
total += amounts[i];*/
mask = ~((1LL << mtx.vin.size()) - 1);
if ( (inputs= AddAssetInputs(cp,mtx,mypk,assetid,total,60)) > 0 )
{
if ( inputs > total )
CCchange = (inputs - total);
//for (i=0; i<n; i++)
mtx.vout.push_back(MakeCC1vout(EVAL_ASSETS,total,pubkey2pk(destpubkey)));
if ( CCchange != 0 )
mtx.vout.push_back(MakeCC1vout(EVAL_ASSETS,CCchange,mypk));
return(FinalizeCCTx(mask,cp,mtx,mypk,txfee,EncodeAssetOpRet('t',assetid,zeroid,0,Mypubkey())));
} else fprintf(stderr,"not enough CC asset inputs for %.8f\n",(double)total/COIN);
//} else fprintf(stderr,"numoutputs.%d != numamounts.%d\n",n,(int32_t)amounts.size());
}
return(0);
}
std::string CreateBuyOffer(int64_t txfee,int64_t bidamount,uint256 assetid,int64_t pricetotal)
{
CMutableTransaction mtx; CPubKey mypk; struct CCcontract_info *cp,C; uint256 hashBlock; CTransaction vintx; std::vector<uint8_t> origpubkey; std::string name,description;
if ( bidamount < 0 || pricetotal < 0 )
{
fprintf(stderr,"negative bidamount %lld, pricetotal %lld\n",(long long)bidamount,(long long)pricetotal);
return(0);
}
if ( GetTransaction(assetid,vintx,hashBlock,false) == 0 )
{
fprintf(stderr,"cant find assetid\n");
return(0);
}
if ( vintx.vout.size() > 0 && DecodeAssetCreateOpRet(vintx.vout[vintx.vout.size()-1].scriptPubKey,origpubkey,name,description) == 0 )
{
fprintf(stderr,"assetid isnt assetcreation txid\n");
return(0);
}
cp = CCinit(&C,EVAL_ASSETS);
if ( txfee == 0 )
txfee = 10000;
mypk = pubkey2pk(Mypubkey());
if ( AddNormalinputs(mtx,mypk,bidamount+txfee,64) > 0 )
{
mtx.vout.push_back(MakeCC1vout(EVAL_ASSETS,bidamount,GetUnspendable(cp,0)));
return(FinalizeCCTx(0,cp,mtx,mypk,txfee,EncodeAssetOpRet('b',assetid,zeroid,pricetotal,Mypubkey())));
}
return(0);
}
std::string CreateSell(int64_t txfee,int64_t askamount,uint256 assetid,int64_t pricetotal)
{
CMutableTransaction mtx; CPubKey mypk; uint64_t mask; int64_t inputs,CCchange; CScript opret; struct CCcontract_info *cp,C;
if ( askamount < 0 || pricetotal < 0 )
{
fprintf(stderr,"negative askamount %lld, askamount %lld\n",(long long)pricetotal,(long long)askamount);
return(0);
}
cp = CCinit(&C,EVAL_ASSETS);
if ( txfee == 0 )
txfee = 10000;
mypk = pubkey2pk(Mypubkey());
if ( AddNormalinputs(mtx,mypk,txfee,1) > 0 )
{
mask = ~((1LL << mtx.vin.size()) - 1);
if ( (inputs= AddAssetInputs(cp,mtx,mypk,assetid,askamount,60)) > 0 )
{
if ( inputs < askamount )
askamount = inputs;
mtx.vout.push_back(MakeCC1vout(EVAL_ASSETS,askamount,GetUnspendable(cp,0)));
if ( inputs > askamount )
CCchange = (inputs - askamount);
if ( CCchange != 0 )
mtx.vout.push_back(MakeCC1vout(EVAL_ASSETS,CCchange,mypk));
opret = EncodeAssetOpRet('s',assetid,zeroid,pricetotal,Mypubkey());
return(FinalizeCCTx(mask,cp,mtx,mypk,txfee,opret));
} else fprintf(stderr,"need some assets to place ask\n");
}
fprintf(stderr,"need some native coins to place ask\n");
return(0);
}
std::string CreateSwap(int64_t txfee,int64_t askamount,uint256 assetid,uint256 assetid2,int64_t pricetotal)
{
CMutableTransaction mtx; CPubKey mypk; uint64_t mask; int64_t inputs,CCchange; CScript opret; struct CCcontract_info *cp,C;
if ( askamount < 0 || pricetotal < 0 )
{
fprintf(stderr,"negative askamount %lld, askamount %lld\n",(long long)pricetotal,(long long)askamount);
return(0);
}
cp = CCinit(&C,EVAL_ASSETS);
if ( txfee == 0 )
txfee = 10000;
mypk = pubkey2pk(Mypubkey());
if ( AddNormalinputs(mtx,mypk,txfee,1) > 0 )
{
mask = ~((1LL << mtx.vin.size()) - 1);
if ( (inputs= AddAssetInputs(cp,mtx,mypk,assetid,askamount,60)) > 0 )
{
if ( inputs < askamount )
askamount = inputs;
mtx.vout.push_back(MakeCC1vout(EVAL_ASSETS,askamount,GetUnspendable(cp,0)));
if ( inputs > askamount )
CCchange = (inputs - askamount);
if ( CCchange != 0 )
mtx.vout.push_back(MakeCC1vout(EVAL_ASSETS,CCchange,mypk));
if ( assetid2 == zeroid )
opret = EncodeAssetOpRet('s',assetid,zeroid,pricetotal,Mypubkey());
else
{
opret = EncodeAssetOpRet('e',assetid,assetid2,pricetotal,Mypubkey());
}
return(FinalizeCCTx(mask,cp,mtx,mypk,txfee,opret));
} else fprintf(stderr,"need some assets to place ask\n");
}
fprintf(stderr,"need some native coins to place ask\n");
return(0);
}
std::string CancelBuyOffer(int64_t txfee,uint256 assetid,uint256 bidtxid)
{
CMutableTransaction mtx; CTransaction vintx; uint64_t mask; uint256 hashBlock; int64_t bidamount; CPubKey mypk; struct CCcontract_info *cp,C;
cp = CCinit(&C,EVAL_ASSETS);
if ( txfee == 0 )
txfee = 10000;
mypk = pubkey2pk(Mypubkey());
if ( AddNormalinputs(mtx,mypk,txfee,1) > 0 )
{
mask = ~((1LL << mtx.vin.size()) - 1);
if ( GetTransaction(bidtxid,vintx,hashBlock,false) != 0 )
{
bidamount = vintx.vout[0].nValue;
mtx.vin.push_back(CTxIn(bidtxid,0,CScript()));
mtx.vout.push_back(CTxOut(bidamount,CScript() << ParseHex(HexStr(mypk)) << OP_CHECKSIG));
return(FinalizeCCTx(mask,cp,mtx,mypk,txfee,EncodeAssetOpRet('o',assetid,zeroid,0,Mypubkey())));
}
}
return(0);
}
std::string CancelSell(int64_t txfee,uint256 assetid,uint256 asktxid)
{
CMutableTransaction mtx; CTransaction vintx; uint64_t mask; uint256 hashBlock; int64_t askamount; CPubKey mypk; struct CCcontract_info *cp,C;
cp = CCinit(&C,EVAL_ASSETS);
if ( txfee == 0 )
txfee = 10000;
mypk = pubkey2pk(Mypubkey());
if ( AddNormalinputs(mtx,mypk,txfee,1) > 0 )
{
mask = ~((1LL << mtx.vin.size()) - 1);
if ( GetTransaction(asktxid,vintx,hashBlock,false) != 0 )
{
askamount = vintx.vout[0].nValue;
mtx.vin.push_back(CTxIn(asktxid,0,CScript()));
mtx.vout.push_back(MakeCC1vout(EVAL_ASSETS,askamount,mypk));
return(FinalizeCCTx(mask,cp,mtx,mypk,txfee,EncodeAssetOpRet('x',assetid,zeroid,0,Mypubkey())));
}
}
return(0);
}
std::string FillBuyOffer(int64_t txfee,uint256 assetid,uint256 bidtxid,int64_t fillamount)
{
CTransaction vintx; uint256 hashBlock; CMutableTransaction mtx; CPubKey mypk; std::vector<uint8_t> origpubkey; int32_t bidvout=0; uint64_t mask; int64_t origprice,bidamount,paid_amount,remaining_required,inputs,CCchange=0; struct CCcontract_info *cp,C;
if ( fillamount < 0 )
{
fprintf(stderr,"negative fillamount %lld\n",(long long)fillamount);
return(0);
}
cp = CCinit(&C,EVAL_ASSETS);
if ( txfee == 0 )
txfee = 10000;
mypk = pubkey2pk(Mypubkey());
if ( AddNormalinputs(mtx,mypk,txfee,1) > 0 )
{
mask = ~((1LL << mtx.vin.size()) - 1);
if ( GetTransaction(bidtxid,vintx,hashBlock,false) != 0 )
{
bidamount = vintx.vout[bidvout].nValue;
SetAssetOrigpubkey(origpubkey,origprice,vintx);
mtx.vin.push_back(CTxIn(bidtxid,bidvout,CScript()));
if ( (inputs= AddAssetInputs(cp,mtx,mypk,assetid,fillamount,60)) > 0 )
{
if ( inputs < fillamount )
fillamount = inputs;
SetBidFillamounts(paid_amount,remaining_required,bidamount,fillamount,origprice);
if ( inputs > fillamount )
CCchange = (inputs - fillamount);
mtx.vout.push_back(MakeCC1vout(EVAL_ASSETS,bidamount - paid_amount,GetUnspendable(cp,0)));
mtx.vout.push_back(CTxOut(paid_amount,CScript() << ParseHex(HexStr(mypk)) << OP_CHECKSIG));
mtx.vout.push_back(MakeCC1vout(EVAL_ASSETS,fillamount,pubkey2pk(origpubkey)));
if ( CCchange != 0 )
mtx.vout.push_back(MakeCC1vout(EVAL_ASSETS,CCchange,mypk));
fprintf(stderr,"remaining %llu -> origpubkey\n",(long long)remaining_required);
return(FinalizeCCTx(mask,cp,mtx,mypk,txfee,EncodeAssetOpRet('B',assetid,zeroid,remaining_required,origpubkey)));
} else return("dont have any assets to fill bid\n");
}
}
return("no normal coins left");
}
std::string FillSell(int64_t txfee,uint256 assetid,uint256 assetid2,uint256 asktxid,int64_t fillunits)
{
CTransaction vintx,filltx; uint256 hashBlock; CMutableTransaction mtx; CPubKey mypk; std::vector<uint8_t> origpubkey; double dprice; uint64_t mask; int32_t askvout=0; int64_t received_assetoshis,total_nValue,orig_assetoshis,paid_nValue,remaining_nValue,inputs,CCchange=0; struct CCcontract_info *cp,C;
if ( fillunits < 0 )
{
fprintf(stderr,"negative fillunits %lld\n",(long long)fillunits);
return(0);
}
cp = CCinit(&C,EVAL_ASSETS);
if ( txfee == 0 )
txfee = 10000;
mypk = pubkey2pk(Mypubkey());
if ( AddNormalinputs(mtx,mypk,txfee,1) > 0 )
{
mask = ~((1LL << mtx.vin.size()) - 1);
if ( GetTransaction(asktxid,vintx,hashBlock,false) != 0 )
{
orig_assetoshis = vintx.vout[askvout].nValue;
SetAssetOrigpubkey(origpubkey,total_nValue,vintx);
dprice = (double)total_nValue / orig_assetoshis;
paid_nValue = dprice * fillunits;
mtx.vin.push_back(CTxIn(asktxid,askvout,CScript()));
if ( assetid2 != zeroid )
inputs = AddAssetInputs(cp,mtx,mypk,assetid2,paid_nValue,60);
else
{
inputs = AddNormalinputs(mtx,mypk,paid_nValue,60);
mask = ~((1LL << mtx.vin.size()) - 1);
}
if ( inputs > 0 )
{
if ( inputs < paid_nValue )
paid_nValue = inputs;
if ( assetid2 != zeroid )
SetSwapFillamounts(received_assetoshis,remaining_nValue,orig_assetoshis,paid_nValue,total_nValue);
else SetAskFillamounts(received_assetoshis,remaining_nValue,orig_assetoshis,paid_nValue,total_nValue);
if ( assetid2 != zeroid && inputs > paid_nValue )
CCchange = (inputs - paid_nValue);
mtx.vout.push_back(MakeCC1vout(EVAL_ASSETS,orig_assetoshis - received_assetoshis,GetUnspendable(cp,0)));
mtx.vout.push_back(MakeCC1vout(EVAL_ASSETS,received_assetoshis,mypk));
mtx.vout.push_back(CTxOut(paid_nValue,CScript() << origpubkey << OP_CHECKSIG));
if ( CCchange != 0 )
mtx.vout.push_back(MakeCC1vout(EVAL_ASSETS,CCchange,mypk));
return(FinalizeCCTx(mask,cp,mtx,mypk,txfee,EncodeAssetOpRet(assetid2!=zeroid?'E':'S',assetid,assetid2,remaining_nValue,origpubkey)));
} else fprintf(stderr,"filltx not enough utxos\n");
}
}
return(0);
}

30
src/cc/CCauction.h

@ -0,0 +1,30 @@
/******************************************************************************
* Copyright © 2014-2018 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. *
* *
******************************************************************************/
#ifndef CC_AUCTION_H
#define CC_AUCTION_H
#include "CCinclude.h"
#define EVAL_AUCTION 0xe8
bool AuctionValidate(struct CCcontract_info *cp,Eval* eval,const CTransaction &tx);
std::string AuctionPost(uint64_t txfee,uint256 itemhash,uint64_t minbid,char *title,char *description);
std::string AuctionBid(uint64_t txfee,uint256 itemhash,uint64_t amount);
std::string AuctionDeliver(uint64_t txfee,uint256 itemhash,uint256 bidtxid);
#endif

195
src/cc/CCcustom.cpp

@ -0,0 +1,195 @@
/******************************************************************************
* Copyright © 2014-2018 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 "CCinclude.h"
#include "CCassets.h"
#include "CCfaucet.h"
#include "CCrewards.h"
#include "CCdice.h"
#include "CCauction.h"
#include "CClotto.h"
#include "CCponzi.h"
/*
CCcustom has most of the functions that need to be extended to create a new CC contract.
A CC scriptPubKey can only be spent if it is properly signed and validated. By constraining the vins and vouts, it is possible to implement a variety of functionality. CC vouts have an otherwise non-standard form, but it is properly supported by the enhanced bitcoin protocol code as a "cryptoconditions" output and the same pubkey will create a different address.
This allows creation of a special address(es) for each contract type, which has the privkey public. That allows anybody to properly sign and spend it, but with the constraints on what is allowed in the validation code, the contract functionality can be implemented.
what needs to be done to add a new contract:
1. add EVAL_CODE to eval.h
2. initialize the variables in the CCinit function below
3. write a Validate function to reject any unsanctioned usage of vin/vout
4. make helper functions to create rawtx for RPC functions
5. add rpc calls to rpcserver.cpp and rpcserver.h and in one of the rpc.cpp files
6. add the new .cpp files to src/Makefile.am
IMPORTANT: make sure that all CC inputs and CC outputs are properly accounted for and reconcile to the satoshi. The built in utxo management will enforce overall vin/vout constraints but it wont know anything about the CC constraints. That is what your Validate function needs to do.
Generally speaking, there will be normal coins that change into CC outputs, CC outputs that go back to being normal coins, CC outputs that are spent to new CC outputs.
Make sure both the CC coins and normal coins are preserved and follow the rules that make sense. It is a good idea to define specific roles for specific vins and vouts to reduce the complexity of validation.
*/
//BTCD Address: RAssetsAtGnvwgK9gVHBbAU4sVTah1hAm5
//BTCD Privkey: UvtvQVgVScXEYm4J3r4nE4nbFuGXSVM5pKec8VWXwgG9dmpWBuDh
//BTCD Address: RSavingsEYcivt2DFsxsKeCjqArV6oVtVZ
//BTCD Privkey: Ux6XQekTxokko6gZHz24B7PUsmUQtWFzG2W9nUA8jba7UoVbPBF4
// Assets, aka Tokens
#define FUNCNAME IsAssetsInput
#define EVALCODE EVAL_ASSETS
const char *AssetsCCaddr = "RGKRjeTBw4LYFotSDLT6RWzMHbhXri6BG6";
const char *AssetsNormaladdr = "RFYE2yL3KknWdHK6uNhvWacYsCUtwzjY3u";
char AssetsCChexstr[67] = { "02adf84e0e075cf90868bd4e3d34a03420e034719649c41f371fc70d8e33aa2702" };
uint8_t AssetsCCpriv[32] = { 0x9b, 0x17, 0x66, 0xe5, 0x82, 0x66, 0xac, 0xb6, 0xba, 0x43, 0x83, 0x74, 0xf7, 0x63, 0x11, 0x3b, 0xf0, 0xf3, 0x50, 0x6f, 0xd9, 0x6b, 0x67, 0x85, 0xf9, 0x7a, 0xf0, 0x54, 0x4d, 0xb1, 0x30, 0x77 };
#include "CCcustom.inc"
#undef FUNCNAME
#undef EVALCODE
// Faucet
#define FUNCNAME IsFaucetInput
#define EVALCODE EVAL_FAUCET
const char *FaucetCCaddr = "R9zHrofhRbub7ER77B7NrVch3A63R39GuC";
const char *FaucetNormaladdr = "RKQV4oYs4rvxAWx1J43VnT73rSTVtUeckk";
char FaucetCChexstr[67] = { "03682b255c40d0cde8faee381a1a50bbb89980ff24539cb8518e294d3a63cefe12" };
uint8_t FaucetCCpriv[32] = { 0xd4, 0x4f, 0xf2, 0x31, 0x71, 0x7d, 0x28, 0x02, 0x4b, 0xc7, 0xdd, 0x71, 0xa0, 0x39, 0xc4, 0xbe, 0x1a, 0xfe, 0xeb, 0xc2, 0x46, 0xda, 0x76, 0xf8, 0x07, 0x53, 0x3d, 0x96, 0xb4, 0xca, 0xa0, 0xe9 };
#include "CCcustom.inc"
#undef FUNCNAME
#undef EVALCODE
// Rewards
#define FUNCNAME IsRewardsInput
#define EVALCODE EVAL_REWARDS
const char *RewardsCCaddr = "RTsRBYL1HSvMoE3qtBJkyiswdVaWkm8YTK";
const char *RewardsNormaladdr = "RMgye9jeczNjQx9Uzq8no8pTLiCSwuHwkz";
char RewardsCChexstr[67] = { "03da60379d924c2c30ac290d2a86c2ead128cb7bd571f69211cb95356e2dcc5eb9" };
uint8_t RewardsCCpriv[32] = { 0x82, 0xf5, 0xd2, 0xe7, 0xd6, 0x99, 0x33, 0x77, 0xfb, 0x80, 0x00, 0x97, 0x23, 0x3d, 0x1e, 0x6f, 0x61, 0xa9, 0xb5, 0x2e, 0x5e, 0xb4, 0x96, 0x6f, 0xbc, 0xed, 0x6b, 0xe2, 0xbb, 0x7b, 0x4b, 0xb3 };
#include "CCcustom.inc"
#undef FUNCNAME
#undef EVALCODE
// Dice
#define FUNCNAME IsDiceInput
#define EVALCODE EVAL_DICE
const char *DiceCCaddr = "REabWB7KjFN5C3LFMZ5odExHPenYzHLtVw";
const char *DiceNormaladdr = "RLEe8f7Eg3TDuXii9BmNiiiaVGraHUt25c";
char DiceCChexstr[67] = { "039d966927cfdadab3ee6c56da63c21f17ea753dde4b3dfd41487103e24b27e94e" };
uint8_t DiceCCpriv[32] = { 0x0e, 0xe8, 0xf5, 0xb4, 0x3d, 0x25, 0xcc, 0x35, 0xd1, 0xf1, 0x2f, 0x04, 0x5f, 0x01, 0x26, 0xb8, 0xd1, 0xac, 0x3a, 0x5a, 0xea, 0xe0, 0x25, 0xa2, 0x8f, 0x2a, 0x8e, 0x0e, 0xf9, 0x34, 0xfa, 0x77 };
#include "CCcustom.inc"
#undef FUNCNAME
#undef EVALCODE
// Lotto
#define FUNCNAME IsLottoInput
#define EVALCODE EVAL_LOTTO
const char *LottoCCaddr = "RNXZxgyWSAE6XS3qGnTaf5dVNCxnYzhPrg";
const char *LottoNormaladdr = "RLW6hhRqBZZMBndnyPv29Yg3krh6iBYCyg";
char LottoCChexstr[67] = { "03f72d2c4db440df1e706502b09ca5fec73ffe954ea1883e4049e98da68690d98f" };
uint8_t LottoCCpriv[32] = { 0xb4, 0xac, 0xc2, 0xd9, 0x67, 0x34, 0xd7, 0x58, 0x80, 0x4e, 0x25, 0x55, 0xc0, 0x50, 0x66, 0x84, 0xbb, 0xa2, 0xe7, 0xc0, 0x39, 0x17, 0xb4, 0xc5, 0x07, 0xb7, 0x3f, 0xca, 0x07, 0xb0, 0x9a, 0xeb };
#include "CCcustom.inc"
#undef FUNCNAME
#undef EVALCODE
// Ponzi
#define FUNCNAME IsPonziInput
#define EVALCODE EVAL_PONZI
const char *PonziCCaddr = "RUKTbLBeKgHkm3Ss4hKZP3ikuLW1xx7B2x";
const char *PonziNormaladdr = "RWSHRbxnJYLvDjpcQ2i8MekgP6h2ctTKaj";
char PonziCChexstr[67] = { "039b52d294b413b07f3643c1a28c5467901a76562d8b39a785910ae0a0f3043810" };
uint8_t PonziCCpriv[32] = { 0x11, 0xe1, 0xea, 0x3e, 0xdb, 0x36, 0xf0, 0xa8, 0xc6, 0x34, 0xe1, 0x21, 0xb8, 0x02, 0xb9, 0x4b, 0x12, 0x37, 0x8f, 0xa0, 0x86, 0x23, 0x50, 0xb2, 0x5f, 0xe4, 0xe7, 0x36, 0x0f, 0xda, 0xae, 0xfc };
#include "CCcustom.inc"
#undef FUNCNAME
#undef EVALCODE
// Auction
#define FUNCNAME IsAuctionInput
#define EVALCODE EVAL_AUCTION
const char *AuctionCCaddr = "RL4YPX7JYG3FnvoPqWF2pn3nQknH5NWEwx";
const char *AuctionNormaladdr = "RFtVDNmdTZBTNZdmFRbfBgJ6LitgTghikL";
char AuctionCChexstr[67] = { "037eefe050c14cb60ae65d5b2f69eaa1c9006826d729bc0957bdc3024e3ca1dbe6" };
uint8_t AuctionCCpriv[32] = { 0x8c, 0x1b, 0xb7, 0x8c, 0x02, 0xa3, 0x9d, 0x21, 0x28, 0x59, 0xf5, 0xea, 0xda, 0xec, 0x0d, 0x11, 0xcd, 0x38, 0x47, 0xac, 0x0b, 0x6f, 0x19, 0xc0, 0x24, 0x36, 0xbf, 0x1c, 0x0a, 0x06, 0x31, 0xfb };
#include "CCcustom.inc"
#undef FUNCNAME
#undef EVALCODE
struct CCcontract_info *CCinit(struct CCcontract_info *cp,uint8_t evalcode)
{
cp->evalcode = evalcode;
switch ( evalcode )
{
case EVAL_ASSETS:
strcpy(cp->unspendableCCaddr,AssetsCCaddr);
strcpy(cp->normaladdr,AssetsNormaladdr);
strcpy(cp->CChexstr,AssetsCChexstr);
memcpy(cp->CCpriv,AssetsCCpriv,32);
cp->validate = AssetsValidate;
cp->ismyvin = IsAssetsInput;
break;
case EVAL_FAUCET:
strcpy(cp->unspendableCCaddr,FaucetCCaddr);
strcpy(cp->normaladdr,FaucetNormaladdr);
strcpy(cp->CChexstr,FaucetCChexstr);
memcpy(cp->CCpriv,FaucetCCpriv,32);
cp->validate = FaucetValidate;
cp->ismyvin = IsFaucetInput;
break;
case EVAL_REWARDS:
strcpy(cp->unspendableCCaddr,RewardsCCaddr);
strcpy(cp->normaladdr,RewardsNormaladdr);
strcpy(cp->CChexstr,RewardsCChexstr);
memcpy(cp->CCpriv,RewardsCCpriv,32);
cp->validate = RewardsValidate;
cp->ismyvin = IsRewardsInput;
break;
case EVAL_DICE:
strcpy(cp->unspendableCCaddr,DiceCCaddr);
strcpy(cp->normaladdr,DiceNormaladdr);
strcpy(cp->CChexstr,DiceCChexstr);
memcpy(cp->CCpriv,DiceCCpriv,32);
cp->validate = DiceValidate;
cp->ismyvin = IsDiceInput;
break;
case EVAL_LOTTO:
strcpy(cp->unspendableCCaddr,LottoCCaddr);
strcpy(cp->normaladdr,LottoNormaladdr);
strcpy(cp->CChexstr,LottoCChexstr);
memcpy(cp->CCpriv,LottoCCpriv,32);
cp->validate = LottoValidate;
cp->ismyvin = IsLottoInput;
break;
case EVAL_PONZI:
strcpy(cp->unspendableCCaddr,PonziCCaddr);
strcpy(cp->normaladdr,PonziNormaladdr);
strcpy(cp->CChexstr,PonziCChexstr);
memcpy(cp->CCpriv,PonziCCpriv,32);
cp->validate = PonziValidate;
cp->ismyvin = IsPonziInput;
break;
case EVAL_AUCTION:
strcpy(cp->unspendableCCaddr,AuctionCCaddr);
strcpy(cp->normaladdr,AuctionNormaladdr);
strcpy(cp->CChexstr,AuctionCChexstr);
memcpy(cp->CCpriv,AuctionCCpriv,32);
cp->validate = AuctionValidate;
cp->ismyvin = IsAuctionInput;
break;
}
return(cp);
}

17
src/cc/CCcustom.inc

@ -0,0 +1,17 @@
bool FUNCNAME(CScript const& scriptSig)
{
CC *cond;
if (!(cond = GetCryptoCondition(scriptSig)))
return false;
// Recurse the CC tree to find asset condition
auto findEval = [] (CC *cond, struct CCVisitor _) {
bool r = cc_typeId(cond) == CC_Eval && cond->codeLength == 1 && cond->code[0] == EVALCODE;
// false for a match, true for continue
return r ? 0 : 1;
};
CCVisitor visitor = {findEval, (uint8_t*)"", 0, NULL};
bool out =! cc_visit(cond, visitor);
cc_free(cond);
return out;
}

32
src/cc/CCdice.h

@ -0,0 +1,32 @@
/******************************************************************************
* Copyright © 2014-2018 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. *
* *
******************************************************************************/
#ifndef CC_DICE_H
#define CC_DICE_H
#include "CCinclude.h"
#define EVAL_DICE 0xe6
bool DiceValidate(struct CCcontract_info *cp,Eval* eval,const CTransaction &tx);
std::string DiceBet(uint64_t txfee,char *planstr,uint256 fundingtxid,int64_t bet,int32_t odds);
std::string DiceCreateFunding(uint64_t txfee,char *planstr,int64_t funds,int64_t minbet,int64_t maxbet,int64_t maxodds,int64_t forfeitblocks);
std::string DiceAddfunding(uint64_t txfee,char *planstr,uint256 fundingtxid,int64_t amount);
UniValue DiceInfo(uint256 diceid);
UniValue DiceList();
#endif

30
src/cc/CCfaucet.h

@ -0,0 +1,30 @@
/******************************************************************************
* Copyright © 2014-2018 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. *
* *
******************************************************************************/
#ifndef CC_FAUCET_H
#define CC_FAUCET_H
#include "CCinclude.h"
#define EVAL_FAUCET 0xe4
bool FaucetValidate(struct CCcontract_info *cp,Eval* eval,const CTransaction &tx);
// CCcustom
std::string FaucetFund(uint64_t txfee,uint64_t funds);
std::string FaucetGet(uint64_t txfee);
#endif

82
src/cc/CCinclude.h

@ -0,0 +1,82 @@
/******************************************************************************
* Copyright © 2014-2018 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. *
* *
******************************************************************************/
#ifndef CC_INCLUDE_H
#define CC_INCLUDE_H
#include <cc/eval.h>
#include <script/cc.h>
#include <script/script.h>
#include <cryptoconditions.h>
#include "../script/standard.h"
#include "../base58.h"
#include "../core_io.h"
#include "../script/sign.h"
#include "../wallet/wallet.h"
#include <univalue.h>
#include <exception>
#define SMALLVAL 0.000000000000001
struct CCcontract_info
{
uint256 prevtxid;
char unspendableCCaddr[64],CChexstr[72],normaladdr[64];
uint8_t CCpriv[32];
bool (*validate)(struct CCcontract_info *cp,Eval* eval,const CTransaction &tx);
bool (*ismyvin)(CScript const& scriptSig);
uint8_t evalcode,didinit;
};
struct CCcontract_info *CCinit(struct CCcontract_info *cp,uint8_t evalcode);
#ifdef ENABLE_WALLET
extern CWallet* pwalletMain;
#endif
bool GetAddressUnspent(uint160 addressHash, int type,std::vector<std::pair<CAddressUnspentKey,CAddressUnspentValue> > &unspentOutputs);
static uint256 zeroid;
// CCcustom
CPubKey GetUnspendable(struct CCcontract_info *cp,uint8_t *unspendablepriv);
// CCutils
CTxOut MakeCC1vout(uint8_t evalcode,CAmount nValue,CPubKey pk);
CC *MakeCCcond1(uint8_t evalcode,CPubKey pk);
CC* GetCryptoCondition(CScript const& scriptSig);
bool IsCCInput(CScript const& scriptSig);
int32_t unstringbits(char *buf,uint64_t bits);
uint64_t stringbits(char *str);
uint256 revuint256(uint256 txid);
char *uint256_str(char *dest,uint256 txid);
char *pubkey33_str(char *dest,uint8_t *pubkey33);
uint256 Parseuint256(char *hexstr);
CPubKey pubkey2pk(std::vector<uint8_t> pubkey);
bool GetCCaddress(struct CCcontract_info *cp,char *destaddr,CPubKey pk);
bool ConstrainVout(CTxOut vout,int32_t CCflag,char *cmpaddr,uint64_t nValue);
bool PreventCC(Eval* eval,const CTransaction &tx,int32_t preventCCvins,int32_t numvins,int32_t preventCCvouts,int32_t numvouts);
bool Getscriptaddress(char *destaddr,const CScript &scriptPubKey);
std::vector<uint8_t> Mypubkey();
bool Myprivkey(uint8_t myprivkey[]);
int64_t CCduration(uint256 txid);
// CCtx
std::string FinalizeCCTx(uint64_t skipmask,struct CCcontract_info *cp,CMutableTransaction &mtx,CPubKey mypk,uint64_t txfee,CScript opret);
void SetCCunspents(std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> > &unspentOutputs,char *coinaddr);
void SetCCtxids(std::vector<std::pair<CAddressIndexKey, CAmount> > &addressIndex,char *coinaddr);
uint64_t AddNormalinputs(CMutableTransaction &mtx,CPubKey mypk,uint64_t total,int32_t maxinputs);
uint64_t CCutxovalue(char *coinaddr,uint256 utxotxid,int32_t utxovout);
#endif

29
src/cc/CClotto.h

@ -0,0 +1,29 @@
/******************************************************************************
* Copyright © 2014-2018 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. *
* *
******************************************************************************/
#ifndef CC_LOTTO_H
#define CC_LOTTO_H
#include "CCinclude.h"
#define EVAL_LOTTO 0xe9
bool LottoValidate(struct CCcontract_info *cp,Eval* eval,const CTransaction &tx);
std::string LottoTicket(uint64_t txfee,uint64_t numtickets);
std::string LottoWinner(uint64_t txfee);
#endif

29
src/cc/CCponzi.h

@ -0,0 +1,29 @@
/******************************************************************************
* Copyright © 2014-2018 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. *
* *
******************************************************************************/
#ifndef CC_PONZI_H
#define CC_PONZI_H
#include "CCinclude.h"
#define EVAL_PONZI 0xe7
bool PonziValidate(struct CCcontract_info *cp,Eval* eval,const CTransaction &tx);
std::string PonziBuy(uint64_t txfee,uint64_t amount);
std::string PonziClaim(uint64_t txfee);
#endif

33
src/cc/CCrewards.h

@ -0,0 +1,33 @@
/******************************************************************************
* Copyright © 2014-2018 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. *
* *
******************************************************************************/
#ifndef CC_REWARDS_H
#define CC_REWARDS_H
#include "CCinclude.h"
#define EVAL_REWARDS 0xe5
bool RewardsValidate(struct CCcontract_info *cp,Eval* eval,const CTransaction &tx);
UniValue RewardsInfo(uint256 rewardid);
UniValue RewardsList();
std::string RewardsCreateFunding(uint64_t txfee,char *planstr,int64_t funds,int64_t APR,int64_t minseconds,int64_t maxseconds,int64_t mindeposit);
std::string RewardsAddfunding(uint64_t txfee,char *planstr,uint256 fundingtxid,int64_t amount);
std::string RewardsLock(uint64_t txfee,char *planstr,uint256 fundingtxid,int64_t amount);
std::string RewardsUnlock(uint64_t txfee,char *planstr,uint256 fundingtxid,uint256 locktxid);
#endif

235
src/cc/CCtx.cpp

@ -0,0 +1,235 @@
/******************************************************************************
* Copyright © 2014-2018 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 "CCinclude.h"
/*
FinalizeCCTx is a very useful function that will properly sign both CC and normal inputs, adds normal change and the opreturn.
This allows the contract transaction functions to create the appropriate vins and vouts and have FinalizeCCTx create a properly signed transaction.
By using -addressindex=1, it allows tracking of all the CC addresses
*/
bool SignTx(CMutableTransaction &mtx,int32_t vini,uint64_t utxovalue,const CScript scriptPubKey)
{
#ifdef ENABLE_WALLET
CTransaction txNewConst(mtx); SignatureData sigdata; const CKeyStore& keystore = *pwalletMain;
auto consensusBranchId = CurrentEpochBranchId(chainActive.Height() + 1, Params().GetConsensus());
if ( ProduceSignature(TransactionSignatureCreator(&keystore,&txNewConst,vini,utxovalue,SIGHASH_ALL),scriptPubKey,sigdata,consensusBranchId) != 0 )
{
UpdateTransaction(mtx,vini,sigdata);
return(true);
} else fprintf(stderr,"signing error for SignTx vini.%d %.8f\n",vini,(double)utxovalue/COIN);
#else
return(false);
#endif
}
std::string FinalizeCCTx(uint64_t CCmask,struct CCcontract_info *cp,CMutableTransaction &mtx,CPubKey mypk,uint64_t txfee,CScript opret)
{
auto consensusBranchId = CurrentEpochBranchId(chainActive.Height() + 1, Params().GetConsensus());
CTransaction vintx; std::string hex; uint256 hashBlock; uint64_t mask=0,nmask=0,vinimask=0,utxovalues[64],change,normalinputs=0,totaloutputs=0,normaloutputs=0,totalinputs=0; int32_t i,utxovout,n,err = 0; char myaddr[64],destaddr[64],unspendable[64]; uint8_t *privkey,myprivkey[32],unspendablepriv[32],*msg32 = 0; CC *mycond=0,*othercond=0,*cond; CPubKey unspendablepk;
n = mtx.vout.size();
for (i=0; i<n; i++)
{
if ( mtx.vout[i].scriptPubKey.IsPayToCryptoCondition() == 0 )
normaloutputs += mtx.vout[i].nValue;
totaloutputs += mtx.vout[i].nValue;
}
if ( (n= mtx.vin.size()) > 64 )
{
fprintf(stderr,"FinalizeCCTx: %d is too many vins\n",n);
return(0);
}
Myprivkey(myprivkey);
unspendablepk = GetUnspendable(cp,unspendablepriv);
GetCCaddress(cp,myaddr,mypk);
mycond = MakeCCcond1(cp->evalcode,mypk);
GetCCaddress(cp,unspendable,unspendablepk);
othercond = MakeCCcond1(cp->evalcode,unspendablepk);
//fprintf(stderr,"myCCaddr.(%s) %p vs unspendable.(%s) %p\n",myaddr,mycond,unspendable,othercond);
memset(utxovalues,0,sizeof(utxovalues));
for (i=0; i<n; i++)
{
if ( GetTransaction(mtx.vin[i].prevout.hash,vintx,hashBlock,false) != 0 )
{
utxovout = mtx.vin[i].prevout.n;
utxovalues[i] = vintx.vout[utxovout].nValue;
totalinputs += utxovalues[i];
if ( vintx.vout[utxovout].scriptPubKey.IsPayToCryptoCondition() == 0 )
{
//fprintf(stderr,"vin.%d is normal %.8f\n",i,(double)utxovalues[i]/COIN);
normalinputs += utxovalues[i];
vinimask |= (1LL << i);
}
else
{
mask |= (1LL << i);
}
} else fprintf(stderr,"FinalizeCCTx couldnt find %s\n",mtx.vin[i].prevout.hash.ToString().c_str());
}
nmask = (1LL << n) - 1;
if ( (mask & nmask) != (CCmask & nmask) )
fprintf(stderr,"mask.%llx vs CCmask.%llx %llx %llx %llx\n",(long long)(mask & nmask),(long long)(CCmask & nmask),(long long)mask,(long long)CCmask,(long long)nmask);
if ( totalinputs >= totaloutputs+2*txfee )
{
change = totalinputs - (totaloutputs+txfee);
mtx.vout.push_back(CTxOut(change,CScript() << ParseHex(HexStr(mypk)) << OP_CHECKSIG));
}
if ( opret.size() > 0 )
mtx.vout.push_back(CTxOut(0,opret));
PrecomputedTransactionData txdata(mtx);
n = mtx.vin.size();
for (i=0; i<n; i++)
{
if ( GetTransaction(mtx.vin[i].prevout.hash,vintx,hashBlock,false) != 0 )
{
utxovout = mtx.vin[i].prevout.n;
if ( vintx.vout[utxovout].scriptPubKey.IsPayToCryptoCondition() == 0 )
{
if ( SignTx(mtx,i,vintx.vout[utxovout].nValue,vintx.vout[utxovout].scriptPubKey) == 0 )
fprintf(stderr,"signing error for vini.%d of %llx\n",i,(long long)vinimask);
}
else
{
Getscriptaddress(destaddr,vintx.vout[utxovout].scriptPubKey);
//fprintf(stderr,"vin.%d is CC %.8f -> (%s)\n",i,(double)utxovalues[i]/COIN,destaddr);
if ( strcmp(destaddr,myaddr) == 0 )
{
privkey = myprivkey;
cond = mycond;
//fprintf(stderr,"my CC addr.(%s)\n",myaddr);
}
else if ( strcmp(destaddr,unspendable) == 0 )
{
privkey = unspendablepriv;
cond = othercond;
//fprintf(stderr,"unspendable CC addr.(%s)\n",unspendable);
}
else
{
fprintf(stderr,"vini.%d has unknown CC address.(%s)\n",i,destaddr);
continue;
}
uint256 sighash = SignatureHash(CCPubKey(cond), mtx, i, SIGHASH_ALL, utxovalues[i],consensusBranchId, &txdata);
if ( cc_signTreeSecp256k1Msg32(cond,privkey,sighash.begin()) != 0 )
{
//int32_t z;
//for (z=0; z<32; z++)
// fprintf(stderr,"%02x",((uint8_t *)sighash.begin())[z]);
//fprintf(stderr," sighash, ");
//for (z=0; z<32; z++)
// fprintf(stderr,"%02x",privkey[z]);
//fprintf(stderr," signed with privkey\n");
mtx.vin[i].scriptSig = CCSig(cond);
}
else fprintf(stderr,"vini.%d has CC signing error address.(%s)\n",i,destaddr);
}
} else fprintf(stderr,"FinalizeCCTx couldnt find %s\n",mtx.vin[i].prevout.hash.ToString().c_str());
}
if ( mycond != 0 )
cc_free(mycond);
if ( othercond != 0 )
cc_free(othercond);
std::string strHex = EncodeHexTx(mtx);
if ( strHex.size() > 0 )
return(strHex);
else return(0);
}
void SetCCunspents(std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> > &unspentOutputs,char *coinaddr)
{
int32_t type=0,i,n; char *ptr; std::string addrstr; uint160 hashBytes; std::vector<std::pair<uint160, int> > addresses;
n = (int32_t)strlen(coinaddr);
addrstr.resize(n+1);
ptr = (char *)addrstr.data();
for (i=0; i<=n; i++)
ptr[i] = coinaddr[i];
CBitcoinAddress address(addrstr);
if ( address.GetIndexKey(hashBytes, type) == 0 )
return;
addresses.push_back(std::make_pair(hashBytes,type));
for (std::vector<std::pair<uint160, int> >::iterator it = addresses.begin(); it != addresses.end(); it++)
{
if ( GetAddressUnspent((*it).first, (*it).second, unspentOutputs) == 0 )
return;
}
}
void SetCCtxids(std::vector<std::pair<CAddressIndexKey, CAmount> > &addressIndex,char *coinaddr)
{
int32_t type=0,i,n; char *ptr; std::string addrstr; uint160 hashBytes; std::vector<std::pair<uint160, int> > addresses;
n = (int32_t)strlen(coinaddr);
addrstr.resize(n+1);
ptr = (char *)addrstr.data();
for (i=0; i<=n; i++)
ptr[i] = coinaddr[i];
CBitcoinAddress address(addrstr);
if ( address.GetIndexKey(hashBytes, type) == 0 )
return;
addresses.push_back(std::make_pair(hashBytes,type));
for (std::vector<std::pair<uint160, int> >::iterator it = addresses.begin(); it != addresses.end(); it++)
{
if ( GetAddressIndex((*it).first, (*it).second, addressIndex) == 0 )
return;
}
}
uint64_t CCutxovalue(char *coinaddr,uint256 utxotxid,int32_t utxovout)
{
uint256 txid; std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> > unspentOutputs;
SetCCunspents(unspentOutputs,coinaddr);
for (std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++)
{
txid = it->first.txhash;
if ( txid == utxotxid && utxovout == it->first.index )
return(it->second.satoshis);
}
return(0);
}
uint64_t AddNormalinputs(CMutableTransaction &mtx,CPubKey mypk,uint64_t total,int32_t maxinputs)
{
int32_t vout,j,n = 0; uint64_t nValue,totalinputs = 0; uint256 txid; std::vector<COutput> vecOutputs;
#ifdef ENABLE_WALLET
const CKeyStore& keystore = *pwalletMain;
assert(pwalletMain != NULL);
LOCK2(cs_main, pwalletMain->cs_wallet);
pwalletMain->AvailableCoins(vecOutputs, false, NULL, true);
BOOST_FOREACH(const COutput& out, vecOutputs)
{
if ( out.fSpendable != 0 )
{
txid = out.tx->GetHash();
vout = out.i;
for (j=0; j<mtx.vin.size(); j++)
if ( txid == mtx.vin[j].prevout.hash && vout == mtx.vin[j].prevout.n )
break;
if ( j != mtx.vin.size() )
continue;
mtx.vin.push_back(CTxIn(txid,vout,CScript()));
nValue = out.tx->vout[out.i].nValue;
totalinputs += nValue;
n++;
if ( totalinputs >= total || n >= maxinputs )
break;
}
}
if ( totalinputs >= total )
return(totalinputs);
#endif
return(0);
}

298
src/cc/CCutils.cpp

@ -0,0 +1,298 @@
/******************************************************************************
* Copyright © 2014-2018 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 "CCinclude.h"
/*
CCutils has low level functions that are universally useful for all contracts.
*/
CTxOut MakeCC1vout(uint8_t evalcode,CAmount nValue,CPubKey pk)
{
CTxOut vout;
CC *payoutCond = MakeCCcond1(evalcode,pk);
vout = CTxOut(nValue,CCPubKey(payoutCond));
cc_free(payoutCond);
return(vout);
}
CC *MakeCCcond1(uint8_t evalcode,CPubKey pk)
{
std::vector<CC*> pks;
pks.push_back(CCNewSecp256k1(pk));
CC *condCC = CCNewEval(E_MARSHAL(ss << evalcode));
CC *Sig = CCNewThreshold(1, pks);
return CCNewThreshold(2, {condCC, Sig});
}
CC* GetCryptoCondition(CScript const& scriptSig)
{
auto pc = scriptSig.begin();
opcodetype opcode;
std::vector<unsigned char> ffbin;
if (scriptSig.GetOp(pc, opcode, ffbin))
return cc_readFulfillmentBinary((uint8_t*)ffbin.data(), ffbin.size()-1);
}
bool IsCCInput(CScript const& scriptSig)
{
CC *cond;
if ( (cond= GetCryptoCondition(scriptSig)) == 0 )
return false;
cc_free(cond);
return true;
}
int32_t unstringbits(char *buf,uint64_t bits)
{
int32_t i;
for (i=0; i<8; i++,bits>>=8)
if ( (buf[i]= (char)(bits & 0xff)) == 0 )
break;
buf[i] = 0;
return(i);
}
uint64_t stringbits(char *str)
{
uint64_t bits = 0;
if ( str == 0 )
return(0);
int32_t i,n = (int32_t)strlen(str);
if ( n > 8 )
n = 8;
for (i=n-1; i>=0; i--)
bits = (bits << 8) | (str[i] & 0xff);
//printf("(%s) -> %llx %llu\n",str,(long long)bits,(long long)bits);
return(bits);
}
uint256 revuint256(uint256 txid)
{
uint256 revtxid; int32_t i;
for (i=31; i>=0; i--)
((uint8_t *)&revtxid)[31-i] = ((uint8_t *)&txid)[i];
return(revtxid);
}
char *uint256_str(char *dest,uint256 txid)
{
int32_t i,j=0;
for (i=31; i>=0; i--)
sprintf(&dest[j++ * 2],"%02x",((uint8_t *)&txid)[i]);
dest[64] = 0;
return(dest);
}
char *pubkey33_str(char *dest,uint8_t *pubkey33)
{
int32_t i;
if ( pubkey33 != 0 )
{
for (i=0; i<33; i++)
sprintf(&dest[i * 2],"%02x",pubkey33[i]);
} else dest[0] = 0;
return(dest);
}
uint256 Parseuint256(char *hexstr)
{
uint256 txid; int32_t i; std::vector<unsigned char> txidbytes(ParseHex(hexstr));
memset(&txid,0,sizeof(txid));
if ( strlen(hexstr) == 64 )
{
for (i=31; i>=0; i--)
((uint8_t *)&txid)[31-i] = ((uint8_t *)txidbytes.data())[i];
}
return(txid);
}
CPubKey pubkey2pk(std::vector<uint8_t> pubkey)
{
CPubKey pk; int32_t i,n; uint8_t *dest,*pubkey33;
n = pubkey.size();
dest = (uint8_t *)pk.begin();
pubkey33 = (uint8_t *)pubkey.data();
for (i=0; i<n; i++)
dest[i] = pubkey33[i];
return(pk);
}
bool Getscriptaddress(char *destaddr,const CScript &scriptPubKey)
{
CTxDestination address; txnouttype whichType;
if ( ExtractDestination(scriptPubKey,address) != 0 )
{
strcpy(destaddr,(char *)CBitcoinAddress(address).ToString().c_str());
return(true);
}
fprintf(stderr,"ExtractDestination failed\n");
return(false);
}
bool GetCCaddress(struct CCcontract_info *cp,char *destaddr,CPubKey pk)
{
CC *payoutCond;
destaddr[0] = 0;
if ( pk.size() == 0 )
pk = GetUnspendable(cp,0);
if ( (payoutCond= MakeCCcond1(cp->evalcode,pk)) != 0 )
{
Getscriptaddress(destaddr,CCPubKey(payoutCond));
cc_free(payoutCond);
}
return(destaddr[0] != 0);
}
bool ConstrainVout(CTxOut vout,int32_t CCflag,char *cmpaddr,uint64_t nValue)
{
char destaddr[64];
if ( vout.scriptPubKey.IsPayToCryptoCondition() != CCflag )
{
fprintf(stderr,"constrain vout error isCC %d vs %d CCflag\n",vout.scriptPubKey.IsPayToCryptoCondition(),CCflag);
return(false);
}
else if ( cmpaddr != 0 && (Getscriptaddress(destaddr,vout.scriptPubKey) == 0 || strcmp(destaddr,cmpaddr) != 0) )
{
fprintf(stderr,"constrain vout error addr %s vs %s\n",cmpaddr!=0?cmpaddr:"",destaddr!=0?destaddr:"");
return(false);
}
else if ( nValue != 0 && nValue != vout.nValue ) //(nValue == 0 && vout.nValue < 10000) || (
{
fprintf(stderr,"constrain vout error nValue %.8f vs %.8f\n",(double)nValue/COIN,(double)vout.nValue/COIN);
return(false);
}
else return(true);
}
bool PreventCC(Eval* eval,const CTransaction &tx,int32_t preventCCvins,int32_t numvins,int32_t preventCCvouts,int32_t numvouts)
{
int32_t i;
if ( preventCCvins >= 0 )
{
for (i=preventCCvins; i<numvins; i++)
{
if ( IsCCInput(tx.vin[i].scriptSig) != 0 )
return eval->Invalid("invalid CC vin");
}
}
if ( preventCCvouts >= 0 )
{
for (i=preventCCvouts; i<numvouts; i++)
{
if ( tx.vout[i].scriptPubKey.IsPayToCryptoCondition() != 0 )
return eval->Invalid("invalid CC vout");
}
}
return(true);
}
std::vector<uint8_t> Mypubkey()
{
extern uint8_t NOTARY_PUBKEY33[33];
std::vector<uint8_t> pubkey; int32_t i; uint8_t *dest,*pubkey33;
pubkey33 = NOTARY_PUBKEY33;
pubkey.resize(33);
dest = pubkey.data();
for (i=0; i<33; i++)
dest[i] = pubkey33[i];
return(pubkey);
}
bool Myprivkey(uint8_t myprivkey[])
{
char coinaddr[64]; std::string strAddress; char *dest; int32_t i,n; CBitcoinAddress address; CKeyID keyID; CKey vchSecret;
if ( Getscriptaddress(coinaddr,CScript() << Mypubkey() << OP_CHECKSIG) != 0 )
{
n = (int32_t)strlen(coinaddr);
strAddress.resize(n+1);
dest = (char *)strAddress.data();
for (i=0; i<n; i++)
dest[i] = coinaddr[i];
dest[i] = 0;
if ( address.SetString(strAddress) != 0 && address.GetKeyID(keyID) != 0 )
{
#ifdef ENABLE_WALLET
if ( pwalletMain->GetKey(keyID,vchSecret) != 0 )
{
memcpy(myprivkey,vchSecret.begin(),32);
if ( 0 )
{
for (i=0; i<32; i++)
fprintf(stderr,"0x%02x, ",myprivkey[i]);
fprintf(stderr," found privkey!\n");
}
return(true);
}
#endif
}
}
fprintf(stderr,"privkey for the -pubkey= address is not in the wallet, importprivkey!\n");
return(false);
}
CPubKey GetUnspendable(struct CCcontract_info *cp,uint8_t *unspendablepriv)
{
if ( unspendablepriv != 0 )
memcpy(unspendablepriv,cp->CCpriv,32);
return(pubkey2pk(ParseHex(cp->CChexstr)));
}
bool ProcessCC(struct CCcontract_info *cp,Eval* eval, std::vector<uint8_t> paramsNull,const CTransaction &ctx, unsigned int nIn)
{
CTransaction createTx; uint256 txid,assetid,assetid2,hashBlock; uint8_t funcid; int32_t i,n; uint64_t amount; std::vector<uint8_t> origpubkey;
txid = ctx.GetHash();
if ( txid == cp->prevtxid )
return(true);
if ( paramsNull.size() != 0 ) // Don't expect params
return eval->Invalid("Cannot have params");
else if ( ctx.vout.size() == 0 )
return eval->Invalid("no-vouts");
else if ( (*cp->validate)(cp,eval,ctx) != 0 )
{
cp->prevtxid = txid;
return(true);
}
return(false);
}
int64_t CCduration(uint256 txid)
{
CTransaction tx; uint256 hashBlock; uint32_t txtime=0; char str[65]; CBlockIndex *pindex; int64_t duration = 0;
if ( GetTransaction(txid,tx,hashBlock,false) == 0 )
{
fprintf(stderr,"CCduration cant find duration txid %s\n",uint256_str(str,txid));
return(0);
}
else if ( hashBlock == zeroid )
{
fprintf(stderr,"CCduration no hashBlock for txid %s\n",uint256_str(str,txid));
return(0);
}
else if ( (pindex= mapBlockIndex[hashBlock]) == 0 || (txtime= pindex->nTime) == 0 )
{
fprintf(stderr,"CCduration no txtime %u %p for txid %s\n",txtime,pindex,uint256_str(str,txid));
return(0);
}
else if ( (pindex= chainActive.LastTip()) == 0 || pindex->nTime < txtime )
{
fprintf(stderr,"CCduration backwards timestamps %u %u for txid %s\n",(uint32_t)pindex->nTime,txtime,uint256_str(str,txid));
return(0);
}
duration = (pindex->nTime - txtime);
fprintf(stderr,"duration %d (%u - %u)\n",(int32_t)duration,(uint32_t)pindex->nTime,txtime);
return(duration);
}

367
src/cc/assets.cpp

@ -0,0 +1,367 @@
/******************************************************************************
* Copyright © 2014-2018 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 "CCassets.h"
/*
Assets can be created or transferred.
native coins are also locked in the EVAL_ASSETS address, so we need a strict rule on when utxo in the special address are native coins and when they are assets. The specific rule that must not be violated is that vout0 for 'b'/'B' funcid are native coins. All other utxo locked in the special address are assets.
To create an asset use CC EVAL_ASSETS to create a transaction where vout[0] funds the assets. Externally each satoshi can be interpreted to represent 1 asset, or 100 million satoshis for one asset with 8 decimals, and the other decimals in between. The interpretation of the number of decimals is left to the higher level usages.
Once created, the assetid is the txid of the create transaction and using the assetid/0 it can spend the assets to however many outputs it creates. The restriction is that the last output must be an opreturn with the assetid. The sum of all but the first output needs to add up to the total assetoshis input. The first output is ignored and used for change from txfee.
What this means is that vout 0 of the creation txid and vouts 1 ... n-2 for transfer vouts are assetoshi outputs.
There is a special type of transfer to an unspendable address, that locks the asset and creates an offer for all. The details specified in the opreturn. In order to be compatible with the signing restrictions, the "unspendable" address is actually an address whose privkey is known to all. Funds sent to this address can only be spent if the swap parameters are fulfilled, or if the original pubkey cancels the offer by spending it.
Types of transactions:
create name:description -> txid for assetid
transfer <pubkey> <assetid> -> [{address:amount}, ... ] // like withdraw api
selloffer <pubkey> <txid/vout> <amount> -> cancel or fillsell -> mempool txid or rejected, might not confirm
buyoffer <amount> <assetid> <required> -> cancelbuy or fillbuy -> mempool txid or rejected, might not confirm
exchange <pubkey> <txid/vout> <required> <required assetid> -> cancel or fillexchange -> mempool txid or rejected, might not confirm
assetsaddress <pubkey> // all assets end up in a special address for each pubkey
assetbalance <pubkey> <assetid>
assetutxos <pubkey> <assetid>
assetsbalances <pubkey>
asks <assetid>
bids <assetid>
swaps <assetid>
valid CC output: create or transfer or buyoffer or selloffer or exchange or cancel or fill
create
vin.0: normal input
vout.0: issuance assetoshis to CC
vout.1: tag sent to normal address of AssetsCCaddress
vout.2: normal output for change (if any)
vout.n-1: opreturn [EVAL_ASSETS] ['c'] [origpubkey] "<assetname>" "<description>"
transfer
vin.0: normal input
vin.1 .. vin.n-1: valid CC outputs
vout.0 to n-2: assetoshis output to CC
vout.n-2: normal output for change (if any)
vout.n-1: opreturn [EVAL_ASSETS] ['t'] [assetid]
buyoffer:
vins.*: normal inputs (bid + change)
vout.0: amount of bid to unspendable
vout.1: normal output for change (if any)
vout.n-1: opreturn [EVAL_ASSETS] ['b'] [assetid] [amount of asset required] [origpubkey]
cancelbuy:
vin.0: normal input
vin.1: unspendable.(vout.0 from buyoffer) buyTx.vout[0]
vout.0: vin.1 value to original pubkey buyTx.vout[0].nValue -> [origpubkey]
vout.1: normal output for change (if any)
vout.n-1: opreturn [EVAL_ASSETS] ['o'] [assetid]
fillbuy:
vin.0: normal input
vin.1: unspendable.(vout.0 from buyoffer) buyTx.vout[0]
vin.2+: valid CC output satisfies buyoffer (*tx.vin[2])->nValue
vout.0: remaining amount of bid to unspendable
vout.1: vin.1 value to signer of vin.2
vout.2: vin.2 assetoshis to original pubkey
vout.3: CC output for assetoshis change (if any)
vout.4: normal output for change (if any)
vout.n-1: opreturn [EVAL_ASSETS] ['B'] [assetid] [remaining asset required] [origpubkey]
selloffer:
vin.0: normal input
vin.1+: valid CC output for sale
vout.0: vin.1 assetoshis output to CC to unspendable
vout.1: CC output for change (if any)
vout.2: normal output for change (if any)
vout.n-1: opreturn [EVAL_ASSETS] ['s'] [assetid] [amount of native coin required] [origpubkey]
exchange:
vin.0: normal input
vin.1+: valid CC output
vout.0: vin.1 assetoshis output to CC to unspendable
vout.1: CC output for change (if any)
vout.2: normal output for change (if any)
vout.n-1: opreturn [EVAL_ASSETS] ['e'] [assetid] [assetid2] [amount of asset2 required] [origpubkey]
cancel:
vin.0: normal input
vin.1: unspendable.(vout.0 from exchange or selloffer) sellTx/exchangeTx.vout[0] inputTx
vout.0: vin.1 assetoshis to original pubkey CC sellTx/exchangeTx.vout[0].nValue -> [origpubkey]
vout.1: normal output for change (if any)
vout.n-1: opreturn [EVAL_ASSETS] ['x'] [assetid]
fillsell:
vin.0: normal input
vin.1: unspendable.(vout.0 assetoshis from selloffer) sellTx.vout[0]
vin.2+: normal output that satisfies selloffer (*tx.vin[2])->nValue
vout.0: remaining assetoshis -> unspendable
vout.1: vin.1 assetoshis to signer of vin.2 sellTx.vout[0].nValue -> any
vout.2: vin.2 value to original pubkey [origpubkey]
vout.3: CC asset for change (if any)
vout.4: CC asset2 for change (if any) 'E' only
vout.5: normal output for change (if any)
vout.n-1: opreturn [EVAL_ASSETS] ['S'] [assetid] [amount of coin still required] [origpubkey]
fillexchange:
vin.0: normal input
vin.1: unspendable.(vout.0 assetoshis from exchange) exchangeTx.vout[0]
vin.2+: valid CC assetid2 output that satisfies exchange (*tx.vin[2])->nValue
vout.0: remaining assetoshis -> unspendable
vout.1: vin.1 assetoshis to signer of vin.2 exchangeTx.vout[0].nValue -> any
vout.2: vin.2 assetoshis2 to original pubkey [origpubkey]
vout.3: normal output for change (if any)
vout.n-1: opreturn [EVAL_ASSETS] ['E'] [assetid vin0+1] [assetid vin2] [remaining asset2 required] [origpubkey]
*/
bool AssetsValidate(struct CCcontract_info *cp,Eval* eval,const CTransaction &tx)
{
static uint256 zero;
CTxDestination address; CTransaction vinTx,createTx; uint256 hashBlock,assetid,assetid2; int32_t i,starti,numvins,numvouts,preventCCvins,preventCCvouts; int64_t remaining_price,nValue,assetoshis,outputs,inputs,tmpprice,totalunits,ignore; std::vector<uint8_t> origpubkey,tmporigpubkey,ignorepubkey; uint8_t funcid; char destaddr[64],origaddr[64],CCaddr[64];
numvins = tx.vin.size();
numvouts = tx.vout.size();
outputs = inputs = 0;
preventCCvins = preventCCvouts = -1;
if ( (funcid= DecodeAssetOpRet(tx.vout[numvouts-1].scriptPubKey,assetid,assetid2,remaining_price,origpubkey)) == 0 )
return eval->Invalid("Invalid opreturn payload");
fprintf(stderr,"AssetValidate (%c)\n",funcid);
if ( funcid != 'o' && funcid != 'x' && eval->GetTxUnconfirmed(assetid,createTx,hashBlock) == 0 )
return eval->Invalid("cant find asset create txid");
else if ( funcid != 'o' && funcid != 'x' && assetid2 != zero && eval->GetTxUnconfirmed(assetid2,createTx,hashBlock) == 0 )
return eval->Invalid("cant find asset2 create txid");
else if ( IsCCInput(tx.vin[0].scriptSig) != 0 )
return eval->Invalid("illegal asset vin0");
else if ( numvouts < 1 )
return eval->Invalid("no vouts");
else if ( funcid != 'c' )
{
if ( funcid == 't' )
starti = 0;
else starti = 1;
if ( assetid == zero )
return eval->Invalid("illegal assetid");
else if ( AssetExactAmounts(cp,inputs,starti,outputs,eval,tx,assetid) == false )
return eval->Invalid("asset inputs != outputs");
}
switch ( funcid )
{
case 'c': // create wont be called to be verified as it has no CC inputs
//vin.0: normal input
//vout.0: issuance assetoshis to CC
//vout.1: normal output for change (if any)
//vout.n-1: opreturn [EVAL_ASSETS] ['c'] [{"<assetname>":"<description>"}]
return eval->Invalid("unexpected AssetValidate for createasset");
break;
case 't': // transfer
//vin.0: normal input
//vin.1 .. vin.n-1: valid CC outputs
//vout.0 to n-2: assetoshis output to CC
//vout.n-2: normal output for change (if any)
//vout.n-1: opreturn [EVAL_ASSETS] ['t'] [assetid]
if ( inputs == 0 )
return eval->Invalid("no asset inputs for transfer");
fprintf(stderr,"transfer validated %.8f -> %.8f\n",(double)inputs/COIN,(double)outputs/COIN);
break;
case 'b': // buyoffer
//vins.*: normal inputs (bid + change)
//vout.0: amount of bid to unspendable
//vout.1: normal output for change (if any)
// vout.n-1: opreturn [EVAL_ASSETS] ['b'] [assetid] [amount of asset required] [origpubkey]
if ( remaining_price == 0 )
return eval->Invalid("illegal null amount for buyoffer");
else if ( ConstrainVout(tx.vout[0],1,cp->unspendableCCaddr,0) == 0 )
return eval->Invalid("invalid vout for buyoffer");
preventCCvins = 1;
preventCCvouts = 1;
fprintf(stderr,"buy offer validated to destaddr.(%s)\n",cp->unspendableCCaddr);
break;
case 'o': // cancelbuy
//vin.0: normal input
//vin.1: unspendable.(vout.0 from buyoffer) buyTx.vout[0]
//vout.0: vin.1 value to original pubkey buyTx.vout[0].nValue -> [origpubkey]
//vout.1: normal output for change (if any)
//vout.n-1: opreturn [EVAL_ASSETS] ['o']
if ( (nValue= AssetValidateBuyvin(cp,eval,tmpprice,tmporigpubkey,CCaddr,origaddr,tx,assetid)) == 0 )
return(false);
else if ( ConstrainVout(tx.vout[0],0,origaddr,nValue) == 0 )
return eval->Invalid("invalid refund for cancelbuy");
preventCCvins = 2;
preventCCvouts = 0;
fprintf(stderr,"cancelbuy validated to origaddr.(%s)\n",origaddr);
break;
case 'B': // fillbuy:
//vin.0: normal input
//vin.1: unspendable.(vout.0 from buyoffer) buyTx.vout[0]
//vin.2+: valid CC output satisfies buyoffer (*tx.vin[2])->nValue
//vout.0: remaining amount of bid to unspendable
//vout.1: vin.1 value to signer of vin.2
//vout.2: vin.2 assetoshis to original pubkey
//vout.3: CC output for assetoshis change (if any)
//vout.4: normal output for change (if any)
//vout.n-1: opreturn [EVAL_ASSETS] ['B'] [assetid] [remaining asset required] [origpubkey]
preventCCvouts = 4;
if ( (nValue= AssetValidateBuyvin(cp,eval,totalunits,tmporigpubkey,CCaddr,origaddr,tx,assetid)) == 0 )
return(false);
else if ( numvouts < 3 )
return eval->Invalid("not enough vouts for fillbuy");
else if ( tmporigpubkey != origpubkey )
return eval->Invalid("mismatched origpubkeys for fillbuy");
else
{
if ( nValue != tx.vout[0].nValue+tx.vout[1].nValue )
return eval->Invalid("locked value doesnt match vout0+1 fillbuy");
else if ( tx.vout[3].scriptPubKey.IsPayToCryptoCondition() != 0 )
{
if ( ConstrainVout(tx.vout[2],1,CCaddr,0) == 0 )
return eval->Invalid("vout2 doesnt go to origpubkey fillbuy");
else if ( inputs != tx.vout[2].nValue+tx.vout[3].nValue )
return eval->Invalid("asset inputs doesnt match vout2+3 fillbuy");
}
else if ( ConstrainVout(tx.vout[2],1,CCaddr,inputs) == 0 )
return eval->Invalid("vout2 doesnt match inputs fillbuy");
else if ( ConstrainVout(tx.vout[1],0,0,0) == 0 )
return eval->Invalid("vout1 is CC for fillbuy");
else if ( ValidateBidRemainder(remaining_price,tx.vout[0].nValue,nValue,tx.vout[1].nValue,tx.vout[2].nValue,totalunits) == false )
return eval->Invalid("mismatched remainder for fillbuy");
else if ( remaining_price != 0 )
{
if ( ConstrainVout(tx.vout[0],1,cp->unspendableCCaddr,0) == 0 )
return eval->Invalid("mismatched vout0 AssetsCCaddr for fillbuy");
}
}
fprintf(stderr,"fillbuy validated\n");
break;
case 's': // selloffer
case 'e': // exchange
//vin.0: normal input
//vin.1+: valid CC output for sale
//vout.0: vin.1 assetoshis output to CC to unspendable
//vout.1: normal output for change (if any)
//'s'.vout.n-1: opreturn [EVAL_ASSETS] ['s'] [assetid] [amount of native coin required] [origpubkey]
//'e'.vout.n-1: opreturn [EVAL_ASSETS] ['e'] [assetid] [assetid2] [amount of asset2 required] [origpubkey]
if ( remaining_price == 0 )
return eval->Invalid("illegal null remaining_price for selloffer");
else if ( ConstrainVout(tx.vout[0],1,(char *)cp->unspendableCCaddr,inputs) == 0 )
return eval->Invalid("mismatched vout0 AssetsCCaddr for selloffer");
//fprintf(stderr,"remaining.%d for sell\n",(int32_t)remaining_price);
preventCCvouts = 1;
break;
case 'x': // cancel
//vin.0: normal input
//vin.1: unspendable.(vout.0 from exchange or selloffer) sellTx/exchangeTx.vout[0] inputTx
//vout.0: vin.1 assetoshis to original pubkey CC sellTx/exchangeTx.vout[0].nValue -> [origpubkey]
//vout.1: normal output for change (if any)
//vout.n-1: opreturn [EVAL_ASSETS] ['x'] [assetid]
if ( (assetoshis= AssetValidateSellvin(cp,eval,tmpprice,tmporigpubkey,CCaddr,origaddr,tx,assetid)) == 0 )
return(false);
else if ( ConstrainVout(tx.vout[0],1,CCaddr,assetoshis) == 0 )
return eval->Invalid("invalid vout for cancel");
preventCCvins = 2;
preventCCvouts = 1;
break;
case 'S': // fillsell
//vin.0: normal input
//vin.1: unspendable.(vout.0 assetoshis from selloffer) sellTx.vout[0]
//'S'.vin.2+: normal output that satisfies selloffer (*tx.vin[2])->nValue
//vout.0: remaining assetoshis -> unspendable
//vout.1: vin.1 assetoshis to signer of vin.2 sellTx.vout[0].nValue -> any
//'S'.vout.2: vin.2 value to original pubkey [origpubkey]
//vout.3: normal output for change (if any)
//'S'.vout.n-1: opreturn [EVAL_ASSETS] ['S'] [assetid] [amount of coin still required] [origpubkey]
if ( (assetoshis= AssetValidateSellvin(cp,eval,totalunits,tmporigpubkey,CCaddr,origaddr,tx,assetid)) == 0 )
return(false);
else if ( numvouts < 3 )
return eval->Invalid("not enough vouts for fillask");
else if ( tmporigpubkey != origpubkey )
return eval->Invalid("mismatched origpubkeys for fillask");
else
{
if ( assetoshis != tx.vout[0].nValue+tx.vout[1].nValue )
return eval->Invalid("locked value doesnt match vout0+1 fillask");
if ( ValidateAskRemainder(remaining_price,tx.vout[0].nValue,assetoshis,tx.vout[1].nValue,tx.vout[2].nValue,totalunits) == false )
return eval->Invalid("mismatched remainder for fillask");
else if ( ConstrainVout(tx.vout[1],1,0,0) == 0 )
return eval->Invalid("normal vout1 for fillask");
else if ( ConstrainVout(tx.vout[2],0,origaddr,0) == 0 )
return eval->Invalid("normal vout1 for fillask");
else if ( remaining_price != 0 )
{
if ( ConstrainVout(tx.vout[0],1,(char *)cp->unspendableCCaddr,0) == 0 )
return eval->Invalid("mismatched vout0 AssetsCCaddr for fill");
}
}
fprintf(stderr,"fill validated\n");
break;
case 'E': // fillexchange
//vin.0: normal input
//vin.1: unspendable.(vout.0 assetoshis from selloffer) sellTx.vout[0]
//vin.2+: valid CC assetid2 output that satisfies exchange (*tx.vin[2])->nValue
//vout.0: remaining assetoshis -> unspendable
//vout.1: vin.1 assetoshis to signer of vin.2 sellTx.vout[0].nValue -> any
//vout.2: vin.2+ assetoshis2 to original pubkey [origpubkey]
//vout.3: CC output for asset2 change (if any)
//vout.3/4: normal output for change (if any)
//vout.n-1: opreturn [EVAL_ASSETS] ['E'] [assetid vin0+1] [assetid vin2] [remaining asset2 required] [origpubkey]
if ( AssetExactAmounts(cp,inputs,1,outputs,eval,tx,assetid2) == false )
eval->Invalid("asset2 inputs != outputs");
if ( (assetoshis= AssetValidateSellvin(cp,eval,totalunits,tmporigpubkey,CCaddr,origaddr,tx,assetid)) == 0 )
return(false);
else if ( numvouts < 3 )
return eval->Invalid("not enough vouts for fillex");
else if ( tmporigpubkey != origpubkey )
return eval->Invalid("mismatched origpubkeys for fillex");
else
{
if ( assetoshis != tx.vout[0].nValue+tx.vout[1].nValue )
return eval->Invalid("locked value doesnt match vout0+1 fillex");
else if ( tx.vout[3].scriptPubKey.IsPayToCryptoCondition() != 0 )
{
if ( ConstrainVout(tx.vout[2],1,CCaddr,0) == 0 )
return eval->Invalid("vout2 doesnt go to origpubkey fillex");
else if ( inputs != tx.vout[2].nValue+tx.vout[3].nValue )
return eval->Invalid("asset inputs doesnt match vout2+3 fillex");
}
else if ( ConstrainVout(tx.vout[2],1,CCaddr,inputs) == 0 )
return eval->Invalid("vout2 doesnt match inputs fillex");
else if ( ConstrainVout(tx.vout[1],0,0,0) == 0 )
return eval->Invalid("vout1 is CC for fillex");
fprintf(stderr,"assets vout0 %llu, vin1 %llu, vout2 %llu -> orig, vout1 %llu, total %llu\n",(long long)tx.vout[0].nValue,(long long)assetoshis,(long long)tx.vout[2].nValue,(long long)tx.vout[1].nValue,(long long)totalunits);
if ( ValidateSwapRemainder(remaining_price,tx.vout[0].nValue,assetoshis,tx.vout[1].nValue,tx.vout[2].nValue,totalunits) == false )
return eval->Invalid("mismatched remainder for fillex");
else if ( ConstrainVout(tx.vout[1],1,0,0) == 0 )
return eval->Invalid("normal vout1 for fillex");
else if ( remaining_price != 0 )
{
if ( ConstrainVout(tx.vout[0],1,(char *)cp->unspendableCCaddr,0) == 0 )
return eval->Invalid("mismatched vout0 AssetsCCaddr for fillex");
}
}
fprintf(stderr,"fill validated\n");
break;
}
return(PreventCC(eval,tx,preventCCvins,numvins,preventCCvouts,numvouts));
}

203
src/cc/auction.cpp

@ -0,0 +1,203 @@
/******************************************************************************
* Copyright © 2014-2018 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 "CCauction.h"
#include "../txmempool.h"
/*
*/
// start of consensus code
uint64_t IsAuctionvout(struct CCcontract_info *cp,const CTransaction& tx,int32_t v)
{
char destaddr[64];
if ( tx.vout[v].scriptPubKey.IsPayToCryptoCondition() != 0 )
{
if ( Getscriptaddress(destaddr,tx.vout[v].scriptPubKey) > 0 && strcmp(destaddr,cp->unspendableCCaddr) == 0 )
return(tx.vout[v].nValue);
}
return(0);
}
bool AuctionExactAmounts(struct CCcontract_info *cp,Eval* eval,const CTransaction &tx,int32_t minage,uint64_t txfee)
{
static uint256 zerohash;
CTransaction vinTx; uint256 hashBlock,activehash; int32_t i,numvins,numvouts; uint64_t inputs=0,outputs=0,assetoshis;
numvins = tx.vin.size();
numvouts = tx.vout.size();
for (i=0; i<numvins; i++)
{
//fprintf(stderr,"vini.%d\n",i);
if ( (*cp->ismyvin)(tx.vin[i].scriptSig) != 0 )
{
//fprintf(stderr,"vini.%d check mempool\n",i);
if ( eval->GetTxUnconfirmed(tx.vin[i].prevout.hash,vinTx,hashBlock) == 0 )
return eval->Invalid("cant find vinTx");
else
{
//fprintf(stderr,"vini.%d check hash and vout\n",i);
if ( hashBlock == zerohash )
return eval->Invalid("cant Auction from mempool");
if ( (assetoshis= IsAuctionvout(cp,vinTx,tx.vin[i].prevout.n)) != 0 )
inputs += assetoshis;
}
}
}
for (i=0; i<numvouts; i++)
{
//fprintf(stderr,"i.%d of numvouts.%d\n",i,numvouts);
if ( (assetoshis= IsAuctionvout(cp,tx,i)) != 0 )
outputs += assetoshis;
}
if ( inputs != outputs+COIN+txfee )
{
fprintf(stderr,"inputs %llu vs outputs %llu\n",(long long)inputs,(long long)outputs);
return eval->Invalid("mismatched inputs != outputs + COIN + txfee");
}
else return(true);
}
bool AuctionValidate(struct CCcontract_info *cp,Eval* eval,const CTransaction &tx)
{
int32_t numvins,numvouts,preventCCvins,preventCCvouts,i; bool retval;
numvins = tx.vin.size();
numvouts = tx.vout.size();
preventCCvins = preventCCvouts = -1;
if ( numvouts < 1 )
return eval->Invalid("no vouts");
else
{
//fprintf(stderr,"check vins\n");
for (i=0; i<numvins; i++)
{
if ( IsCCInput(tx.vin[0].scriptSig) == 0 )
{
fprintf(stderr,"Auctionget invalid vini\n");
return eval->Invalid("illegal normal vini");
}
}
//fprintf(stderr,"check amounts\n");
if ( AuctionExactAmounts(cp,eval,tx,1,10000) == false )
{
fprintf(stderr,"Auctionget invalid amount\n");
return false;
}
else
{
preventCCvouts = 1;
if ( IsAuctionvout(cp,tx,0) != 0 )
{
preventCCvouts++;
i = 1;
} else i = 0;
if ( tx.vout[i].nValue != COIN )
return eval->Invalid("invalid Auction output");
retval = PreventCC(eval,tx,preventCCvins,numvins,preventCCvouts,numvouts);
if ( retval != 0 )
fprintf(stderr,"Auctionget validated\n");
else fprintf(stderr,"Auctionget invalid\n");
return(retval);
}
}
}
// end of consensus code
// helper functions for rpc calls in rpcwallet.cpp
uint64_t AddAuctionInputs(struct CCcontract_info *cp,CMutableTransaction &mtx,CPubKey pk,uint64_t total,int32_t maxinputs)
{
char coinaddr[64]; uint64_t nValue,price,totalinputs = 0; uint256 txid,hashBlock; std::vector<uint8_t> origpubkey; CTransaction vintx; int32_t n = 0;
std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> > unspentOutputs;
GetCCaddress(cp,coinaddr,pk);
SetCCunspents(unspentOutputs,coinaddr);
for (std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++)
{
txid = it->first.txhash;
// prevent dup
if ( GetTransaction(txid,vintx,hashBlock,false) != 0 )
{
if ( (nValue= IsAuctionvout(cp,vintx,(int32_t)it->first.index)) > 0 )
{
if ( total != 0 && maxinputs != 0 )
mtx.vin.push_back(CTxIn(txid,(int32_t)it->first.index,CScript()));
nValue = it->second.satoshis;
totalinputs += nValue;
n++;
if ( (total > 0 && totalinputs >= total) || (maxinputs > 0 && n >= maxinputs) )
break;
}
}
}
return(totalinputs);
}
std::string AuctionBid(uint64_t txfee,uint256 itemhash,uint64_t amount)
{
CMutableTransaction mtx; CPubKey mypk,Auctionpk; CScript opret; uint64_t inputs,CCchange=0,nValue=COIN; struct CCcontract_info *cp,C;
cp = CCinit(&C,EVAL_AUCTION);
if ( txfee == 0 )
txfee = 10000;
Auctionpk = GetUnspendable(cp,0);
mypk = pubkey2pk(Mypubkey());
if ( (inputs= AddAuctionInputs(cp,mtx,Auctionpk,nValue+txfee,60)) > 0 )
{
if ( inputs > nValue )
CCchange = (inputs - nValue - txfee);
if ( CCchange != 0 )
mtx.vout.push_back(MakeCC1vout(EVAL_AUCTION,CCchange,Auctionpk));
mtx.vout.push_back(CTxOut(nValue,CScript() << ParseHex(HexStr(mypk)) << OP_CHECKSIG));
return(FinalizeCCTx(-1LL,cp,mtx,mypk,txfee,opret));
} else fprintf(stderr,"cant find Auction inputs\n");
return(0);
}
std::string AuctionDeliver(uint64_t txfee,uint256 itemhash,uint256 bidtxid)
{
CMutableTransaction mtx; CPubKey mypk,Auctionpk; CScript opret; uint64_t inputs,CCchange=0,nValue=COIN; struct CCcontract_info *cp,C;
cp = CCinit(&C,EVAL_AUCTION);
if ( txfee == 0 )
txfee = 10000;
Auctionpk = GetUnspendable(cp,0);
mypk = pubkey2pk(Mypubkey());
if ( (inputs= AddAuctionInputs(cp,mtx,Auctionpk,nValue+txfee,60)) > 0 )
{
if ( inputs > nValue )
CCchange = (inputs - nValue - txfee);
if ( CCchange != 0 )
mtx.vout.push_back(MakeCC1vout(EVAL_AUCTION,CCchange,Auctionpk));
mtx.vout.push_back(CTxOut(nValue,CScript() << ParseHex(HexStr(mypk)) << OP_CHECKSIG));
return(FinalizeCCTx(-1LL,cp,mtx,mypk,txfee,opret));
} else fprintf(stderr,"cant find Auction inputs\n");
return(0);
}
std::string AuctionPost(uint64_t txfee,uint256 itemhash,uint64_t minbid,char *title,char *description)
{
CMutableTransaction mtx; CPubKey mypk,Auctionpk; uint64_t funds = 0; CScript opret; struct CCcontract_info *cp,C;
cp = CCinit(&C,EVAL_AUCTION);
if ( txfee == 0 )
txfee = 10000;
mypk = pubkey2pk(Mypubkey());
Auctionpk = GetUnspendable(cp,0);
if ( AddNormalinputs(mtx,mypk,txfee,64) > 0 )
{
mtx.vout.push_back(MakeCC1vout(EVAL_AUCTION,funds,Auctionpk));
return(FinalizeCCTx(0,cp,mtx,mypk,txfee,opret));
}
return(0);
}

164
src/cc/betprotocol.cpp

@ -1,9 +1,28 @@
/******************************************************************************
* Copyright © 2014-2018 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 <cryptoconditions.h>
#include "hash.h"
#include "main.h"
#include "chain.h"
#include "streams.h"
#include "script/cc.h"
#include "cc/eval.h"
#include "cc/betprotocol.h"
#include "cc/eval.h"
#include "cc/utils.h"
#include "primitives/transaction.h"
@ -137,3 +156,146 @@ bool GetOpReturnHash(CScript script, uint256 &hash)
hash = uint256(vHash);
return true;
}
/*
* Crypto-Condition EVAL method that verifies a payout against a transaction
* notarised on another chain.
*
* IN: params - condition params
* IN: importTx - Payout transaction on value chain (KMD)
* IN: nIn - index of input of stake
*
* importTx: Spends stakeTx with payouts from asset chain
*
* in 0: Spends Stake TX and contains ImportPayout CC
* out 0: OP_RETURN MomProof, disputeTx
* out 1-: arbitrary payouts
*
* disputeTx: Spends sessionTx.0 (opener on asset chain)
*
* in 0: spends sessionTx.0
* in 1-: anything
* out 0: OP_RETURN hash of payouts
* out 1-: anything
*/
bool Eval::ImportPayout(const std::vector<uint8_t> params, const CTransaction &importTx, unsigned int nIn)
{
if (importTx.vout.size() == 0) return Invalid("no-vouts");
// load data from vout[0]
MoMProof proof;
CTransaction disputeTx;
{
std::vector<unsigned char> vopret;
GetOpReturnData(importTx.vout[0].scriptPubKey, vopret);
if (!E_UNMARSHAL(vopret, ss >> proof; ss >> disputeTx))
return Invalid("invalid-payload");
}
// Check disputeTx.0 shows correct payouts
{
uint256 givenPayoutsHash;
GetOpReturnHash(disputeTx.vout[0].scriptPubKey, givenPayoutsHash);
std::vector<CTxOut> payouts(importTx.vout.begin() + 1, importTx.vout.end());
if (givenPayoutsHash != SerializeHash(payouts))
return Invalid("wrong-payouts");
}
// Check disputeTx spends sessionTx.0
// condition ImportPayout params is session ID from other chain
{
uint256 sessionHash;
if (!E_UNMARSHAL(params, ss >> sessionHash))
return Invalid("malformed-params");
if (disputeTx.vin[0].prevout != COutPoint(sessionHash, 0))
return Invalid("wrong-session");
}
// Check disputeTx solves momproof from vout[0]
{
NotarisationData data(0);
if (!GetNotarisationData(proof.notarisationHash, data))
return Invalid("coudnt-load-mom");
if (data.MoM != proof.branch.Exec(disputeTx.GetHash()))
return Invalid("mom-check-fail");
}
return Valid();
}
/*
* Crypto-Condition EVAL method that resolves a dispute of a session
*
* IN: vm - AppVM virtual machine to verify states
* IN: params - condition params
* IN: disputeTx - transaction attempting to resolve dispute
* IN: nIn - index of input of dispute tx
*
* disputeTx: attempt to resolve a dispute
*
* in 0: Spends Session TX first output, reveals DisputeHeader
* out 0: OP_RETURN hash of payouts
*/
bool Eval::DisputePayout(AppVM &vm, std::vector<uint8_t> params, const CTransaction &disputeTx, unsigned int nIn)
{
if (disputeTx.vout.size() == 0) return Invalid("no-vouts");
// get payouts hash
uint256 payoutHash;
if (!GetOpReturnHash(disputeTx.vout[0].scriptPubKey, payoutHash))
return Invalid("invalid-payout-hash");
// load params
uint16_t waitBlocks;
std::vector<uint8_t> vmParams;
if (!E_UNMARSHAL(params, ss >> VARINT(waitBlocks); ss >> vmParams))
return Invalid("malformed-params");
// ensure that enough time has passed
{
CTransaction sessionTx;
CBlockIndex sessionBlock;
// if unconformed its too soon
if (!GetTxConfirmed(disputeTx.vin[0].prevout.hash, sessionTx, sessionBlock))
return Error("couldnt-get-parent");
if (GetCurrentHeight() < sessionBlock.nHeight + waitBlocks)
return Invalid("dispute-too-soon"); // Not yet
}
// get spends
std::vector<CTransaction> spends;
if (!GetSpendsConfirmed(disputeTx.vin[0].prevout.hash, spends))
return Error("couldnt-get-spends");
// verify result from VM
int maxLength = -1;
uint256 bestPayout;
for (int i=1; i<spends.size(); i++)
{
std::vector<unsigned char> vmState;
if (spends[i].vout.size() == 0) continue;
if (!GetOpReturnData(spends[i].vout[0].scriptPubKey, vmState)) continue;
auto out = vm.evaluate(vmParams, vmState);
uint256 resultHash = SerializeHash(out.second);
if (out.first > maxLength) {
maxLength = out.first;
bestPayout = resultHash;
}
// The below means that if for any reason there is a draw, the first dispute wins
else if (out.first == maxLength) {
if (bestPayout != payoutHash) {
fprintf(stderr, "WARNING: VM has multiple solutions of same length\n");
bestPayout = resultHash;
}
}
}
if (maxLength == -1) return Invalid("no-evidence");
return bestPayout == payoutHash ? Valid() : Invalid("wrong-payout");
}

27
src/cc/betprotocol.h

@ -1,9 +1,23 @@
/******************************************************************************
* Copyright © 2014-2018 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. *
* *
******************************************************************************/
#ifndef BETPROTOCOL_H
#define BETPROTOCOL_H
#include "cc/eval.h"
#include "pubkey.h"
#include "primitives/block.h"
#include "primitives/transaction.h"
#include "cryptoconditions/include/cryptoconditions.h"
@ -11,25 +25,18 @@
class MoMProof
{
public:
int nIndex;
std::vector<uint256> branch;
MerkleBranch branch;
uint256 notarisationHash;
MoMProof() {}
MoMProof(int i, std::vector<uint256> b, uint256 n) : notarisationHash(n), nIndex(i), branch(b) {}
uint256 Exec(uint256 hash) const { return CBlock::CheckMerkleBranch(hash, branch, nIndex); }
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
READWRITE(VARINT(nIndex));
READWRITE(branch);
READWRITE(notarisationHash);
}
};
class BetProtocol
{
protected:

512
src/cc/dice.cpp

@ -0,0 +1,512 @@
/******************************************************************************
* Copyright © 2014-2018 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 "CCdice.h"
/*
in order to implement a dice game, we need a source of entropy, reasonably fast completion time and a way to manage the utxos.
1. CC vout locks "house" funds with hash(entropy) + half of shared secret
2. bettor submits bet, with entropy, odds, houseid and sends combined amount into another CC vout.
3. house account sends funds to winner with proof of entropy
4. if timeout, bettor wins funds
2. and 3. can be done in mempool
*/
uint64_t DiceCalc(uint64_t amount,uint256 txid,int64_t minbet,int64_t maxbet,int64_t maxodds,int64_t forfeitblocks)
{
/*uint64_t duration,reward = 0;
if ( (duration= CCduration(txid)) < minseconds )
{
return(0);
//duration = (uint32_t)time(NULL) - (1532713903 - 3600 * 24);
} else if ( duration > maxseconds )
maxseconds = duration;
reward = (((amount * APR) / COIN) * duration) / (365*24*3600LL * 100);
fprintf(stderr,"amount %.8f %.8f %llu -> duration.%llu reward %.8f\n",(double)amount/COIN,((double)amount * APR)/COIN,(long long)((amount * APR) / (COIN * 365*24*3600)),(long long)duration,(double)reward/COIN);
return(reward);*/
return(0);
}
CScript EncodeDiceFundingOpRet(uint8_t funcid,uint64_t sbits,int64_t minbet,int64_t maxbet,int64_t maxodds,int64_t forfeitblocks)
{
CScript opret; uint8_t evalcode = EVAL_DICE;
opret << OP_RETURN << E_MARSHAL(ss << evalcode << 'F' << sbits << minbet << maxbet << maxodds << forfeitblocks);
return(opret);
}
uint8_t DecodeDiceFundingOpRet(const CScript &scriptPubKey,uint64_t &sbits,int64_t &minbet,int64_t &maxbet,int64_t &maxodds,int64_t &forfeitblocks)
{
std::vector<uint8_t> vopret; uint8_t *script,e,f;
GetOpReturnData(scriptPubKey, vopret);
script = (uint8_t *)vopret.data();
if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> sbits; ss >> minbet; ss >> maxbet; ss >> maxodds; ss >> forfeitblocks) != 0 )
{
if ( e == EVAL_DICE && f == 'F' )
return(f);
}
return(0);
}
CScript EncodeDiceOpRet(uint8_t funcid,uint64_t sbits,uint256 fundingtxid)
{
CScript opret; uint8_t evalcode = EVAL_DICE;
opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << sbits << fundingtxid);
return(opret);
}
uint8_t DecodeDiceOpRet(uint256 txid,const CScript &scriptPubKey,uint64_t &sbits,uint256 &fundingtxid)
{
std::vector<uint8_t> vopret; uint8_t *script,e,f,funcid; int64_t minbet,maxbet,maxodds,forfeitblocks;
GetOpReturnData(scriptPubKey, vopret);
if ( vopret.size() > 2 )
{
script = (uint8_t *)vopret.data();
if ( script[0] == EVAL_DICE )
{
if ( script[1] == 'F' )
{
if ( E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> sbits; ss >> minbet; ss >> maxbet; ss >> maxodds; ss >> forfeitblocks) != 0 )
{
fundingtxid = txid;
return('F');
} else fprintf(stderr,"unmarshal error for F\n");
}
else if ( E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> sbits; ss >> fundingtxid) != 0 )
{
if ( e == EVAL_DICE && (f == 'L' || f == 'U' || f == 'A') )
return(f);
else fprintf(stderr,"mismatched e.%02x f.(%c)\n",e,f);
}
} else fprintf(stderr,"script[0] %02x != EVAL_DICE\n",script[0]);
} else fprintf(stderr,"not enough opret.[%d]\n",(int32_t)vopret.size());
return(0);
}
uint64_t IsDicevout(struct CCcontract_info *cp,const CTransaction& tx,int32_t v)
{
char destaddr[64];
if ( tx.vout[v].scriptPubKey.IsPayToCryptoCondition() != 0 )
{
if ( Getscriptaddress(destaddr,tx.vout[v].scriptPubKey) > 0 && strcmp(destaddr,cp->unspendableCCaddr) == 0 )
return(tx.vout[v].nValue);
}
return(0);
}
bool DiceExactAmounts(struct CCcontract_info *cp,Eval *eval,const CTransaction &tx,uint64_t txfee)
{
static uint256 zerohash;
CTransaction vinTx; uint256 hashBlock; int32_t i,numvins,numvouts; uint64_t inputs=0,outputs=0,assetoshis;
numvins = tx.vin.size();
numvouts = tx.vout.size();
for (i=0; i<numvins; i++)
{
if ( (*cp->ismyvin)(tx.vin[i].scriptSig) != 0 )
{
if ( eval->GetTxUnconfirmed(tx.vin[i].prevout.hash,vinTx,hashBlock) == 0 )
return eval->Invalid("always should find vin, but didnt");
else
{
if ( hashBlock == zerohash )
return eval->Invalid("cant dice from mempool");
if ( (assetoshis= IsDicevout(cp,vinTx,tx.vin[i].prevout.n)) != 0 )
inputs += assetoshis;
}
}
}
for (i=0; i<numvouts; i++)
{
//fprintf(stderr,"i.%d of numvouts.%d\n",i,numvouts);
if ( (assetoshis= IsDicevout(cp,tx,i)) != 0 )
outputs += assetoshis;
}
if ( inputs != outputs+txfee )
{
fprintf(stderr,"inputs %llu vs outputs %llu\n",(long long)inputs,(long long)outputs);
return eval->Invalid("mismatched inputs != outputs + txfee");
}
else return(true);
}
bool DiceValidate(struct CCcontract_info *cp,Eval* eval,const CTransaction &tx)
{
uint256 txid,fundingtxid,hashBlock; int64_t minbet,maxbet,maxodds,forfeitblocks; uint64_t sbits,amount,reward,txfee=10000; int32_t numvins,numvouts,preventCCvins,preventCCvouts,i; uint8_t funcid; CScript scriptPubKey; CTransaction fundingTx,vinTx;
numvins = tx.vin.size();
numvouts = tx.vout.size();
preventCCvins = preventCCvouts = -1;
if ( numvouts < 1 )
return eval->Invalid("no vouts");
else
{
txid = tx.GetHash();
if ( (funcid= DecodeDiceOpRet(txid,tx.vout[numvouts-1].scriptPubKey,sbits,fundingtxid)) != 0 )
{
if ( eval->GetTxUnconfirmed(fundingtxid,fundingTx,hashBlock) == 0 )
return eval->Invalid("cant find fundingtxid");
else if ( fundingTx.vout.size() > 0 && DecodeDiceFundingOpRet(fundingTx.vout[fundingTx.vout.size()-1].scriptPubKey,sbits,minbet,maxbet,maxodds,forfeitblocks) != 'F' )
return eval->Invalid("fundingTx not valid");
switch ( funcid )
{
case 'F':
//vins.*: normal inputs
//vout.0: CC vout for funding
//vout.1: normal marker vout for easy searching
//vout.2: normal change
//vout.n-1: opreturn 'F' sbits APR minseconds maxseconds mindeposit
return eval->Invalid("unexpected DiceValidate for createfunding");
break;
case 'A':
//vins.*: normal inputs
//vout.0: CC vout for funding
//vout.1: normal change
//vout.n-1: opreturn 'A' sbits fundingtxid
return eval->Invalid("unexpected DiceValidate for addfunding");
break;
case 'L':
//vins.*: normal inputs
//vout.0: CC vout for locked funds
//vout.1: normal output to unlock address
//vout.2: change
//vout.n-1: opreturn 'L' sbits fundingtxid
return eval->Invalid("unexpected DiceValidate for lock");
break;
case 'U':
//vin.0: locked funds CC vout.0 from lock
//vin.1+: funding CC vout.0 from 'F' and 'A' and 'U'
//vout.0: funding CC change
//vout.1: normal output to unlock address
//vout.n-1: opreturn 'U' sbits fundingtxid
for (i=0; i<numvins; i++)
{
if ( (*cp->ismyvin)(tx.vin[i].scriptSig) == 0 )
return eval->Invalid("unexpected normal vin for unlock");
}
if ( DiceExactAmounts(cp,eval,tx,txfee+tx.vout[1].nValue) == 0 )
return false;
else if ( eval->GetTxUnconfirmed(tx.vin[0].prevout.hash,vinTx,hashBlock) == 0 )
return eval->Invalid("always should find vin.0, but didnt");
else if ( vinTx.vout[0].scriptPubKey.IsPayToCryptoCondition() == 0 )
return eval->Invalid("lock tx vout.0 is normal output");
else if ( tx.vout.size() < 3 )
return eval->Invalid("unlock tx not enough vouts");
else if ( tx.vout[0].scriptPubKey.IsPayToCryptoCondition() == 0 )
return eval->Invalid("unlock tx vout.0 is normal output");
else if ( tx.vout[1].scriptPubKey.IsPayToCryptoCondition() != 0 )
return eval->Invalid("unlock tx vout.1 is CC output");
else if ( tx.vout[1].scriptPubKey != vinTx.vout[1].scriptPubKey )
return eval->Invalid("unlock tx vout.1 mismatched scriptPubKey");
amount = vinTx.vout[0].nValue;
reward = DiceCalc(amount,tx.vin[0].prevout.hash,minbet,maxbet,maxodds,forfeitblocks);
if ( tx.vout[1].nValue > amount+reward )
return eval->Invalid("unlock tx vout.1 isnt amount+reward");
preventCCvouts = 1;
break;
}
}
return(PreventCC(eval,tx,preventCCvins,numvins,preventCCvouts,numvouts));
}
return(true);
}
// 'L' vs 'F' and 'A'
uint64_t AddDiceInputs(CScript &scriptPubKey,int32_t fundsflag,struct CCcontract_info *cp,CMutableTransaction &mtx,CPubKey pk,uint64_t total,int32_t maxinputs)
{
char coinaddr[64],str[65]; uint64_t sbits,nValue,totalinputs = 0; uint256 txid,hashBlock,fundingtxid; CTransaction tx; int32_t j,vout,n = 0; uint8_t funcid;
std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> > unspentOutputs;
GetCCaddress(cp,coinaddr,pk);
SetCCunspents(unspentOutputs,coinaddr);
for (std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++)
{
txid = it->first.txhash;
vout = (int32_t)it->first.index;
fprintf(stderr,"(%s) %s/v%d %.8f\n",coinaddr,uint256_str(str,txid),vout,(double)it->second.satoshis/COIN);
for (j=0; j<mtx.vin.size(); j++)
if ( txid == mtx.vin[j].prevout.hash && vout == mtx.vin[j].prevout.n )
break;
if ( j != mtx.vin.size() )
continue;
if ( GetTransaction(txid,tx,hashBlock,false) != 0 && tx.vout.size() > 0 && tx.vout[vout].scriptPubKey.IsPayToCryptoCondition() != 0 )
{
if ( (funcid= DecodeDiceOpRet(txid,tx.vout[tx.vout.size()-1].scriptPubKey,sbits,fundingtxid)) != 0 )
{
fprintf(stderr,"fundsflag.%d (%c) %.8f %.8f\n",fundsflag,funcid,(double)tx.vout[vout].nValue/COIN,(double)it->second.satoshis/COIN);
if ( fundsflag != 0 && funcid != 'F' && funcid != 'A' && funcid != 'U' )
continue;
else if ( fundsflag == 0 && (funcid != 'L' || tx.vout.size() < 4) )
continue;
if ( total != 0 && maxinputs != 0 )
{
if ( fundsflag == 0 )
scriptPubKey = tx.vout[1].scriptPubKey;
mtx.vin.push_back(CTxIn(txid,vout,CScript()));
}
totalinputs += it->second.satoshis;
n++;
if ( (total > 0 && totalinputs >= total) || (maxinputs > 0 && n >= maxinputs) )
break;
} else fprintf(stderr,"null funcid\n");
}
}
return(totalinputs);
}
uint64_t DicePlanFunds(uint64_t refsbits,struct CCcontract_info *cp,CPubKey pk,uint256 reffundingtxid)
{
char coinaddr[64]; uint64_t sbits,nValue,totalinputs = 0; uint256 txid,hashBlock,fundingtxid; CTransaction tx; int32_t vout; uint8_t funcid;
std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> > unspentOutputs;
GetCCaddress(cp,coinaddr,pk);
SetCCunspents(unspentOutputs,coinaddr);
for (std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++)
{
txid = it->first.txhash;
vout = (int32_t)it->first.index;
if ( GetTransaction(txid,tx,hashBlock,false) != 0 && tx.vout[vout].scriptPubKey.IsPayToCryptoCondition() != 0 )
{
if ( (funcid= DecodeDiceOpRet(txid,tx.vout[tx.vout.size()-1].scriptPubKey,sbits,fundingtxid)) != 0 )
{
if ( (funcid == 'F' && reffundingtxid == txid) || reffundingtxid == fundingtxid )
{
if ( refsbits == sbits && (nValue= IsDicevout(cp,tx,vout)) > 0 )
totalinputs += nValue;
else fprintf(stderr,"refsbits.%llx sbits.%llx nValue %.8f\n",(long long)refsbits,(long long)sbits,(double)nValue/COIN);
} //else fprintf(stderr,"else case\n");
} else fprintf(stderr,"funcid.%d %c skipped %.8f\n",funcid,funcid,(double)tx.vout[vout].nValue/COIN);
}
}
return(totalinputs);
}
bool DicePlanExists(struct CCcontract_info *cp,uint64_t refsbits,CPubKey dicepk,int64_t &minbet,int64_t &maxbet,int64_t &maxodds,int64_t &forfeitblocks)
{
char CCaddr[64]; uint64_t sbits; uint256 txid,hashBlock; CTransaction tx;
std::vector<std::pair<CAddressIndexKey, CAmount> > txids;
GetCCaddress(cp,CCaddr,dicepk);
SetCCtxids(txids,CCaddr);
for (std::vector<std::pair<CAddressIndexKey, CAmount> >::const_iterator it=txids.begin(); it!=txids.end(); it++)
{
//int height = it->first.blockHeight;
txid = it->first.txhash;
if ( GetTransaction(txid,tx,hashBlock,false) != 0 && tx.vout.size() > 0 && ConstrainVout(tx.vout[0],1,CCaddr,0) != 0 )
{
if ( DecodeDiceFundingOpRet(tx.vout[tx.vout.size()-1].scriptPubKey,sbits,minbet,maxbet,maxodds,forfeitblocks) == 'F' )
{
if ( sbits == refsbits )
return(true);
}
}
}
return(false);
}
UniValue DiceInfo(uint256 diceid)
{
UniValue result(UniValue::VOBJ); uint256 hashBlock; CTransaction vintx; int64_t minbet,maxbet,maxodds,forfeitblocks; uint64_t sbits; char str[67],numstr[65];
if ( GetTransaction(diceid,vintx,hashBlock,false) == 0 )
{
fprintf(stderr,"cant find fundingtxid\n");
result.push_back(Pair("error","cant find fundingtxid"));
return(result);
}
if ( vintx.vout.size() > 0 && DecodeDiceFundingOpRet(vintx.vout[vintx.vout.size()-1].scriptPubKey,sbits,minbet,maxbet,maxodds,forfeitblocks) == 0 )
{
fprintf(stderr,"fundingtxid isnt dice creation txid\n");
result.push_back(Pair("error","fundingtxid isnt dice creation txid"));
return(result);
}
result.push_back(Pair("result","success"));
result.push_back(Pair("fundingtxid",uint256_str(str,diceid)));
unstringbits(str,sbits);
result.push_back(Pair("name",str));
result.push_back(Pair("sbits",sbits));
sprintf(numstr,"%.8f",(double)minbet/COIN);
result.push_back(Pair("minbet",numstr));
sprintf(numstr,"%.8f",(double)maxbet/COIN);
result.push_back(Pair("maxbet",numstr));
result.push_back(Pair("maxodds",maxodds));
result.push_back(Pair("forfeitblocks",forfeitblocks));
sprintf(numstr,"%.8f",(double)vintx.vout[0].nValue/COIN);
result.push_back(Pair("funding",numstr));
return(result);
}
UniValue DiceList()
{
UniValue result(UniValue::VARR); std::vector<std::pair<CAddressIndexKey, CAmount> > addressIndex; struct CCcontract_info *cp,C; uint256 txid,hashBlock; CTransaction vintx; uint64_t sbits; int64_t minbet,maxbet,maxodds,forfeitblocks; char str[65];
cp = CCinit(&C,EVAL_DICE);
SetCCtxids(addressIndex,cp->normaladdr);
for (std::vector<std::pair<CAddressIndexKey, CAmount> >::const_iterator it=addressIndex.begin(); it!=addressIndex.end(); it++)
{
txid = it->first.txhash;
if ( GetTransaction(txid,vintx,hashBlock,false) != 0 )
{
if ( vintx.vout.size() > 0 && DecodeDiceFundingOpRet(vintx.vout[vintx.vout.size()-1].scriptPubKey,sbits,minbet,maxbet,maxodds,forfeitblocks) != 0 )
{
result.push_back(uint256_str(str,txid));
}
}
}
return(result);
}
std::string DiceCreateFunding(uint64_t txfee,char *planstr,int64_t funds,int64_t minbet,int64_t maxbet,int64_t maxodds,int64_t forfeitblocks)
{
CMutableTransaction mtx; CPubKey mypk,dicepk; CScript opret; uint64_t sbits; int64_t a,b,c,d; struct CCcontract_info *cp,C;
if ( funds < 0 || minbet < 0 || maxbet < 0 || maxodds < 1 || forfeitblocks < 0 || forfeitblocks > 1440 )
{
fprintf(stderr,"negative parameter error\n");
return(0);
}
cp = CCinit(&C,EVAL_DICE);
if ( txfee == 0 )
txfee = 10000;
mypk = pubkey2pk(Mypubkey());
dicepk = GetUnspendable(cp,0);
sbits = stringbits(planstr);
if ( DicePlanExists(cp,sbits,dicepk,a,b,c,d) != 0 )
{
fprintf(stderr,"Dice plan (%s) already exists\n",planstr);
return(0);
}
if ( AddNormalinputs(mtx,mypk,funds+2*txfee,64) > 0 )
{
mtx.vout.push_back(MakeCC1vout(cp->evalcode,funds,dicepk));
mtx.vout.push_back(CTxOut(txfee,CScript() << ParseHex(HexStr(dicepk)) << OP_CHECKSIG));
return(FinalizeCCTx(0,cp,mtx,mypk,txfee,EncodeDiceFundingOpRet('F',sbits,minbet,maxbet,maxodds,forfeitblocks)));
}
fprintf(stderr,"cant find enough inputs\n");
return(0);
}
std::string DiceAddfunding(uint64_t txfee,char *planstr,uint256 fundingtxid,int64_t amount)
{
CMutableTransaction mtx; CPubKey mypk,dicepk; CScript opret; uint64_t sbits; int64_t a,b,c,d; struct CCcontract_info *cp,C;
if ( amount < 0 )
{
fprintf(stderr,"negative parameter error\n");
return(0);
}
cp = CCinit(&C,EVAL_DICE);
if ( txfee == 0 )
txfee = 10000;
mypk = pubkey2pk(Mypubkey());
dicepk = GetUnspendable(cp,0);
sbits = stringbits(planstr);
if ( DicePlanExists(cp,sbits,dicepk,a,b,c,d) == 0 )
{
fprintf(stderr,"Dice plan %s doesnt exist\n",planstr);
return(0);
}
sbits = stringbits(planstr);
if ( AddNormalinputs(mtx,mypk,amount+txfee,64) > 0 )
{
mtx.vout.push_back(MakeCC1vout(cp->evalcode,amount,dicepk));
return(FinalizeCCTx(0,cp,mtx,mypk,txfee,EncodeDiceOpRet('A',sbits,fundingtxid)));
} else fprintf(stderr,"cant find enough inputs\n");
fprintf(stderr,"cant find fundingtxid\n");
return(0);
}
std::string DiceBet(uint64_t txfee,char *planstr,uint256 fundingtxid,int64_t bet,int32_t odds)
{
CMutableTransaction mtx; CPubKey mypk,dicepk; CScript opret; uint64_t sbits; int64_t funding,minbet,maxbet,maxodds,forfeitblocks; struct CCcontract_info *cp,C;
if ( bet < 0 || odds < 1 )
{
fprintf(stderr,"negative parameter error\n");
return(0);
}
cp = CCinit(&C,EVAL_DICE);
if ( txfee == 0 )
txfee = 10000;
mypk = pubkey2pk(Mypubkey());
dicepk = GetUnspendable(cp,0);
sbits = stringbits(planstr);
if ( DicePlanExists(cp,sbits,dicepk,minbet,maxbet,maxodds,forfeitblocks) == 0 )
{
fprintf(stderr,"Dice plan %s doesnt exist\n",planstr);
return(0);
}
if ( bet < minbet )
{
fprintf(stderr,"Dice plan %s bet %.8f < minbet %.8f\n",planstr,(double)bet/COIN,(double)minbet/COIN);
return(0);
}
if ( (funding= DicePlanFunds(sbits,cp,dicepk,fundingtxid)) >= bet*odds+txfee )
{
if ( AddNormalinputs(mtx,mypk,bet+2*txfee,64) > 0 )
{
mtx.vout.push_back(MakeCC1vout(cp->evalcode,bet,dicepk));
mtx.vout.push_back(CTxOut(txfee,CScript() << ParseHex(HexStr(mypk)) << OP_CHECKSIG));
return(FinalizeCCTx(0,cp,mtx,mypk,txfee,EncodeDiceOpRet('L',sbits,fundingtxid)));
} else fprintf(stderr,"cant find enough inputs %.8f note enough for %.8f\n",(double)funding/COIN,(double)bet/COIN);
}
fprintf(stderr,"cant find dice inputs\n");
return(0);
}
std::string DiceUnlock(uint64_t txfee,char *planstr,uint256 fundingtxid,uint256 locktxid)
{
CMutableTransaction mtx; CTransaction tx; char coinaddr[64]; CPubKey mypk,dicepk; CScript opret,scriptPubKey,ignore; uint256 hashBlock; uint64_t funding,sbits,reward=0,amount=0,inputs,CCchange=0; int64_t minbet,maxbet,maxodds,forfeitblocks; struct CCcontract_info *cp,C;
cp = CCinit(&C,EVAL_DICE);
if ( txfee == 0 )
txfee = 10000;
dicepk = GetUnspendable(cp,0);
mypk = pubkey2pk(Mypubkey());
sbits = stringbits(planstr);
if ( DicePlanExists(cp,sbits,dicepk,minbet,maxbet,maxodds,forfeitblocks) == 0 )
{
fprintf(stderr,"Dice plan %s doesnt exist\n",planstr);
return(0);
}
// need to deal with finding the right utxos
if ( locktxid == zeroid )
amount = AddDiceInputs(scriptPubKey,0,cp,mtx,dicepk,(1LL << 30),1);
else
{
GetCCaddress(cp,coinaddr,dicepk);
if ( (amount= CCutxovalue(coinaddr,locktxid,0)) == 0 )
{
fprintf(stderr,"%s locktxid/v0 is spent\n",coinaddr);
return(0);
}
if ( GetTransaction(locktxid,tx,hashBlock,false) != 0 && tx.vout.size() > 0 && tx.vout[1].scriptPubKey.IsPayToCryptoCondition() == 0 )
{
scriptPubKey = tx.vout[1].scriptPubKey;
mtx.vin.push_back(CTxIn(locktxid,0,CScript()));
}
else
{
fprintf(stderr,"%s no normal vout.1 in locktxid\n",coinaddr);
return(0);
}
}
if ( amount > 0 && (reward= DiceCalc(amount,mtx.vin[0].prevout.hash,minbet,maxbet,maxodds,forfeitblocks)) > txfee && scriptPubKey.size() > 0 )
{
if ( (inputs= AddDiceInputs(ignore,1,cp,mtx,dicepk,reward+txfee,30)) > 0 )
{
if ( inputs >= (reward + 2*txfee) )
CCchange = (inputs - (reward + txfee));
fprintf(stderr,"inputs %.8f CCchange %.8f amount %.8f reward %.8f\n",(double)inputs/COIN,(double)CCchange/COIN,(double)amount/COIN,(double)reward/COIN);
mtx.vout.push_back(MakeCC1vout(cp->evalcode,CCchange,dicepk));
mtx.vout.push_back(CTxOut(amount+reward,scriptPubKey));
return(FinalizeCCTx(-1LL,cp,mtx,mypk,txfee,EncodeDiceOpRet('U',sbits,fundingtxid)));
}
fprintf(stderr,"cant find enough dice inputs\n");
}
fprintf(stderr,"amount %.8f -> reward %.8f\n",(double)amount/COIN,(double)reward/COIN);
return(0);
}

84
src/cc/disputepayout.cpp

@ -1,84 +0,0 @@
#include <cryptoconditions.h>
#include "hash.h"
#include "chain.h"
#include "version.h"
#include "script/cc.h"
#include "cc/eval.h"
#include "cc/betprotocol.h"
#include "primitives/transaction.h"
/*
* Crypto-Condition EVAL method that resolves a dispute of a session
*
* IN: vm - AppVM virtual machine to verify states
* IN: params - condition params
* IN: disputeTx - transaction attempting to resolve dispute
* IN: nIn - index of input of dispute tx
*
* disputeTx: attempt to resolve a dispute
*
* in 0: Spends Session TX first output, reveals DisputeHeader
* out 0: OP_RETURN hash of payouts
*/
bool Eval::DisputePayout(AppVM &vm, std::vector<uint8_t> params, const CTransaction &disputeTx, unsigned int nIn)
{
if (disputeTx.vout.size() == 0) return Invalid("no-vouts");
// get payouts hash
uint256 payoutHash;
if (!GetOpReturnHash(disputeTx.vout[0].scriptPubKey, payoutHash))
return Invalid("invalid-payout-hash");
// load params
uint16_t waitBlocks;
std::vector<uint8_t> vmParams;
if (!E_UNMARSHAL(params, ss >> VARINT(waitBlocks); ss >> vmParams))
return Invalid("malformed-params");
// ensure that enough time has passed
{
CTransaction sessionTx;
CBlockIndex sessionBlock;
// if unconformed its too soon
if (!GetTxConfirmed(disputeTx.vin[0].prevout.hash, sessionTx, sessionBlock))
return Error("couldnt-get-parent");
if (GetCurrentHeight() < sessionBlock.nHeight + waitBlocks)
return Invalid("dispute-too-soon"); // Not yet
}
// get spends
std::vector<CTransaction> spends;
if (!GetSpendsConfirmed(disputeTx.vin[0].prevout.hash, spends))
return Error("couldnt-get-spends");
// verify result from VM
int maxLength = -1;
uint256 bestPayout;
for (int i=1; i<spends.size(); i++)
{
std::vector<unsigned char> vmState;
if (spends[i].vout.size() == 0) continue;
if (!GetOpReturnData(spends[i].vout[0].scriptPubKey, vmState)) continue;
auto out = vm.evaluate(vmParams, vmState);
uint256 resultHash = SerializeHash(out.second);
if (out.first > maxLength) {
maxLength = out.first;
bestPayout = resultHash;
}
// The below means that if for any reason there is a draw, the first dispute wins
else if (out.first == maxLength) {
if (bestPayout != payoutHash) {
fprintf(stderr, "WARNING: VM has multiple solutions of same length\n");
bestPayout = resultHash;
}
}
}
if (maxLength == -1) return Invalid("no-evidence");
return bestPayout == payoutHash ? Valid() : Invalid("wrong-payout");
}

149
src/cc/eval.cpp

@ -1,24 +1,44 @@
/******************************************************************************
* Copyright © 2014-2018 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 <assert.h>
#include <cryptoconditions.h>
#include "primitives/block.h"
#include "primitives/transaction.h"
#include "script/cc.h"
#include "cc/eval.h"
#include "cc/utils.h"
#include "cc/CCinclude.h"
#include "main.h"
#include "chain.h"
#include "core_io.h"
#include "crosschain.h"
Eval* EVAL_TEST = 0;
struct CCcontract_info CCinfos[0x100];
bool RunCCEval(const CC *cond, const CTransaction &tx, unsigned int nIn)
{
Eval eval_;
Eval *eval = EVAL_TEST;
if (!eval) eval = &eval_;
// DISABLE CRYPTO CONDITIONS FOR NOW
return false;
EvalRef eval;
bool out = eval->Dispatch(cond, tx, nIn);
//fprintf(stderr,"out %d vs %d isValid\n",(int32_t)out,(int32_t)eval->state.IsValid());
assert(eval->state.IsValid() == out);
if (eval->state.IsValid()) return true;
@ -39,17 +59,33 @@ bool RunCCEval(const CC *cond, const CTransaction &tx, unsigned int nIn)
*/
bool Eval::Dispatch(const CC *cond, const CTransaction &txTo, unsigned int nIn)
{
struct CCcontract_info *cp;
if (cond->codeLength == 0)
return Invalid("empty-eval");
uint8_t ecode = cond->code[0];
cp = &CCinfos[(int32_t)ecode];
if ( cp->didinit == 0 )
{
CCinit(cp,ecode);
cp->didinit = 1;
}
std::vector<uint8_t> vparams(cond->code+1, cond->code+cond->codeLength);
if (ecode == EVAL_IMPORTPAYOUT) {
return ImportPayout(vparams, txTo, nIn);
switch ( ecode )
{
case EVAL_IMPORTPAYOUT:
return ImportPayout(vparams, txTo, nIn);
break;
case EVAL_IMPORTCOIN:
return ImportCoin(vparams, txTo, nIn);
break;
default:
return(ProcessCC(cp,this, vparams, txTo, nIn));
break;
}
return Invalid("invalid-code");
return Invalid("invalid-code, dont forget to add EVAL_NEWCC to Eval::Dispatch");
}
@ -62,8 +98,11 @@ bool Eval::GetSpendsConfirmed(uint256 hash, std::vector<CTransaction> &spends) c
bool Eval::GetTxUnconfirmed(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock) const
{
bool fAllowSlow = false; // Don't allow slow
return GetTransaction(hash, txOut, hashBlock, fAllowSlow);
bool myGetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock);
// there is a LOCK(cs_main) in the normal GetTransaction(), which leads to deadlocks
//bool fAllowSlow = false; // Don't allow slow
//return GetTransaction(hash, txOut, hashBlock, fAllowSlow);
return myGetTransaction(hash, txOut,hashBlock);
}
@ -83,7 +122,6 @@ unsigned int Eval::GetCurrentHeight() const
return chainActive.Height();
}
bool Eval::GetBlock(uint256 hash, CBlockIndex& blockIdx) const
{
auto r = mapBlockIndex.find(hash);
@ -95,7 +133,6 @@ bool Eval::GetBlock(uint256 hash, CBlockIndex& blockIdx) const
return false;
}
extern int32_t komodo_notaries(uint8_t pubkeys[64][33],int32_t height,uint32_t timestamp);
@ -144,7 +181,7 @@ bool Eval::CheckNotaryInputs(const CTransaction &tx, uint32_t height, uint32_t t
/*
* Get MoM from a notarisation tx hash
* Get MoM from a notarisation tx hash (on KMD)
*/
bool Eval::GetNotarisationData(const uint256 notaryHash, NotarisationData &data) const
{
@ -152,54 +189,84 @@ bool Eval::GetNotarisationData(const uint256 notaryHash, NotarisationData &data)
CBlockIndex block;
if (!GetTxConfirmed(notaryHash, notarisationTx, block)) return false;
if (!CheckNotaryInputs(notarisationTx, block.nHeight, block.nTime)) return false;
if (notarisationTx.vout.size() < 2) return false;
if (!data.Parse(notarisationTx.vout[1].scriptPubKey)) return false;
if (!ParseNotarisationOpReturn(notarisationTx, data)) return false;
return true;
}
/*
* Notarisation data, ie, OP_RETURN payload in notarisation transactions
* Get MoMoM corresponding to a notarisation tx hash (on assetchain)
*/
extern char ASSETCHAINS_SYMBOL[16];
bool NotarisationData::Parse(const CScript scriptPK)
bool Eval::GetProofRoot(uint256 kmdNotarisationHash, uint256 &momom) const
{
*this = NotarisationData();
std::pair<uint256,NotarisationData> out;
if (!GetNextBacknotarisation(kmdNotarisationHash, out)) return false;
momom = out.second.MoMoM;
return true;
}
std::vector<unsigned char> vdata;
if (!GetOpReturnData(scriptPK, vdata)) return false;
CDataStream ss(vdata, SER_NETWORK, PROTOCOL_VERSION);
uint32_t Eval::GetAssetchainsCC() const
{
return ASSETCHAINS_CC;
}
try {
ss >> blockHash;
ss >> height;
if (ASSETCHAINS_SYMBOL[0])
ss >> txHash;
char *nullPos = (char*) memchr(&ss[0], 0, ss.size());
if (!nullPos) return false;
ss.read(symbol, nullPos-&ss[0]+1);
std::string Eval::GetAssetchainsSymbol() const
{
return std::string(ASSETCHAINS_SYMBOL);
}
if (ss.size() < 36) return false;
ss >> MoM;
ss >> MoMDepth;
} catch (...) {
return false;
}
return true;
/*
* Notarisation data, ie, OP_RETURN payload in notarisation transactions
*/
bool ParseNotarisationOpReturn(const CTransaction &tx, NotarisationData &data)
{
if (tx.vout.size() < 2) return false;
std::vector<unsigned char> vdata;
if (!GetOpReturnData(tx.vout[1].scriptPubKey, vdata)) return false;
bool out = E_UNMARSHAL(vdata, ss >> data);
return out;
}
/*
* Misc
*/
std::string EvalToStr(EvalCode c)
{
FOREACH_EVAL(EVAL_GENERATE_STRING);
char s[10];
sprintf(s, "0x%x", c);
return std::string(s);
}
uint256 SafeCheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
{
if (nIndex == -1)
return uint256();
for (auto it(vMerkleBranch.begin()); it != vMerkleBranch.end(); ++it)
{
if (nIndex & 1) {
if (*it == hash) {
// non canonical. hash may be equal to node but never on the right.
return uint256();
}
hash = Hash(BEGIN(*it), END(*it), BEGIN(hash), END(hash));
}
else
hash = Hash(BEGIN(hash), END(hash), BEGIN(*it), END(*it));
nIndex >>= 1;
}
return hash;
}
uint256 GetMerkleRoot(const std::vector<uint256>& vLeaves)
{
bool fMutated;
std::vector<uint256> vMerkleTree;
return BuildMerkleTree(&fMutated, vLeaves, vMerkleTree);
}

197
src/cc/eval.h

@ -1,14 +1,31 @@
/******************************************************************************
* Copyright © 2014-2018 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. *
* *
******************************************************************************/
#ifndef CC_EVAL_H
#define CC_EVAL_H
#include <cryptoconditions.h>
#include "cc/utils.h"
#include "chain.h"
#include "streams.h"
#include "version.h"
#include "consensus/validation.h"
#include "primitives/transaction.h"
#define KOMODO_FIRSTFUNGIBLEID 100
/*
* Eval codes
@ -20,8 +37,17 @@
* a possible code is EVAL_BITCOIN_SCRIPT, where the entire binary
* after the code is interpreted as a bitcoin script.
*/
#define FOREACH_EVAL(EVAL) \
EVAL(EVAL_IMPORTPAYOUT, 0xe1)
#define FOREACH_EVAL(EVAL) \
EVAL(EVAL_IMPORTPAYOUT, 0xe1) \
EVAL(EVAL_IMPORTCOIN, 0xe2) \
EVAL(EVAL_ASSETS, 0xe3) \
EVAL(EVAL_FAUCET, 0xe4) \
EVAL(EVAL_REWARDS, 0xe5) \
EVAL(EVAL_DICE, 0xe6) \
EVAL(EVAL_PONZI, 0xe7) \
EVAL(EVAL_AUCTION, 0xe8) \
EVAL(EVAL_LOTTO, 0xe9)
typedef uint8_t EvalCode;
@ -54,6 +80,11 @@ public:
*/
bool ImportPayout(std::vector<uint8_t> params, const CTransaction &importTx, unsigned int nIn);
/*
* Import coin from another chain with same symbol
*/
bool ImportCoin(std::vector<uint8_t> params, const CTransaction &importTx, unsigned int nIn);
/*
* IO functions
*/
@ -64,10 +95,30 @@ public:
virtual bool GetBlock(uint256 hash, CBlockIndex& blockIdx) const;
virtual int32_t GetNotaries(uint8_t pubkeys[64][33], int32_t height, uint32_t timestamp) const;
virtual bool GetNotarisationData(uint256 notarisationHash, NotarisationData &data) const;
virtual bool GetProofRoot(uint256 kmdNotarisationHash, uint256 &momom) const;
virtual bool CheckNotaryInputs(const CTransaction &tx, uint32_t height, uint32_t timestamp) const;
virtual uint32_t GetAssetchainsCC() const;
virtual std::string GetAssetchainsSymbol() const;
};
extern Eval* EVAL_TEST;
/*
* Get a pointer to an Eval to use
*/
typedef std::unique_ptr<Eval,void(*)(Eval*)> EvalRef_;
class EvalRef : public EvalRef_
{
public:
EvalRef() : EvalRef_(
EVAL_TEST ? EVAL_TEST : new Eval(),
[](Eval* e){if (e!=EVAL_TEST) delete e;}) { }
};
bool RunCCEval(const CC *cond, const CTransaction &tx, unsigned int nIn);
@ -88,22 +139,92 @@ public:
};
extern char ASSETCHAINS_SYMBOL[65];
/*
* Data from notarisation OP_RETURN
* Data from notarisation OP_RETURN from chain being notarised
*/
class NotarisationData {
class NotarisationData
{
public:
uint256 blockHash;
uint32_t height;
uint256 txHash; // Only get this guy in asset chains not in KMD
int IsBackNotarisation = 0;
uint256 blockHash = uint256();
uint32_t height = 0;
uint256 txHash = uint256();
char symbol[64];
uint256 MoM;
uint32_t MoMDepth;
uint256 MoM = uint256();
uint16_t MoMDepth = 0;
uint16_t ccId = 0;
uint256 MoMoM = uint256();
uint32_t MoMoMDepth = 0;
NotarisationData(int IsBack=2) : IsBackNotarisation(IsBack) {
symbol[0] = '\0';
}
bool Parse(CScript scriptPubKey);
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
bool IsBack = IsBackNotarisation;
if (2 == IsBackNotarisation) IsBack = DetectBackNotarisation(s, ser_action);
READWRITE(blockHash);
READWRITE(height);
if (IsBack)
READWRITE(txHash);
SerSymbol(s, ser_action);
if (s.size() == 0) return;
READWRITE(MoM);
READWRITE(MoMDepth);
READWRITE(ccId);
if (s.size() == 0) return;
if (IsBack) {
READWRITE(MoMoM);
READWRITE(MoMoMDepth);
}
}
template <typename Stream>
void SerSymbol(Stream& s, CSerActionSerialize act)
{
s.write(symbol, strlen(symbol)+1);
}
template <typename Stream>
void SerSymbol(Stream& s, CSerActionUnserialize act)
{
size_t readlen = std::min(sizeof(symbol), s.size());
char *nullPos = (char*) memchr(&s[0], 0, readlen);
if (!nullPos)
throw std::ios_base::failure("couldn't parse symbol");
s.read(symbol, nullPos-&s[0]+1);
}
template <typename Stream>
bool DetectBackNotarisation(Stream& s, CSerActionUnserialize act)
{
if (ASSETCHAINS_SYMBOL[0]) return 1;
if (s.size() >= 72) {
if (strcmp("BTC", &s[68]) == 0) return 1;
if (strcmp("KMD", &s[68]) == 0) return 1;
}
return 0;
}
template <typename Stream>
bool DetectBackNotarisation(Stream& s, CSerActionSerialize act)
{
return !txHash.IsNull();
}
};
bool ParseNotarisationOpReturn(const CTransaction &tx, NotarisationData &data);
/*
* Eval code utilities.
*/
@ -116,28 +237,44 @@ std::string EvalToStr(EvalCode c);
/*
* Serialisation boilerplate
* Merkle stuff
*/
#define E_MARSHAL(body) SerializeF([&] (CDataStream &ss) {body;})
template <class T>
std::vector<uint8_t> SerializeF(const T f)
{
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
f(ss);
return std::vector<unsigned char>(ss.begin(), ss.end());
}
#define E_UNMARSHAL(params, body) DeserializeF(params, [&] (CDataStream &ss) {body;})
template <class T>
bool DeserializeF(const std::vector<unsigned char> vIn, T f)
uint256 SafeCheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex);
class MerkleBranch
{
CDataStream ss(vIn, SER_NETWORK, PROTOCOL_VERSION);
try {
f(ss);
if (ss.eof()) return true;
} catch(...) {}
return false;
}
public:
int nIndex;
std::vector<uint256> branch;
MerkleBranch() {}
MerkleBranch(int i, std::vector<uint256> b) : nIndex(i), branch(b) {}
uint256 Exec(uint256 hash) const { return SafeCheckMerkleBranch(hash, branch, nIndex); }
MerkleBranch& operator<<(MerkleBranch append)
{
nIndex += append.nIndex << branch.size();
branch.insert(branch.end(), append.branch.begin(), append.branch.end());
return *this;
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
READWRITE(VARINT(nIndex));
READWRITE(branch);
}
};
typedef std::pair<uint256,MerkleBranch> TxProof;
uint256 GetMerkleRoot(const std::vector<uint256>& vLeaves);
struct CCcontract_info *CCinit(struct CCcontract_info *cp,uint8_t evalcode);
bool ProcessCC(struct CCcontract_info *cp,Eval* eval, std::vector<uint8_t> paramsNull, const CTransaction &tx, unsigned int nIn);
#endif /* CC_EVAL_H */

190
src/cc/faucet.cpp

@ -0,0 +1,190 @@
/******************************************************************************
* Copyright © 2014-2018 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 "CCfaucet.h"
#include "../txmempool.h"
/*
This file implements a simple CC faucet as an example of how to make a new CC contract. It wont have any fancy sybil protection but will serve the purpose of a fully automated faucet.
In order to implement a faucet, we need to have it funded. Once it is funded, anybody should be able to get some reasonable small amount.
This leads to needing to lock the funding in a CC protected output. And to put a spending limit. We can do a per transaction spending limit quite easily with vout constraints. However, that would allow anybody to issue thousands of transactions per block, so we also need to add a rate limiter.
To implement this, we can simply make any faucet vout fund the faucet. Then we can limit the number of confirmed utxo by combining faucet outputs and then only using utxo which are confirmed. This combined with a vout size limit will drastically limit the funds that can be withdrawn from the faucet.
*/
// start of consensus code
uint64_t IsFaucetvout(struct CCcontract_info *cp,const CTransaction& tx,int32_t v)
{
char destaddr[64];
if ( tx.vout[v].scriptPubKey.IsPayToCryptoCondition() != 0 )
{
if ( Getscriptaddress(destaddr,tx.vout[v].scriptPubKey) > 0 && strcmp(destaddr,cp->unspendableCCaddr) == 0 )
return(tx.vout[v].nValue);
}
return(0);
}
bool FaucetExactAmounts(struct CCcontract_info *cp,Eval* eval,const CTransaction &tx,int32_t minage,uint64_t txfee)
{
static uint256 zerohash;
CTransaction vinTx; uint256 hashBlock,activehash; int32_t i,numvins,numvouts; uint64_t inputs=0,outputs=0,assetoshis;
numvins = tx.vin.size();
numvouts = tx.vout.size();
for (i=0; i<numvins; i++)
{
//fprintf(stderr,"vini.%d\n",i);
if ( (*cp->ismyvin)(tx.vin[i].scriptSig) != 0 )
{
//fprintf(stderr,"vini.%d check mempool\n",i);
if ( eval->GetTxUnconfirmed(tx.vin[i].prevout.hash,vinTx,hashBlock) == 0 )
return eval->Invalid("cant find vinTx");
else
{
//fprintf(stderr,"vini.%d check hash and vout\n",i);
if ( hashBlock == zerohash )
return eval->Invalid("cant faucet from mempool");
if ( (assetoshis= IsFaucetvout(cp,vinTx,tx.vin[i].prevout.n)) != 0 )
inputs += assetoshis;
}
}
}
for (i=0; i<numvouts; i++)
{
//fprintf(stderr,"i.%d of numvouts.%d\n",i,numvouts);
if ( (assetoshis= IsFaucetvout(cp,tx,i)) != 0 )
outputs += assetoshis;
}
if ( inputs != outputs+COIN+txfee )
{
fprintf(stderr,"inputs %llu vs outputs %llu\n",(long long)inputs,(long long)outputs);
return eval->Invalid("mismatched inputs != outputs + COIN + txfee");
}
else return(true);
}
bool FaucetValidate(struct CCcontract_info *cp,Eval* eval,const CTransaction &tx)
{
int32_t numvins,numvouts,preventCCvins,preventCCvouts,i; bool retval;
numvins = tx.vin.size();
numvouts = tx.vout.size();
preventCCvins = preventCCvouts = -1;
if ( numvouts < 1 )
return eval->Invalid("no vouts");
else
{
//fprintf(stderr,"check vins\n");
for (i=0; i<numvins; i++)
{
if ( IsCCInput(tx.vin[0].scriptSig) == 0 )
{
fprintf(stderr,"faucetget invalid vini\n");
return eval->Invalid("illegal normal vini");
}
}
//fprintf(stderr,"check amounts\n");
if ( FaucetExactAmounts(cp,eval,tx,1,10000) == false )
{
fprintf(stderr,"faucetget invalid amount\n");
return false;
}
else
{
preventCCvouts = 1;
if ( IsFaucetvout(cp,tx,0) != 0 )
{
preventCCvouts++;
i = 1;
} else i = 0;
if ( tx.vout[i].nValue != COIN )
return eval->Invalid("invalid faucet output");
retval = PreventCC(eval,tx,preventCCvins,numvins,preventCCvouts,numvouts);
if ( retval != 0 )
fprintf(stderr,"faucetget validated\n");
else fprintf(stderr,"faucetget invalid\n");
return(retval);
}
}
}
// end of consensus code
// helper functions for rpc calls in rpcwallet.cpp
uint64_t AddFaucetInputs(struct CCcontract_info *cp,CMutableTransaction &mtx,CPubKey pk,uint64_t total,int32_t maxinputs)
{
char coinaddr[64]; uint64_t nValue,price,totalinputs = 0; uint256 txid,hashBlock; std::vector<uint8_t> origpubkey; CTransaction vintx; int32_t n = 0;
std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> > unspentOutputs;
GetCCaddress(cp,coinaddr,pk);
SetCCunspents(unspentOutputs,coinaddr);
for (std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++)
{
txid = it->first.txhash;
// prevent dup
if ( GetTransaction(txid,vintx,hashBlock,false) != 0 )
{
if ( (nValue= IsFaucetvout(cp,vintx,(int32_t)it->first.index)) > 0 )
{
if ( total != 0 && maxinputs != 0 )
mtx.vin.push_back(CTxIn(txid,(int32_t)it->first.index,CScript()));
nValue = it->second.satoshis;
totalinputs += nValue;
n++;
if ( (total > 0 && totalinputs >= total) || (maxinputs > 0 && n >= maxinputs) )
break;
}
}
}
return(totalinputs);
}
std::string FaucetGet(uint64_t txfee)
{
CMutableTransaction mtx; CPubKey mypk,faucetpk; CScript opret; uint64_t inputs,CCchange=0,nValue=COIN; struct CCcontract_info *cp,C;
cp = CCinit(&C,EVAL_FAUCET);
if ( txfee == 0 )
txfee = 10000;
faucetpk = GetUnspendable(cp,0);
mypk = pubkey2pk(Mypubkey());
if ( (inputs= AddFaucetInputs(cp,mtx,faucetpk,nValue+txfee,60)) > 0 )
{
if ( inputs > nValue )
CCchange = (inputs - nValue - txfee);
if ( CCchange != 0 )
mtx.vout.push_back(MakeCC1vout(EVAL_FAUCET,CCchange,faucetpk));
mtx.vout.push_back(CTxOut(nValue,CScript() << ParseHex(HexStr(mypk)) << OP_CHECKSIG));
return(FinalizeCCTx(-1LL,cp,mtx,mypk,txfee,opret));
} else fprintf(stderr,"cant find faucet inputs\n");
return(0);
}
std::string FaucetFund(uint64_t txfee,uint64_t funds)
{
CMutableTransaction mtx; CPubKey mypk,faucetpk; CScript opret; struct CCcontract_info *cp,C;
cp = CCinit(&C,EVAL_FAUCET);
if ( txfee == 0 )
txfee = 10000;
mypk = pubkey2pk(Mypubkey());
faucetpk = GetUnspendable(cp,0);
if ( AddNormalinputs(mtx,mypk,funds+txfee,64) > 0 )
{
mtx.vout.push_back(MakeCC1vout(EVAL_FAUCET,funds,faucetpk));
return(FinalizeCCTx(0,cp,mtx,mypk,txfee,opret));
}
return(0);
}

90
src/cc/import.cpp

@ -0,0 +1,90 @@
/******************************************************************************
* Copyright © 2014-2018 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 "cc/eval.h"
#include "cc/utils.h"
#include "importcoin.h"
#include "primitives/transaction.h"
/*
* CC Eval method for import coin.
*
* This method should control every parameter of the ImportCoin transaction, since it has no signature
* to protect it from malleability.
*/
bool Eval::ImportCoin(const std::vector<uint8_t> params, const CTransaction &importTx, unsigned int nIn)
{
if (importTx.vout.size() < 2)
return Invalid("too-few-vouts");
// params
TxProof proof;
CTransaction burnTx;
std::vector<CTxOut> payouts;
if (!UnmarshalImportTx(importTx, proof, burnTx, payouts))
return Invalid("invalid-params");
// Control all aspects of this transaction
// It should not be at all malleable
if (MakeImportCoinTransaction(proof, burnTx, payouts).GetHash() != importTx.GetHash())
return Invalid("non-canonical");
// burn params
uint32_t targetCcid;
std::string targetSymbol;
uint256 payoutsHash;
if (!UnmarshalBurnTx(burnTx, targetSymbol, &targetCcid, payoutsHash))
return Invalid("invalid-burn-tx");
if (targetCcid != GetAssetchainsCC() || targetSymbol != GetAssetchainsSymbol())
return Invalid("importcoin-wrong-chain");
if (targetCcid < KOMODO_FIRSTFUNGIBLEID)
return Invalid("chain-not-fungible");
// check burn amount
{
uint64_t burnAmount = burnTx.vout[0].nValue;
if (burnAmount == 0)
return Invalid("invalid-burn-amount");
uint64_t totalOut = 0;
for (int i=0; i<importTx.vout.size(); i++)
totalOut += importTx.vout[i].nValue;
if (totalOut > burnAmount)
return Invalid("payout-too-high");
}
// Check burntx shows correct outputs hash
if (payoutsHash != SerializeHash(payouts))
return Invalid("wrong-payouts");
// Check proof confirms existance of burnTx
{
uint256 momom, target;
if (!GetProofRoot(proof.first, momom))
return Invalid("coudnt-load-momom");
target = proof.second.Exec(burnTx.GetHash());
if (momom != proof.second.Exec(burnTx.GetHash()))
return Invalid("momom-check-fail");
}
return Valid();
}

76
src/cc/importpayout.cpp

@ -1,76 +0,0 @@
#include <cryptoconditions.h>
#include "main.h"
#include "chain.h"
#include "streams.h"
#include "cc/eval.h"
#include "cc/betprotocol.h"
#include "primitives/transaction.h"
/*
* Crypto-Condition EVAL method that verifies a payout against a transaction
* notarised on another chain.
*
* IN: params - condition params
* IN: importTx - Payout transaction on value chain (KMD)
* IN: nIn - index of input of stake
*
* importTx: Spends stakeTx with payouts from asset chain
*
* in 0: Spends Stake TX and contains ImportPayout CC
* out 0: OP_RETURN MomProof, disputeTx
* out 1-: arbitrary payouts
*
* disputeTx: Spends sessionTx.0 (opener on asset chain)
*
* in 0: spends sessionTx.0
* in 1-: anything
* out 0: OP_RETURN hash of payouts
* out 1-: anything
*/
bool Eval::ImportPayout(const std::vector<uint8_t> params, const CTransaction &importTx, unsigned int nIn)
{
if (importTx.vout.size() == 0) return Invalid("no-vouts");
// load data from vout[0]
MoMProof proof;
CTransaction disputeTx;
{
std::vector<unsigned char> vopret;
GetOpReturnData(importTx.vout[0].scriptPubKey, vopret);
if (!E_UNMARSHAL(vopret, ss >> proof; ss >> disputeTx))
return Invalid("invalid-payload");
}
// Check disputeTx.0 shows correct payouts
{
uint256 givenPayoutsHash;
GetOpReturnHash(disputeTx.vout[0].scriptPubKey, givenPayoutsHash);
std::vector<CTxOut> payouts(importTx.vout.begin() + 1, importTx.vout.end());
if (givenPayoutsHash != SerializeHash(payouts))
return Invalid("wrong-payouts");
}
// Check disputeTx spends sessionTx.0
// condition ImportPayout params is session ID from other chain
{
uint256 sessionHash;
if (!E_UNMARSHAL(params, ss >> sessionHash))
return Invalid("malformed-params");
if (disputeTx.vin[0].prevout != COutPoint(sessionHash, 0))
return Invalid("wrong-session");
}
// Check disputeTx solves momproof from vout[0]
{
NotarisationData data;
if (!GetNotarisationData(proof.notarisationHash, data))
return Invalid("coudnt-load-mom");
if (data.MoM != proof.Exec(disputeTx.GetHash()))
return Invalid("mom-check-fail");
}
return Valid();
}

183
src/cc/lotto.cpp

@ -0,0 +1,183 @@
/******************************************************************************
* Copyright © 2014-2018 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 "CClotto.h"
#include "../txmempool.h"
/*
*/
// start of consensus code
uint64_t IsLottovout(struct CCcontract_info *cp,const CTransaction& tx,int32_t v)
{
char destaddr[64];
if ( tx.vout[v].scriptPubKey.IsPayToCryptoCondition() != 0 )
{
if ( Getscriptaddress(destaddr,tx.vout[v].scriptPubKey) > 0 && strcmp(destaddr,cp->unspendableCCaddr) == 0 )
return(tx.vout[v].nValue);
}
return(0);
}
bool LottoExactAmounts(struct CCcontract_info *cp,Eval* eval,const CTransaction &tx,int32_t minage,uint64_t txfee)
{
static uint256 zerohash;
CTransaction vinTx; uint256 hashBlock,activehash; int32_t i,numvins,numvouts; uint64_t inputs=0,outputs=0,assetoshis;
numvins = tx.vin.size();
numvouts = tx.vout.size();
for (i=0; i<numvins; i++)
{
//fprintf(stderr,"vini.%d\n",i);
if ( (*cp->ismyvin)(tx.vin[i].scriptSig) != 0 )
{
//fprintf(stderr,"vini.%d check mempool\n",i);
if ( eval->GetTxUnconfirmed(tx.vin[i].prevout.hash,vinTx,hashBlock) == 0 )
return eval->Invalid("cant find vinTx");
else
{
//fprintf(stderr,"vini.%d check hash and vout\n",i);
if ( hashBlock == zerohash )
return eval->Invalid("cant Lotto from mempool");
if ( (assetoshis= IsLottovout(cp,vinTx,tx.vin[i].prevout.n)) != 0 )
inputs += assetoshis;
}
}
}
for (i=0; i<numvouts; i++)
{
//fprintf(stderr,"i.%d of numvouts.%d\n",i,numvouts);
if ( (assetoshis= IsLottovout(cp,tx,i)) != 0 )
outputs += assetoshis;
}
if ( inputs != outputs+COIN+txfee )
{
fprintf(stderr,"inputs %llu vs outputs %llu\n",(long long)inputs,(long long)outputs);
return eval->Invalid("mismatched inputs != outputs + COIN + txfee");
}
else return(true);
}
bool LottoValidate(struct CCcontract_info *cp,Eval* eval,const CTransaction &tx)
{
int32_t numvins,numvouts,preventCCvins,preventCCvouts,i; bool retval;
numvins = tx.vin.size();
numvouts = tx.vout.size();
preventCCvins = preventCCvouts = -1;
if ( numvouts < 1 )
return eval->Invalid("no vouts");
else
{
//fprintf(stderr,"check vins\n");
for (i=0; i<numvins; i++)
{
if ( IsCCInput(tx.vin[0].scriptSig) == 0 )
{
fprintf(stderr,"Lottoget invalid vini\n");
return eval->Invalid("illegal normal vini");
}
}
//fprintf(stderr,"check amounts\n");
if ( LottoExactAmounts(cp,eval,tx,1,10000) == false )
{
fprintf(stderr,"Lottoget invalid amount\n");
return false;
}
else
{
preventCCvouts = 1;
if ( IsLottovout(cp,tx,0) != 0 )
{
preventCCvouts++;
i = 1;
} else i = 0;
if ( tx.vout[i].nValue != COIN )
return eval->Invalid("invalid Lotto output");
retval = PreventCC(eval,tx,preventCCvins,numvins,preventCCvouts,numvouts);
if ( retval != 0 )
fprintf(stderr,"Lottoget validated\n");
else fprintf(stderr,"Lottoget invalid\n");
return(retval);
}
}
}
// end of consensus code
// helper functions for rpc calls in rpcwallet.cpp
uint64_t AddLottoInputs(struct CCcontract_info *cp,CMutableTransaction &mtx,CPubKey pk,uint64_t total,int32_t maxinputs)
{
char coinaddr[64]; uint64_t nValue,price,totalinputs = 0; uint256 txid,hashBlock; std::vector<uint8_t> origpubkey; CTransaction vintx; int32_t n = 0;
std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> > unspentOutputs;
GetCCaddress(cp,coinaddr,pk);
SetCCunspents(unspentOutputs,coinaddr);
for (std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++)
{
txid = it->first.txhash;
// prevent dup
if ( GetTransaction(txid,vintx,hashBlock,false) != 0 )
{
if ( (nValue= IsLottovout(cp,vintx,(int32_t)it->first.index)) > 0 )
{
if ( total != 0 && maxinputs != 0 )
mtx.vin.push_back(CTxIn(txid,(int32_t)it->first.index,CScript()));
nValue = it->second.satoshis;
totalinputs += nValue;
n++;
if ( (total > 0 && totalinputs >= total) || (maxinputs > 0 && n >= maxinputs) )
break;
}
}
}
return(totalinputs);
}
std::string LottoTicket(uint64_t txfee,uint64_t numtickets)
{
CMutableTransaction mtx; CPubKey mypk,Lottopk; CScript opret; uint64_t inputs,CCchange=0,nValue=COIN; struct CCcontract_info *cp,C;
cp = CCinit(&C,EVAL_LOTTO);
if ( txfee == 0 )
txfee = 10000;
Lottopk = GetUnspendable(cp,0);
mypk = pubkey2pk(Mypubkey());
if ( (inputs= AddLottoInputs(cp,mtx,Lottopk,nValue+txfee,60)) > 0 )
{
if ( inputs > nValue )
CCchange = (inputs - nValue - txfee);
if ( CCchange != 0 )
mtx.vout.push_back(MakeCC1vout(EVAL_LOTTO,CCchange,Lottopk));
mtx.vout.push_back(CTxOut(nValue,CScript() << ParseHex(HexStr(mypk)) << OP_CHECKSIG));
return(FinalizeCCTx(-1LL,cp,mtx,mypk,txfee,opret));
} else fprintf(stderr,"cant find Lotto inputs\n");
return(0);
}
std::string LottoWinner(uint64_t txfee)
{
CMutableTransaction mtx; CPubKey mypk,Lottopk; uint64_t winnings = 0; CScript opret; struct CCcontract_info *cp,C;
cp = CCinit(&C,EVAL_LOTTO);
if ( txfee == 0 )
txfee = 10000;
mypk = pubkey2pk(Mypubkey());
Lottopk = GetUnspendable(cp,0);
if ( AddNormalinputs(mtx,mypk,txfee,64) > 0 )
{
mtx.vout.push_back(MakeCC1vout(EVAL_LOTTO,winnings,Lottopk));
return(FinalizeCCTx(0,cp,mtx,mypk,txfee,opret));
}
return(0);
}

183
src/cc/ponzi.cpp

@ -0,0 +1,183 @@
/******************************************************************************
* Copyright © 2014-2018 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 "CCponzi.h"
#include "../txmempool.h"
/*
*/
// start of consensus code
uint64_t IsPonzivout(struct CCcontract_info *cp,const CTransaction& tx,int32_t v)
{
char destaddr[64];
if ( tx.vout[v].scriptPubKey.IsPayToCryptoCondition() != 0 )
{
if ( Getscriptaddress(destaddr,tx.vout[v].scriptPubKey) > 0 && strcmp(destaddr,cp->unspendableCCaddr) == 0 )
return(tx.vout[v].nValue);
}
return(0);
}
bool PonziExactAmounts(struct CCcontract_info *cp,Eval* eval,const CTransaction &tx,int32_t minage,uint64_t txfee)
{
static uint256 zerohash;
CTransaction vinTx; uint256 hashBlock,activehash; int32_t i,numvins,numvouts; uint64_t inputs=0,outputs=0,assetoshis;
numvins = tx.vin.size();
numvouts = tx.vout.size();
for (i=0; i<numvins; i++)
{
//fprintf(stderr,"vini.%d\n",i);
if ( (*cp->ismyvin)(tx.vin[i].scriptSig) != 0 )
{
//fprintf(stderr,"vini.%d check mempool\n",i);
if ( eval->GetTxUnconfirmed(tx.vin[i].prevout.hash,vinTx,hashBlock) == 0 )
return eval->Invalid("cant find vinTx");
else
{
//fprintf(stderr,"vini.%d check hash and vout\n",i);
if ( hashBlock == zerohash )
return eval->Invalid("cant ponzi from mempool");
if ( (assetoshis= IsPonzivout(cp,vinTx,tx.vin[i].prevout.n)) != 0 )
inputs += assetoshis;
}
}
}
for (i=0; i<numvouts; i++)
{
//fprintf(stderr,"i.%d of numvouts.%d\n",i,numvouts);
if ( (assetoshis= IsPonzivout(cp,tx,i)) != 0 )
outputs += assetoshis;
}
if ( inputs != outputs+COIN+txfee )
{
fprintf(stderr,"inputs %llu vs outputs %llu\n",(long long)inputs,(long long)outputs);
return eval->Invalid("mismatched inputs != outputs + COIN + txfee");
}
else return(true);
}
bool PonziValidate(struct CCcontract_info *cp,Eval* eval,const CTransaction &tx)
{
int32_t numvins,numvouts,preventCCvins,preventCCvouts,i; bool retval;
numvins = tx.vin.size();
numvouts = tx.vout.size();
preventCCvins = preventCCvouts = -1;
if ( numvouts < 1 )
return eval->Invalid("no vouts");
else
{
//fprintf(stderr,"check vins\n");
for (i=0; i<numvins; i++)
{
if ( IsCCInput(tx.vin[0].scriptSig) == 0 )
{
fprintf(stderr,"ponziget invalid vini\n");
return eval->Invalid("illegal normal vini");
}
}
//fprintf(stderr,"check amounts\n");
if ( PonziExactAmounts(cp,eval,tx,1,10000) == false )
{
fprintf(stderr,"ponziget invalid amount\n");
return false;
}
else
{
preventCCvouts = 1;
if ( IsPonzivout(cp,tx,0) != 0 )
{
preventCCvouts++;
i = 1;
} else i = 0;
if ( tx.vout[i].nValue != COIN )
return eval->Invalid("invalid ponzi output");
retval = PreventCC(eval,tx,preventCCvins,numvins,preventCCvouts,numvouts);
if ( retval != 0 )
fprintf(stderr,"ponziget validated\n");
else fprintf(stderr,"ponziget invalid\n");
return(retval);
}
}
}
// end of consensus code
// helper functions for rpc calls in rpcwallet.cpp
uint64_t AddPonziInputs(struct CCcontract_info *cp,CMutableTransaction &mtx,CPubKey pk,uint64_t total,int32_t maxinputs)
{
char coinaddr[64]; uint64_t nValue,price,totalinputs = 0; uint256 txid,hashBlock; std::vector<uint8_t> origpubkey; CTransaction vintx; int32_t n = 0;
std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> > unspentOutputs;
GetCCaddress(cp,coinaddr,pk);
SetCCunspents(unspentOutputs,coinaddr);
for (std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++)
{
txid = it->first.txhash;
// prevent dup
if ( GetTransaction(txid,vintx,hashBlock,false) != 0 )
{
if ( (nValue= IsPonzivout(cp,vintx,(int32_t)it->first.index)) > 0 )
{
if ( total != 0 && maxinputs != 0 )
mtx.vin.push_back(CTxIn(txid,(int32_t)it->first.index,CScript()));
nValue = it->second.satoshis;
totalinputs += nValue;
n++;
if ( (total > 0 && totalinputs >= total) || (maxinputs > 0 && n >= maxinputs) )
break;
}
}
}
return(totalinputs);
}
std::string PonziBuy(uint64_t txfee,uint64_t amount)
{
CMutableTransaction mtx; CPubKey mypk,ponzipk; CScript opret; uint64_t inputs,CCchange=0,nValue=COIN; struct CCcontract_info *cp,C;
cp = CCinit(&C,EVAL_PONZI);
if ( txfee == 0 )
txfee = 10000;
ponzipk = GetUnspendable(cp,0);
mypk = pubkey2pk(Mypubkey());
if ( (inputs= AddPonziInputs(cp,mtx,ponzipk,nValue+txfee,60)) > 0 )
{
if ( inputs > nValue )
CCchange = (inputs - nValue - txfee);
if ( CCchange != 0 )
mtx.vout.push_back(MakeCC1vout(EVAL_PONZI,CCchange,ponzipk));
mtx.vout.push_back(CTxOut(nValue,CScript() << ParseHex(HexStr(mypk)) << OP_CHECKSIG));
return(FinalizeCCTx(-1LL,cp,mtx,mypk,txfee,opret));
} else fprintf(stderr,"cant find ponzi inputs\n");
return(0);
}
std::string PonziClaim(uint64_t txfee)
{
CMutableTransaction mtx; CPubKey mypk,ponzipk; uint64_t funds = 0; CScript opret; struct CCcontract_info *cp,C;
cp = CCinit(&C,EVAL_PONZI);
if ( txfee == 0 )
txfee = 10000;
mypk = pubkey2pk(Mypubkey());
ponzipk = GetUnspendable(cp,0);
if ( AddNormalinputs(mtx,mypk,txfee,64) > 0 )
{
mtx.vout.push_back(MakeCC1vout(EVAL_PONZI,funds,ponzipk));
return(FinalizeCCTx(0,cp,mtx,mypk,txfee,opret));
}
return(0);
}

553
src/cc/rewards.cpp

@ -0,0 +1,553 @@
/******************************************************************************
* Copyright © 2014-2018 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 "CCinclude.h"
/*
The rewards CC contract is initially for OOT, which needs this functionality. However, many of the attributes can be parameterized to allow different rewards programs to run. Multiple rewards plans could even run on the same blockchain, though the user would need to choose which one to lock funds into.
At the high level, the user would lock funds for some amount of time and at the end of it, would get all the locked funds back with an additional reward. So there needs to be a lock funds and unlock funds ability. Additionally, the rewards need to come from somewhere, so similar to the faucet, there would be a way to fund the reward.
Additional requirements are for the user to be able to lock funds via SPV. This requirement in turns forces the creation of a way for anybody to be able to unlock the funds as that operation requires a native daemon running and cant be done over SPV. The idea is to allow anybody to run a script that would unlock all funds that are matured. As far as the user is concerned, he locks his funds via SPV and after some time it comes back with an extra reward.
In reality, the funds are locked into a CC address that is unspendable, except for some special conditions and it needs to come back to the address that funded the lock. In order to implement this, several things are clear.
1) each locked CC utxo needs to be linked to a specific rewards plan
2) each locked CC utxo needs to know the only address that it can be unlocked into
3) SPV requirement means the lock transaction needs to be able to be created without any CC signing
The opreturn will be used to store the name of the rewards plan and all funding and locked funds with the same plan will use the same pool of rewards. plan names will be limited to 8 chars and encoded into a uint64_t.
The initial funding transaction will have all the parameters for the rewards plan encoded in the vouts. Additional fundings will just increase the available CC utxo for the rewards.
Locks wont have any CC vins, but will send to the RewardsCCaddress, with the plan stringbits in the opreturn. vout1 will have the unlock address and no other destination is valid.
Unlock does a CC spend to the vout1 address
createfunding
vins.*: normal inputs
vout.0: CC vout for funding
vout.1: normal marker vout for easy searching
vout.2: normal change
vout.n-1: opreturn 'F' sbits APR minseconds maxseconds mindeposit
addfunding
vins.*: normal inputs
vout.0: CC vout for funding
vout.1: normal change
vout.n-1: opreturn 'A' sbits fundingtxid
lock
vins.*: normal inputs
vout.0: CC vout for locked funds
vout.1: normal output to unlock address
vout.2: change
vout.n-1: opreturn 'L' sbits fundingtxid
unlock
vin.0: locked funds CC vout.0 from lock
vin.1+: funding CC vout.0 from 'F' and 'A' and 'U'
vout.0: funding CC change
vout.1: normal output to unlock address
vout.n-1: opreturn 'U' sbits fundingtxid
*/
uint64_t RewardsCalc(uint64_t amount,uint256 txid,uint64_t APR,uint64_t minseconds,uint64_t maxseconds,uint64_t mindeposit)
{
uint64_t duration,reward = 0;
fprintf(stderr,"minseconds %llu maxseconds %llu\n",(long long)minseconds,(long long)maxseconds);
if ( (duration= CCduration(txid)) < minseconds )
{
return(0);
//duration = (uint32_t)time(NULL) - (1532713903 - 3600 * 24);
} else if ( duration > maxseconds )
duration = maxseconds;
reward = (((amount * APR) / COIN) * duration) / (365*24*3600LL * 100);
fprintf(stderr,"amount %.8f %.8f %llu -> duration.%llu reward %.8f\n",(double)amount/COIN,((double)amount * APR)/COIN,(long long)((amount * APR) / (COIN * 365*24*3600)),(long long)duration,(double)reward/COIN);
return(reward);
}
CScript EncodeRewardsFundingOpRet(uint8_t funcid,uint64_t sbits,uint64_t APR,uint64_t minseconds,uint64_t maxseconds,uint64_t mindeposit)
{
CScript opret; uint8_t evalcode = EVAL_REWARDS;
opret << OP_RETURN << E_MARSHAL(ss << evalcode << 'F' << sbits << APR << minseconds << maxseconds << mindeposit);
return(opret);
}
uint8_t DecodeRewardsFundingOpRet(const CScript &scriptPubKey,uint64_t &sbits,uint64_t &APR,uint64_t &minseconds,uint64_t &maxseconds,uint64_t &mindeposit)
{
std::vector<uint8_t> vopret; uint8_t *script,e,f;
GetOpReturnData(scriptPubKey, vopret);
script = (uint8_t *)vopret.data();
if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> sbits; ss >> APR; ss >> minseconds; ss >> maxseconds; ss >> mindeposit) != 0 )
{
if ( e == EVAL_REWARDS && f == 'F' )
return(f);
}
return(0);
}
CScript EncodeRewardsOpRet(uint8_t funcid,uint64_t sbits,uint256 fundingtxid)
{
CScript opret; uint8_t evalcode = EVAL_REWARDS;
opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << sbits << fundingtxid);
return(opret);
}
uint8_t DecodeRewardsOpRet(uint256 txid,const CScript &scriptPubKey,uint64_t &sbits,uint256 &fundingtxid)
{
std::vector<uint8_t> vopret; uint8_t *script,e,f,funcid; uint64_t APR,minseconds,maxseconds,mindeposit;
GetOpReturnData(scriptPubKey, vopret);
if ( vopret.size() > 2 )
{
script = (uint8_t *)vopret.data();
if ( script[0] == EVAL_REWARDS )
{
if ( script[1] == 'F' )
{
if ( E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> sbits; ss >> APR; ss >> minseconds; ss >> maxseconds; ss >> mindeposit) != 0 )
{
fundingtxid = txid;
return('F');
} else fprintf(stderr,"unmarshal error for F\n");
}
else if ( E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> sbits; ss >> fundingtxid) != 0 )
{
if ( e == EVAL_REWARDS && (f == 'L' || f == 'U' || f == 'A') )
return(f);
else fprintf(stderr,"mismatched e.%02x f.(%c)\n",e,f);
}
} else fprintf(stderr,"script[0] %02x != EVAL_REWARDS\n",script[0]);
} else fprintf(stderr,"not enough opret.[%d]\n",(int32_t)vopret.size());
return(0);
}
uint64_t IsRewardsvout(struct CCcontract_info *cp,const CTransaction& tx,int32_t v)
{
char destaddr[64];
if ( tx.vout[v].scriptPubKey.IsPayToCryptoCondition() != 0 )
{
if ( Getscriptaddress(destaddr,tx.vout[v].scriptPubKey) > 0 && strcmp(destaddr,cp->unspendableCCaddr) == 0 )
return(tx.vout[v].nValue);
}
return(0);
}
bool RewardsExactAmounts(struct CCcontract_info *cp,Eval *eval,const CTransaction &tx,uint64_t txfee)
{
static uint256 zerohash;
CTransaction vinTx; uint256 hashBlock; int32_t i,numvins,numvouts; uint64_t inputs=0,outputs=0,assetoshis;
numvins = tx.vin.size();
numvouts = tx.vout.size();
for (i=0; i<numvins; i++)
{
if ( (*cp->ismyvin)(tx.vin[i].scriptSig) != 0 )
{
if ( eval->GetTxUnconfirmed(tx.vin[i].prevout.hash,vinTx,hashBlock) == 0 )
return eval->Invalid("always should find vin, but didnt");
else
{
if ( hashBlock == zerohash )
return eval->Invalid("cant rewards from mempool");
if ( (assetoshis= IsRewardsvout(cp,vinTx,tx.vin[i].prevout.n)) != 0 )
inputs += assetoshis;
}
}
}
for (i=0; i<numvouts; i++)
{
//fprintf(stderr,"i.%d of numvouts.%d\n",i,numvouts);
if ( (assetoshis= IsRewardsvout(cp,tx,i)) != 0 )
outputs += assetoshis;
}
if ( inputs != outputs+txfee )
{
fprintf(stderr,"inputs %llu vs outputs %llu\n",(long long)inputs,(long long)outputs);
return eval->Invalid("mismatched inputs != outputs + txfee");
}
else return(true);
}
bool RewardsValidate(struct CCcontract_info *cp,Eval* eval,const CTransaction &tx)
{
uint256 txid,fundingtxid,hashBlock; uint64_t sbits,APR,minseconds,maxseconds,mindeposit,amount,reward,txfee=10000; int32_t numvins,numvouts,preventCCvins,preventCCvouts,i; uint8_t funcid; CScript scriptPubKey; CTransaction fundingTx,vinTx;
numvins = tx.vin.size();
numvouts = tx.vout.size();
preventCCvins = preventCCvouts = -1;
if ( numvouts < 1 )
return eval->Invalid("no vouts");
else
{
txid = tx.GetHash();
if ( (funcid= DecodeRewardsOpRet(txid,tx.vout[numvouts-1].scriptPubKey,sbits,fundingtxid)) != 0 )
{
if ( eval->GetTxUnconfirmed(fundingtxid,fundingTx,hashBlock) == 0 )
return eval->Invalid("cant find fundingtxid");
else if ( fundingTx.vout.size() > 0 && DecodeRewardsFundingOpRet(fundingTx.vout[fundingTx.vout.size()-1].scriptPubKey,sbits,APR,minseconds,maxseconds,mindeposit) != 'F' )
return eval->Invalid("fundingTx not valid");
switch ( funcid )
{
case 'F':
//vins.*: normal inputs
//vout.0: CC vout for funding
//vout.1: normal marker vout for easy searching
//vout.2: normal change
//vout.n-1: opreturn 'F' sbits APR minseconds maxseconds mindeposit
return eval->Invalid("unexpected RewardsValidate for createfunding");
break;
case 'A':
//vins.*: normal inputs
//vout.0: CC vout for funding
//vout.1: normal change
//vout.n-1: opreturn 'A' sbits fundingtxid
return eval->Invalid("unexpected RewardsValidate for addfunding");
break;
case 'L':
//vins.*: normal inputs
//vout.0: CC vout for locked funds
//vout.1: normal output to unlock address
//vout.2: change
//vout.n-1: opreturn 'L' sbits fundingtxid
return eval->Invalid("unexpected RewardsValidate for lock");
break;
case 'U':
//vin.0: locked funds CC vout.0 from lock
//vin.1+: funding CC vout.0 from 'F' and 'A' and 'U'
//vout.0: funding CC change
//vout.1: normal output to unlock address
//vout.n-1: opreturn 'U' sbits fundingtxid
for (i=0; i<numvins; i++)
{
if ( (*cp->ismyvin)(tx.vin[i].scriptSig) == 0 )
return eval->Invalid("unexpected normal vin for unlock");
}
if ( RewardsExactAmounts(cp,eval,tx,txfee+tx.vout[1].nValue) == 0 )
return false;
else if ( eval->GetTxUnconfirmed(tx.vin[0].prevout.hash,vinTx,hashBlock) == 0 )
return eval->Invalid("always should find vin.0, but didnt");
else if ( vinTx.vout[0].scriptPubKey.IsPayToCryptoCondition() == 0 )
return eval->Invalid("lock tx vout.0 is normal output");
else if ( tx.vout.size() < 3 )
return eval->Invalid("unlock tx not enough vouts");
else if ( tx.vout[0].scriptPubKey.IsPayToCryptoCondition() == 0 )
return eval->Invalid("unlock tx vout.0 is normal output");
else if ( tx.vout[1].scriptPubKey.IsPayToCryptoCondition() != 0 )
return eval->Invalid("unlock tx vout.1 is CC output");
else if ( tx.vout[1].scriptPubKey != vinTx.vout[1].scriptPubKey )
return eval->Invalid("unlock tx vout.1 mismatched scriptPubKey");
amount = vinTx.vout[0].nValue;
reward = RewardsCalc(amount,tx.vin[0].prevout.hash,APR,minseconds,maxseconds,mindeposit);
if ( tx.vout[1].nValue > amount+reward )
return eval->Invalid("unlock tx vout.1 isnt amount+reward");
preventCCvouts = 1;
break;
}
}
return(PreventCC(eval,tx,preventCCvins,numvins,preventCCvouts,numvouts));
}
return(true);
}
// 'L' vs 'F' and 'A'
uint64_t AddRewardsInputs(CScript &scriptPubKey,int32_t fundsflag,struct CCcontract_info *cp,CMutableTransaction &mtx,CPubKey pk,uint64_t total,int32_t maxinputs)
{
char coinaddr[64],str[65]; uint64_t sbits,nValue,totalinputs = 0; uint256 txid,hashBlock,fundingtxid; CTransaction tx; int32_t j,vout,n = 0; uint8_t funcid;
std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> > unspentOutputs;
GetCCaddress(cp,coinaddr,pk);
SetCCunspents(unspentOutputs,coinaddr);
for (std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++)
{
txid = it->first.txhash;
vout = (int32_t)it->first.index;
fprintf(stderr,"(%s) %s/v%d %.8f\n",coinaddr,uint256_str(str,txid),vout,(double)it->second.satoshis/COIN);
for (j=0; j<mtx.vin.size(); j++)
if ( txid == mtx.vin[j].prevout.hash && vout == mtx.vin[j].prevout.n )
break;
if ( j != mtx.vin.size() )
continue;
if ( GetTransaction(txid,tx,hashBlock,false) != 0 && tx.vout.size() > 0 && tx.vout[vout].scriptPubKey.IsPayToCryptoCondition() != 0 )
{
if ( (funcid= DecodeRewardsOpRet(txid,tx.vout[tx.vout.size()-1].scriptPubKey,sbits,fundingtxid)) != 0 )
{
fprintf(stderr,"fundsflag.%d (%c) %.8f %.8f\n",fundsflag,funcid,(double)tx.vout[vout].nValue/COIN,(double)it->second.satoshis/COIN);
if ( fundsflag != 0 && funcid != 'F' && funcid != 'A' && funcid != 'U' )
continue;
else if ( fundsflag == 0 && (funcid != 'L' || tx.vout.size() < 4) )
continue;
if ( total != 0 && maxinputs != 0 )
{
if ( fundsflag == 0 )
scriptPubKey = tx.vout[1].scriptPubKey;
mtx.vin.push_back(CTxIn(txid,vout,CScript()));
}
totalinputs += it->second.satoshis;
n++;
if ( (total > 0 && totalinputs >= total) || (maxinputs > 0 && n >= maxinputs) )
break;
} else fprintf(stderr,"null funcid\n");
}
}
return(totalinputs);
}
uint64_t RewardsPlanFunds(uint64_t refsbits,struct CCcontract_info *cp,CPubKey pk,uint256 reffundingtxid)
{
char coinaddr[64]; uint64_t sbits,nValue,totalinputs = 0; uint256 txid,hashBlock,fundingtxid; CTransaction tx; int32_t vout; uint8_t funcid;
std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> > unspentOutputs;
GetCCaddress(cp,coinaddr,pk);
SetCCunspents(unspentOutputs,coinaddr);
for (std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++)
{
txid = it->first.txhash;
vout = (int32_t)it->first.index;
if ( GetTransaction(txid,tx,hashBlock,false) != 0 && tx.vout[vout].scriptPubKey.IsPayToCryptoCondition() != 0 )
{
if ( (funcid= DecodeRewardsOpRet(txid,tx.vout[tx.vout.size()-1].scriptPubKey,sbits,fundingtxid)) != 0 )
{
if ( (funcid == 'F' && reffundingtxid == txid) || reffundingtxid == fundingtxid )
{
if ( refsbits == sbits && (nValue= IsRewardsvout(cp,tx,vout)) > 0 )
totalinputs += nValue;
else fprintf(stderr,"refsbits.%llx sbits.%llx nValue %.8f\n",(long long)refsbits,(long long)sbits,(double)nValue/COIN);
} //else fprintf(stderr,"else case\n");
} else fprintf(stderr,"funcid.%d %c skipped %.8f\n",funcid,funcid,(double)tx.vout[vout].nValue/COIN);
}
}
return(totalinputs);
}
bool RewardsPlanExists(struct CCcontract_info *cp,uint64_t refsbits,CPubKey rewardspk,uint64_t &APR,uint64_t &minseconds,uint64_t &maxseconds,uint64_t &mindeposit)
{
char CCaddr[64]; uint64_t sbits; uint256 txid,hashBlock; CTransaction tx;
std::vector<std::pair<CAddressIndexKey, CAmount> > txids;
GetCCaddress(cp,CCaddr,rewardspk);
SetCCtxids(txids,CCaddr);
for (std::vector<std::pair<CAddressIndexKey, CAmount> >::const_iterator it=txids.begin(); it!=txids.end(); it++)
{
//int height = it->first.blockHeight;
txid = it->first.txhash;
if ( GetTransaction(txid,tx,hashBlock,false) != 0 && tx.vout.size() > 0 && ConstrainVout(tx.vout[0],1,CCaddr,0) != 0 )
{
//char str[65]; fprintf(stderr,"rewards plan %s\n",uint256_str(str,txid));
if ( DecodeRewardsFundingOpRet(tx.vout[tx.vout.size()-1].scriptPubKey,sbits,APR,minseconds,maxseconds,mindeposit) == 'F' )
{
if ( sbits == refsbits )
return(true);
}
}
}
return(false);
}
UniValue RewardsInfo(uint256 rewardsid)
{
UniValue result(UniValue::VOBJ); uint256 hashBlock; CTransaction vintx; uint64_t APR,minseconds,maxseconds,mindeposit,sbits; char str[67],numstr[65];
if ( GetTransaction(rewardsid,vintx,hashBlock,false) == 0 )
{
fprintf(stderr,"cant find fundingtxid\n");
result.push_back(Pair("error","cant find fundingtxid"));
return(result);
}
if ( vintx.vout.size() > 0 && DecodeRewardsFundingOpRet(vintx.vout[vintx.vout.size()-1].scriptPubKey,sbits,APR,minseconds,maxseconds,mindeposit) == 0 )
{
fprintf(stderr,"fundingtxid isnt rewards creation txid\n");
result.push_back(Pair("error","fundingtxid isnt rewards creation txid"));
return(result);
}
result.push_back(Pair("result","success"));
result.push_back(Pair("fundingtxid",uint256_str(str,rewardsid)));
unstringbits(str,sbits);
result.push_back(Pair("name",str));
result.push_back(Pair("sbits",sbits));
sprintf(numstr,"%.8f",(double)APR/COIN);
result.push_back(Pair("APR",numstr));
result.push_back(Pair("minseconds",minseconds));
result.push_back(Pair("maxseconds",maxseconds));
sprintf(numstr,"%.8f",(double)mindeposit/COIN);
result.push_back(Pair("mindeposit",numstr));
sprintf(numstr,"%.8f",(double)vintx.vout[0].nValue/COIN);
result.push_back(Pair("funding",numstr));
return(result);
}
UniValue RewardsList()
{
UniValue result(UniValue::VARR); std::vector<std::pair<CAddressIndexKey, CAmount> > addressIndex; struct CCcontract_info *cp,C; uint256 txid,hashBlock; CTransaction vintx; uint64_t sbits,APR,minseconds,maxseconds,mindeposit; char str[65];
cp = CCinit(&C,EVAL_REWARDS);
SetCCtxids(addressIndex,cp->normaladdr);
for (std::vector<std::pair<CAddressIndexKey, CAmount> >::const_iterator it=addressIndex.begin(); it!=addressIndex.end(); it++)
{
txid = it->first.txhash;
if ( GetTransaction(txid,vintx,hashBlock,false) != 0 )
{
if ( vintx.vout.size() > 0 && DecodeRewardsFundingOpRet(vintx.vout[vintx.vout.size()-1].scriptPubKey,sbits,APR,minseconds,maxseconds,mindeposit) != 0 )
{
result.push_back(uint256_str(str,txid));
}
}
}
return(result);
}
std::string RewardsCreateFunding(uint64_t txfee,char *planstr,int64_t funds,int64_t APR,int64_t minseconds,int64_t maxseconds,int64_t mindeposit)
{
CMutableTransaction mtx; CPubKey mypk,rewardspk; CScript opret; uint64_t sbits,a,b,c,d; struct CCcontract_info *cp,C;
if ( funds < 0 || mindeposit < 0 || minseconds < 0 || maxseconds < 0 )
{
fprintf(stderr,"negative parameter error\n");
return(0);
}
cp = CCinit(&C,EVAL_REWARDS);
if ( txfee == 0 )
txfee = 10000;
mypk = pubkey2pk(Mypubkey());
rewardspk = GetUnspendable(cp,0);
sbits = stringbits(planstr);
if ( RewardsPlanExists(cp,sbits,rewardspk,a,b,c,d) != 0 )
{
fprintf(stderr,"Rewards plan (%s) already exists\n",planstr);
return(0);
}
if ( AddNormalinputs(mtx,mypk,funds+2*txfee,64) > 0 )
{
mtx.vout.push_back(MakeCC1vout(cp->evalcode,funds,rewardspk));
mtx.vout.push_back(CTxOut(txfee,CScript() << ParseHex(HexStr(rewardspk)) << OP_CHECKSIG));
return(FinalizeCCTx(0,cp,mtx,mypk,txfee,EncodeRewardsFundingOpRet('F',sbits,APR,minseconds,maxseconds,mindeposit)));
}
fprintf(stderr,"cant find enough inputs\n");
return(0);
}
std::string RewardsAddfunding(uint64_t txfee,char *planstr,uint256 fundingtxid,int64_t amount)
{
CMutableTransaction mtx; CPubKey mypk,rewardspk; CScript opret; uint64_t sbits,a,b,c,d; struct CCcontract_info *cp,C;
if ( amount < 0 )
{
fprintf(stderr,"negative parameter error\n");
return(0);
}
cp = CCinit(&C,EVAL_REWARDS);
if ( txfee == 0 )
txfee = 10000;
mypk = pubkey2pk(Mypubkey());
rewardspk = GetUnspendable(cp,0);
sbits = stringbits(planstr);
if ( RewardsPlanExists(cp,sbits,rewardspk,a,b,c,d) == 0 )
{
fprintf(stderr,"Rewards plan %s doesnt exist\n",planstr);
return(0);
}
sbits = stringbits(planstr);
if ( AddNormalinputs(mtx,mypk,amount+txfee,64) > 0 )
{
mtx.vout.push_back(MakeCC1vout(cp->evalcode,amount,rewardspk));
return(FinalizeCCTx(0,cp,mtx,mypk,txfee,EncodeRewardsOpRet('A',sbits,fundingtxid)));
} else fprintf(stderr,"cant find enough inputs\n");
fprintf(stderr,"cant find fundingtxid\n");
return(0);
}
std::string RewardsLock(uint64_t txfee,char *planstr,uint256 fundingtxid,int64_t deposit)
{
CMutableTransaction mtx; CPubKey mypk,rewardspk; CScript opret; uint64_t sbits,funding,APR,minseconds,maxseconds,mindeposit; struct CCcontract_info *cp,C;
if ( deposit < 0 )
{
fprintf(stderr,"negative parameter error\n");
return(0);
}
cp = CCinit(&C,EVAL_REWARDS);
if ( txfee == 0 )
txfee = 10000;
mypk = pubkey2pk(Mypubkey());
rewardspk = GetUnspendable(cp,0);
sbits = stringbits(planstr);
if ( RewardsPlanExists(cp,sbits,rewardspk,APR,minseconds,maxseconds,mindeposit) == 0 )
{
fprintf(stderr,"Rewards plan %s doesnt exist\n",planstr);
return(0);
}
if ( deposit < mindeposit )
{
fprintf(stderr,"Rewards plan %s deposit %.8f < mindeposit %.8f\n",planstr,(double)deposit/COIN,(double)mindeposit/COIN);
return(0);
}
if ( (funding= RewardsPlanFunds(sbits,cp,rewardspk,fundingtxid)) >= deposit ) // arbitrary cmpval
{
if ( AddNormalinputs(mtx,mypk,deposit+2*txfee,64) > 0 )
{
mtx.vout.push_back(MakeCC1vout(cp->evalcode,deposit,rewardspk));
mtx.vout.push_back(CTxOut(txfee,CScript() << ParseHex(HexStr(mypk)) << OP_CHECKSIG));
return(FinalizeCCTx(0,cp,mtx,mypk,txfee,EncodeRewardsOpRet('L',sbits,fundingtxid)));
} else fprintf(stderr,"cant find enough inputs %.8f note enough for %.8f\n",(double)funding/COIN,(double)deposit/COIN);
}
fprintf(stderr,"cant find rewards inputs\n");
return(0);
}
std::string RewardsUnlock(uint64_t txfee,char *planstr,uint256 fundingtxid,uint256 locktxid)
{
CMutableTransaction mtx; CTransaction tx; char coinaddr[64]; CPubKey mypk,rewardspk; CScript opret,scriptPubKey,ignore; uint256 hashBlock; uint64_t funding,sbits,reward=0,amount=0,inputs,CCchange=0,APR,minseconds,maxseconds,mindeposit; struct CCcontract_info *cp,C;
cp = CCinit(&C,EVAL_REWARDS);
if ( txfee == 0 )
txfee = 10000;
rewardspk = GetUnspendable(cp,0);
mypk = pubkey2pk(Mypubkey());
sbits = stringbits(planstr);
if ( RewardsPlanExists(cp,sbits,rewardspk,APR,minseconds,maxseconds,mindeposit) == 0 )
{
fprintf(stderr,"Rewards plan %s doesnt exist\n",planstr);
return(0);
}
fprintf(stderr,"APR %.8f minseconds.%llu maxseconds.%llu mindeposit %.8f\n",(double)APR/COIN,(long long)minseconds,(long long)maxseconds,(double)mindeposit/COIN);
if ( locktxid == zeroid )
amount = AddRewardsInputs(scriptPubKey,0,cp,mtx,rewardspk,(1LL << 30),1);
else
{
GetCCaddress(cp,coinaddr,rewardspk);
if ( (amount= CCutxovalue(coinaddr,locktxid,0)) == 0 )
{
fprintf(stderr,"%s locktxid/v0 is spent\n",coinaddr);
return(0);
}
if ( GetTransaction(locktxid,tx,hashBlock,false) != 0 && tx.vout.size() > 0 && tx.vout[1].scriptPubKey.IsPayToCryptoCondition() == 0 )
{
scriptPubKey = tx.vout[1].scriptPubKey;
mtx.vin.push_back(CTxIn(locktxid,0,CScript()));
}
else
{
fprintf(stderr,"%s no normal vout.1 in locktxid\n",coinaddr);
return(0);
}
}
if ( amount > 0 && (reward= RewardsCalc(amount,mtx.vin[0].prevout.hash,APR,minseconds,maxseconds,mindeposit)) > txfee && scriptPubKey.size() > 0 )
{
if ( (inputs= AddRewardsInputs(ignore,1,cp,mtx,rewardspk,reward+txfee,30)) > 0 )
{
if ( inputs >= (reward + 2*txfee) )
CCchange = (inputs - (reward + txfee));
fprintf(stderr,"inputs %.8f CCchange %.8f amount %.8f reward %.8f\n",(double)inputs/COIN,(double)CCchange/COIN,(double)amount/COIN,(double)reward/COIN);
mtx.vout.push_back(MakeCC1vout(cp->evalcode,CCchange,rewardspk));
mtx.vout.push_back(CTxOut(amount+reward,scriptPubKey));
return(FinalizeCCTx(-1LL,cp,mtx,mypk,txfee,EncodeRewardsOpRet('U',sbits,fundingtxid)));
}
fprintf(stderr,"cant find enough rewards inputs\n");
}
fprintf(stderr,"amount %.8f -> reward %.8f\n",(double)amount/COIN,(double)reward/COIN);
return(0);
}

0
src/cc/utils.cpp

49
src/cc/utils.h

@ -0,0 +1,49 @@
/******************************************************************************
* Copyright © 2014-2018 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. *
* *
******************************************************************************/
#ifndef CC_UTILS_H
#define CC_UTILS_H
#include "streams.h"
#include "version.h"
/*
* Serialisation boilerplate
*/
template <class T>
std::vector<uint8_t> SerializeF(const T f)
{
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
f(ss);
return std::vector<unsigned char>(ss.begin(), ss.end());
}
template <class T>
bool DeserializeF(const std::vector<unsigned char> vIn, T f)
{
CDataStream ss(vIn, SER_NETWORK, PROTOCOL_VERSION);
try {
f(ss);
if (ss.eof()) return true;
} catch(...) {}
return false;
}
#define E_MARSHAL(body) SerializeF([&] (CDataStream &ss) {body;})
#define E_UNMARSHAL(params, body) DeserializeF(params, [&] (CDataStream &ss) {body;})
#endif /* CC_UTILS_H */

5
src/chain.h

@ -121,7 +121,7 @@ public:
//! height of the entry in the chain. The genesis block has height 0
int nHeight;
int64_t newcoins,zfunds;
//! Which # file this block is stored in (blk?????.dat)
int nFile;
@ -181,6 +181,7 @@ public:
void SetNull()
{
phashBlock = NULL;
newcoins = zfunds = 0;
pprev = NULL;
pskip = NULL;
nHeight = 0;
@ -436,7 +437,7 @@ public:
CBlockIndex *Tip() const {
return vChain.size() > 0 ? vChain[vChain.size() - 1] : NULL;
}
/** Returns the last tip of the chain, or NULL if none. */
CBlockIndex *LastTip() const {
return vChain.size() > 0 ? lastTip : NULL;

16
src/chainparams.cpp

@ -165,6 +165,7 @@ public:
assert(genesis.hashMerkleRoot == uint256S("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
vFixedSeeds.clear();
vSeeds.clear();
vSeeds.push_back(CDNSSeedData("veruscoin.io", "seeds.veruscoin.io")); // @kolo - old static dns seeds
vSeeds.push_back(CDNSSeedData("komodoplatform.com", "seeds.komodoplatform.com")); // @kolo - old static dns seeds
vSeeds.push_back(CDNSSeedData("kolo.supernet.org", "static.kolo.supernet.org")); // @kolo - new static dns seeds ToDo
vSeeds.push_back(CDNSSeedData("kolo.supernet.org", "dynamic.kolo.supernet.org")); // @kolo - crawler seeds ToDo
@ -572,11 +573,18 @@ public:
BOOST_STATIC_ASSERT(equihash_parameters_acceptable(N, K));
nEquihashN = N;
nEquihashK = K;
genesis.nTime = 1296688602;
genesis.nBits = KOMODO_MINDIFF_NBITS;
genesis.nNonce = uint256S("0x0000000000000000000000000000000000000000000000000000000000000021");
genesis.nSolution = ParseHex("0f2a976db4c4263da10fd5d38eb1790469cf19bdb4bf93450e09a72fdff17a3454326399");
genesis = CreateGenesisBlock(
1296688602,
uint256S("0x0000000000000000000000000000000000000000000000000000000000000009"),
ParseHex("01936b7db1eb4ac39f151b8704642d0a8bda13ec547d54cd5e43ba142fc6d8877cab07b3"),
KOMODO_MINDIFF_NBITS, 4, 0);
consensus.hashGenesisBlock = genesis.GetHash();
assert(consensus.hashGenesisBlock == uint256S("0x029f11d80ef9765602235e1bc9727e3eb6ba20839319f761fee920d63401e327"));
assert(genesis.hashMerkleRoot == uint256S("0xc4eaa58879081de3c24a7b117ed2b28300e7ec4c4c1dff1d3f1268b7857a4ddb"));
nDefaultPort = 17779;
nPruneAfterHeight = 1000;

6
src/chainparamsseeds.h

@ -8,6 +8,12 @@
* IPv4 as well as onion addresses are wrapped inside a IPv6 address accordingly.
*/
static SeedSpec6 pnSeed6_main[] = {
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0xb9,0x19,0x30,0xec}, 27485},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0xb9,0x19,0x30,0xec}, 27487},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0xb9,0x40,0x69,0x6f}, 27485},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0xb9,0x40,0x69,0x6f}, 27487},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0xb9,0x19,0x30,0x48}, 27485},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0xb9,0x19,0x30,0x48}, 27487}
};
static SeedSpec6 pnSeed6_test[] = {

13
src/coins.cpp

@ -9,6 +9,7 @@
#include "version.h"
#include "policy/fees.h"
#include "komodo_defs.h"
#include "importcoin.h"
#include <assert.h>
@ -418,11 +419,13 @@ const CScript &CCoinsViewCache::GetSpendFor(const CTxIn& input) const
CAmount CCoinsViewCache::GetValueIn(int32_t nHeight,int64_t *interestp,const CTransaction& tx,uint32_t tiptime) const
{
CAmount value,nResult = 0;
if ( interestp != 0 )
*interestp = 0;
if ( tx.IsCoinImport() )
return GetCoinImportValue(tx);
if ( tx.IsCoinBase() != 0 )
return 0;
CAmount value,nResult = 0;
for (unsigned int i = 0; i < tx.vin.size(); i++)
{
value = GetOutputFor(tx.vin[i]).nValue;
@ -447,6 +450,7 @@ CAmount CCoinsViewCache::GetValueIn(int32_t nHeight,int64_t *interestp,const CTr
return nResult;
}
bool CCoinsViewCache::HaveJoinSplitRequirements(const CTransaction& tx) const
{
boost::unordered_map<uint256, ZCIncrementalMerkleTree, CCoinsKeyHasher> intermediates;
@ -483,12 +487,12 @@ bool CCoinsViewCache::HaveJoinSplitRequirements(const CTransaction& tx) const
bool CCoinsViewCache::HaveInputs(const CTransaction& tx) const
{
if (!tx.IsCoinBase()) {
if (!tx.IsMint()) {
for (unsigned int i = 0; i < tx.vin.size(); i++) {
const COutPoint &prevout = tx.vin[i].prevout;
const CCoins* coins = AccessCoins(prevout.hash);
if (!coins || !coins->IsAvailable(prevout.n)) {
fprintf(stderr,"HaveInputs missing input %s/v%d\n",prevout.hash.ToString().c_str(),prevout.n);
//fprintf(stderr,"HaveInputs missing input %s/v%d\n",prevout.hash.ToString().c_str(),prevout.n);
return false;
}
}
@ -509,6 +513,9 @@ double CCoinsViewCache::GetPriority(const CTransaction &tx, int nHeight) const
if (tx.vjoinsplit.size() > 0) {
return MAX_PRIORITY;
}
if (tx.IsCoinImport()) {
return MAX_PRIORITY;
}
double dResult = 0.0;
BOOST_FOREACH(const CTxIn& txin, tx.vin)

336
src/crosschain.cpp

@ -0,0 +1,336 @@
#include "cc/eval.h"
#include "crosschain.h"
#include "importcoin.h"
#include "main.h"
#include "notarisationdb.h"
/*
* The crosschain workflow.
*
* 3 chains, A, B, and KMD. We would like to prove TX on B.
* There is a notarisation, nA0, which will include TX via an MoM.
* The notarisation nA0 must fall between 2 notarisations of B,
* ie, nB0 and nB1. An MoMoM including this range is propagated to
* B in notarisation receipt (backnotarisation) bnB2.
*
* A: TX bnA0
* \ /
* KMD: nB0 nA0 nB1 nB2
* \ \ \
* B: bnB0 bnB1 bnB2
*/
// XXX: There are potential crashes wherever we access chainActive without a lock,
// because it might be disconnecting blocks at the same time.
int NOTARISATION_SCAN_LIMIT_BLOCKS = 1440;
/* On KMD */
uint256 CalculateProofRoot(const char* symbol, uint32_t targetCCid, int kmdHeight,
std::vector<uint256> &moms, uint256 &destNotarisationTxid)
{
/*
* Notaries don't wait for confirmation on KMD before performing a backnotarisation,
* but we need a determinable range that will encompass all merkle roots. Include MoMs
* including the block height of the last notarisation until the height before the
* previous notarisation.
*
* kmdHeight notarisations-0 notarisations-1
* *********************|
* > scan backwards >
*/
if (targetCCid < 2)
return uint256();
if (kmdHeight < 0 || kmdHeight > chainActive.Height())
return uint256();
int seenOwnNotarisations = 0;
for (int i=0; i<NOTARISATION_SCAN_LIMIT_BLOCKS; i++) {
if (i > kmdHeight) break;
NotarisationsInBlock notarisations;
uint256 blockHash = *chainActive[kmdHeight-i]->phashBlock;
if (!GetBlockNotarisations(blockHash, notarisations))
continue;
// See if we have an own notarisation in this block
BOOST_FOREACH(Notarisation& nota, notarisations) {
if (strcmp(nota.second.symbol, symbol) == 0)
{
seenOwnNotarisations++;
if (seenOwnNotarisations == 1)
destNotarisationTxid = nota.first;
else if (seenOwnNotarisations == 2)
goto end;
break;
}
}
if (seenOwnNotarisations == 1) {
BOOST_FOREACH(Notarisation& nota, notarisations) {
if (nota.second.ccId == targetCCid)
moms.push_back(nota.second.MoM);
}
}
}
end:
return GetMerkleRoot(moms);
}
/*
* Get a notarisation from a given height
*
* Will scan notarisations leveldb up to a limit
*/
template <typename IsTarget>
int ScanNotarisationsFromHeight(int nHeight, const IsTarget f, Notarisation &found)
{
int limit = std::min(nHeight + NOTARISATION_SCAN_LIMIT_BLOCKS, chainActive.Height());
for (int h=nHeight; h<limit; h++) {
NotarisationsInBlock notarisations;
if (!GetBlockNotarisations(*chainActive[h]->phashBlock, notarisations))
continue;
BOOST_FOREACH(found, notarisations) {
if (f(found)) {
return h;
}
}
}
return 0;
}
/* On KMD */
TxProof GetCrossChainProof(const uint256 txid, const char* targetSymbol, uint32_t targetCCid,
const TxProof assetChainProof)
{
/*
* Here we are given a proof generated by an assetchain A which goes from given txid to
* an assetchain MoM. We need to go from the notarisationTxid for A to the MoMoM range of the
* backnotarisation for B (given by kmdheight of notarisation), find the MoM within the MoMs for
* that range, and finally extend the proof to lead to the MoMoM (proof root).
*/
EvalRef eval;
uint256 MoM = assetChainProof.second.Exec(txid);
// Get a kmd height for given notarisation Txid
int kmdHeight;
{
CTransaction sourceNotarisation;
uint256 hashBlock;
CBlockIndex blockIdx;
if (!eval->GetTxConfirmed(assetChainProof.first, sourceNotarisation, blockIdx))
throw std::runtime_error("Notarisation not found");
kmdHeight = blockIdx.nHeight;
}
// We now have a kmdHeight of the notarisation from chain A. So we know that a MoM exists
// at that height.
// If we call CalculateProofRoot with that height, it'll scan backwards, until it finds
// a notarisation from B, and it might not include our notarisation from A
// at all. So, the thing we need to do is scan forwards to find the notarisation for B,
// that is inclusive of A.
Notarisation nota;
auto isTarget = [&](Notarisation &nota) {
return strcmp(nota.second.symbol, targetSymbol) == 0;
};
kmdHeight = ScanNotarisationsFromHeight(kmdHeight, isTarget, nota);
if (!kmdHeight)
throw std::runtime_error("Cannot find notarisation for target inclusive of source");
// Get MoMs for kmd height and symbol
std::vector<uint256> moms;
uint256 targetChainNotarisationTxid;
uint256 MoMoM = CalculateProofRoot(targetSymbol, targetCCid, kmdHeight, moms, targetChainNotarisationTxid);
if (MoMoM.IsNull())
throw std::runtime_error("No MoMs found");
// Find index of source MoM in MoMoM
int nIndex;
for (nIndex=0; nIndex<moms.size(); nIndex++) {
if (moms[nIndex] == MoM)
goto cont;
}
throw std::runtime_error("Couldn't find MoM within MoMoM set");
cont:
// Create a branch
std::vector<uint256> vBranch;
{
CBlock fakeBlock;
for (int i=0; i<moms.size(); i++) {
CTransaction fakeTx;
// first value in CTransaction memory is it's hash
memcpy((void*)&fakeTx, moms[i].begin(), 32);
fakeBlock.vtx.push_back(fakeTx);
}
vBranch = fakeBlock.GetMerkleBranch(nIndex);
}
// Concatenate branches
MerkleBranch newBranch = assetChainProof.second;
newBranch << MerkleBranch(nIndex, vBranch);
// Check proof
if (newBranch.Exec(txid) != MoMoM)
throw std::runtime_error("Proof check failed");
return std::make_pair(targetChainNotarisationTxid,newBranch);
}
/*
* Takes an importTx that has proof leading to assetchain root
* and extends proof to cross chain root
*/
void CompleteImportTransaction(CTransaction &importTx)
{
TxProof proof;
CTransaction burnTx;
std::vector<CTxOut> payouts;
if (!UnmarshalImportTx(importTx, proof, burnTx, payouts))
throw std::runtime_error("Couldn't parse importTx");
std::string targetSymbol;
uint32_t targetCCid;
uint256 payoutsHash;
if (!UnmarshalBurnTx(burnTx, targetSymbol, &targetCCid, payoutsHash))
throw std::runtime_error("Couldn't parse burnTx");
proof = GetCrossChainProof(burnTx.GetHash(), targetSymbol.data(), targetCCid, proof);
importTx = MakeImportCoinTransaction(proof, burnTx, payouts);
}
bool IsSameAssetChain(const Notarisation &nota) {
return strcmp(nota.second.symbol, ASSETCHAINS_SYMBOL) == 0;
};
/* On assetchain */
bool GetNextBacknotarisation(uint256 kmdNotarisationTxid, Notarisation &out)
{
/*
* Here we are given a txid, and a proof.
* We go from the KMD notarisation txid to the backnotarisation,
* then jump to the next backnotarisation, which contains the corresponding MoMoM.
*/
Notarisation bn;
if (!GetBackNotarisation(kmdNotarisationTxid, bn))
return false;
// Need to get block height of that backnotarisation
EvalRef eval;
CBlockIndex block;
CTransaction tx;
if (!eval->GetTxConfirmed(bn.first, tx, block)){
fprintf(stderr, "Can't get height of backnotarisation, this should not happen\n");
return false;
}
return (bool) ScanNotarisationsFromHeight(block.nHeight+1, &IsSameAssetChain, out);
}
/*
* On assetchain
* in: txid
* out: pair<notarisationTxHash,merkleBranch>
*/
TxProof GetAssetchainProof(uint256 hash)
{
int nIndex;
CBlockIndex* blockIndex;
Notarisation nota;
std::vector<uint256> branch;
{
uint256 blockHash;
CTransaction tx;
if (!GetTransaction(hash, tx, blockHash, true))
throw std::runtime_error("cannot find transaction");
if (blockHash.IsNull())
throw std::runtime_error("tx still in mempool");
blockIndex = mapBlockIndex[blockHash];
int h = blockIndex->nHeight;
// The assumption here is that the first notarisation for a height GTE than
// the transaction block height will contain the corresponding MoM. If there
// are sequence issues with the notarisations this may fail.
auto isTarget = [&](Notarisation &nota) {
if (!IsSameAssetChain(nota)) return false;
return nota.second.height >= blockIndex->nHeight;
};
if (!ScanNotarisationsFromHeight(blockIndex->nHeight, isTarget, nota))
throw std::runtime_error("backnotarisation not yet confirmed");
// index of block in MoM leaves
nIndex = nota.second.height - blockIndex->nHeight;
}
// build merkle chain from blocks to MoM
{
std::vector<uint256> leaves, tree;
for (int i=0; i<nota.second.MoMDepth; i++) {
uint256 mRoot = chainActive[nota.second.height - i]->hashMerkleRoot;
leaves.push_back(mRoot);
}
bool fMutated;
BuildMerkleTree(&fMutated, leaves, tree);
branch = GetMerkleBranch(nIndex, leaves.size(), tree);
// Check branch
uint256 ourResult = SafeCheckMerkleBranch(blockIndex->hashMerkleRoot, branch, nIndex);
if (nota.second.MoM != ourResult)
throw std::runtime_error("Failed merkle block->MoM");
}
// Now get the tx merkle branch
{
CBlock block;
if (fHavePruned && !(blockIndex->nStatus & BLOCK_HAVE_DATA) && blockIndex->nTx > 0)
throw std::runtime_error("Block not available (pruned data)");
if(!ReadBlockFromDisk(block, blockIndex,1))
throw std::runtime_error("Can't read block from disk");
// Locate the transaction in the block
int nTxIndex;
for (nTxIndex = 0; nTxIndex < (int)block.vtx.size(); nTxIndex++)
if (block.vtx[nTxIndex].GetHash() == hash)
break;
if (nTxIndex == (int)block.vtx.size())
throw std::runtime_error("Error locating tx in block");
std::vector<uint256> txBranch = block.GetMerkleBranch(nTxIndex);
// Check branch
if (block.hashMerkleRoot != CBlock::CheckMerkleBranch(hash, txBranch, nTxIndex))
throw std::runtime_error("Failed merkle tx->block");
// concatenate branches
nIndex = (nIndex << txBranch.size()) + nTxIndex;
branch.insert(branch.begin(), txBranch.begin(), txBranch.end());
}
// Check the proof
if (nota.second.MoM != CBlock::CheckMerkleBranch(hash, branch, nIndex))
throw std::runtime_error("Failed validating MoM");
// All done!
CDataStream ssProof(SER_NETWORK, PROTOCOL_VERSION);
return std::make_pair(nota.second.txHash, MerkleBranch(nIndex, branch));
}

21
src/crosschain.h

@ -0,0 +1,21 @@
#ifndef CROSSCHAIN_H
#define CROSSCHAIN_H
#include "cc/eval.h"
/* On assetchain */
TxProof GetAssetchainProof(uint256 hash);
/* On KMD */
uint256 CalculateProofRoot(const char* symbol, uint32_t targetCCid, int kmdHeight,
std::vector<uint256> &moms, uint256 &destNotarisationTxid);
TxProof GetCrossChainProof(const uint256 txid, const char* targetSymbol, uint32_t targetCCid,
const TxProof assetChainProof);
void CompleteImportTransaction(CTransaction &importTx);
/* On assetchain */
bool GetNextBacknotarisation(uint256 txid, std::pair<uint256,NotarisationData> &bn);
#endif /* CROSSCHAIN_H */

14
src/cryptoconditions/src/anon.c

@ -1,3 +1,17 @@
/******************************************************************************
* Copyright © 2014-2018 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 "asn/Condition.h"
#include "asn/Fulfillment.h"

15
src/cryptoconditions/src/cryptoconditions.c

@ -1,3 +1,18 @@
/******************************************************************************
* Copyright © 2014-2018 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 "strings.h"
#include "asn/Condition.h"
#include "asn/Fulfillment.h"

15
src/cryptoconditions/src/ed25519.c

@ -1,3 +1,18 @@
/******************************************************************************
* Copyright © 2014-2018 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 "asn/Condition.h"
#include "asn/Fulfillment.h"
#include "asn/Ed25519FingerprintContents.h"

15
src/cryptoconditions/src/eval.c

@ -1,3 +1,18 @@
/******************************************************************************
* Copyright © 2014-2018 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 "asn/Condition.h"
#include "asn/Fulfillment.h"
#include "asn/EvalFulfillment.h"

15
src/cryptoconditions/src/internal.h

@ -1,3 +1,18 @@
/******************************************************************************
* Copyright © 2014-2018 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 <Condition.h>
#include <Fulfillment.h>
#include "include/cJSON.h"

15
src/cryptoconditions/src/json_rpc.c

@ -1,3 +1,18 @@
/******************************************************************************
* Copyright © 2014-2018 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 "cryptoconditions.h"
#include "internal.h"
#include <cJSON.h>

14
src/cryptoconditions/src/prefix.c

@ -1,3 +1,17 @@
/******************************************************************************
* Copyright © 2014-2018 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 "asn/Condition.h"
#include "asn/Fulfillment.h"

14
src/cryptoconditions/src/preimage.c

@ -1,3 +1,17 @@
/******************************************************************************
* Copyright © 2014-2018 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 "asn/Condition.h"
#include "asn/Fulfillment.h"

14
src/cryptoconditions/src/threshold.c

@ -1,3 +1,17 @@
/******************************************************************************
* Copyright © 2014-2018 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 "asn/Condition.h"
#include "asn/Fulfillment.h"

15
src/cryptoconditions/src/utils.c

@ -1,3 +1,18 @@
/******************************************************************************
* Copyright © 2014-2018 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 <stdint.h>
#include <stdlib.h>
#include <stdio.h>

8
src/deprecation.h

@ -6,11 +6,11 @@
#define ZCASH_DEPRECATION_H
// Deprecation policy:
// * Shut down 16 weeks' worth of blocks after the estimated release block height.
// * A warning is shown during the 2 weeks' worth of blocks prior to shut down.
static const int APPROX_RELEASE_HEIGHT = 800000;
// * Shut down WEEKS_UNTIL_DEPRECATION weeks' worth of blocks after the estimated release block height.
// * A warning is shown during the DEPRECATION_WARN_LIMIT worth of blocks prior to shut down.
static const int WEEKS_UNTIL_DEPRECATION = 52;
static const int DEPRECATION_HEIGHT = APPROX_RELEASE_HEIGHT + (WEEKS_UNTIL_DEPRECATION * 7 * 24 * 24);
static const int DEPRECATION_HEIGHT = 1400000;
static const int APPROX_RELEASE_HEIGHT = DEPRECATION_HEIGHT - (WEEKS_UNTIL_DEPRECATION * 7 * 24 * 60);
// Number of blocks before deprecation to warn users
static const int DEPRECATION_WARN_LIMIT = 60 * 24 * 60; // 2 months

11
src/dpowassets

@ -22,13 +22,20 @@ curl --url "http://127.0.0.1:7776" --data "{\"agent\":\"iguana\",\"method\":\"dp
curl --url "http://127.0.0.1:7776" --data "{\"agent\":\"iguana\",\"method\":\"dpow\",\"symbol\":\"CEAL\",\"pubkey\":\"$pubkey\"}"
curl --url "http://127.0.0.1:7776" --data "{\"agent\":\"iguana\",\"method\":\"dpow\",\"symbol\":\"MESH\",\"pubkey\":\"$pubkey\"}"
curl --url "http://127.0.0.1:7776" --data "{\"agent\":\"iguana\",\"method\":\"dpow\",\"symbol\":\"MNZ\",\"pubkey\":\"$pubkey\"}"
curl --url "http://127.0.0.1:7776" --data "{\"agent\":\"iguana\",\"method\":\"dpow\",\"symbol\":\"CHIPS\",\"pubkey\":\"$pubkey\"}"
curl --url "http://127.0.0.1:7776" --data "{\"agent\":\"iguana\",\"method\":\"dpow\",\"symbol\":\"AXO\",\"pubkey\":\"$pubkey\"}"
curl --url "http://127.0.0.1:7776" --data "{\"agent\":\"iguana\",\"method\":\"dpow\",\"symbol\":\"ETOMIC\",\"pubkey\":\"$pubkey\"}"
curl --url "http://127.0.0.1:7776" --data "{\"agent\":\"iguana\",\"method\":\"dpow\",\"symbol\":\"BTCH\",\"pubkey\":\"$pubkey\"}"
curl --url "http://127.0.0.1:7776" --data "{\"agent\":\"iguana\",\"method\":\"dpow\",\"symbol\":\"CHAIN\",\"pubkey\":\"$pubkey\"}"
curl --url "http://127.0.0.1:7776" --data "{\"agent\":\"iguana\",\"method\":\"dpow\",\"symbol\":\"VOTE2018\",\"pubkey\":\"$pubkey\"}"
curl --url "http://127.0.0.1:7776" --data "{\"agent\":\"iguana\",\"method\":\"dpow\",\"symbol\":\"NINJA\",\"pubkey\":\"$pubkey\"}"
curl --url "http://127.0.0.1:7776" --data "{\"agent\":\"iguana\",\"method\":\"dpow\",\"symbol\":\"OOT\",\"pubkey\":\"$pubkey\"}"
curl --url "http://127.0.0.1:7776" --data "{\"agent\":\"iguana\",\"method\":\"dpow\",\"symbol\":\"BNTN\",\"pubkey\":\"$pubkey\"}"
curl --url "http://127.0.0.1:7776" --data "{\"agent\":\"iguana\",\"method\":\"dpow\",\"symbol\":\"PRLPAY\",\"pubkey\":\"$pubkey\"}"
curl --url "http://127.0.0.1:7776" --data "{\"agent\":\"iguana\",\"method\":\"dpow\",\"symbol\":\"DSEC\",\"pubkey\":\"$pubkey\"}"
curl --url "http://127.0.0.1:7776" --data "{\"agent\":\"iguana\",\"method\":\"dpow\",\"symbol\":\"GLXT\",\"pubkey\":\"$pubkey\"}"
curl --url "http://127.0.0.1:7776" --data "{\"agent\":\"iguana\",\"method\":\"dpow\",\"symbol\":\"EQL\",\"pubkey\":\"$pubkey\"}"
curl --url "http://127.0.0.1:7776" --data "{\"agent\":\"iguana\",\"method\":\"dpow\",\"symbol\":\"ZILLA\",\"pubkey\":\"$pubkey\"}"
curl --url "http://127.0.0.1:7776" --data "{\"agent\":\"iguana\",\"method\":\"dpow\",\"symbol\":\"CHIPS\",\"pubkey\":\"$pubkey\"}"
curl --url "http://127.0.0.1:7776" --data "{\"agent\":\"iguana\",\"method\":\"dpow\",\"symbol\":\"GAME\",\"freq\":5,\"pubkey\":\"$pubkey\"}"
curl --url "http://127.0.0.1:7776" --data "{\"agent\":\"iguana\",\"method\":\"dpow\",\"symbol\":\"RFOX\",\"freq\":10,\"pubkey\":\"$pubkey\"}"
curl --url "http://127.0.0.1:7776" --data "{\"agent\":\"iguana\",\"method\":\"dpow\",\"symbol\":\"VRSC\",\"freq\":10,\"pubkey\":\"$pubkey\"}"
curl --url "http://127.0.0.1:7776" --data "{\"agent\":\"iguana\",\"method\":\"dpow\",\"symbol\":\"SEC\",\"pubkey\":\"$pubkey\"}"

36
src/fiat-cli

@ -1,30 +1,8 @@
#!/bin/bash
#set -x
echo revs; fiat/revs $1 $2 $3 $4
echo supernet; fiat/supernet $1 $2 $3 $4
echo dex; fiat/dex $1 $2 $3 $4
echo pangea; fiat/pangea $1 $2 $3 $4
echo jumblr; fiat/jumblr $1 $2 $3 $4
echo bet; fiat/bet $1 $2 $3 $4
echo crypto; fiat/crypto $1 $2 $3 $4
echo hodl; fiat/hodl $1 $2 $3 $4
echo mshark; fiat/mshark $1 $2 $3 $4
echo bots; fiat/bots $1 $2 $3 $4
echo mgw; fiat/mgw $1 $2 $3 $4
echo coqui; fiat/coqui $1 $2 $3 $4
echo wlc; fiat/wlc $1 $2 $3 $4
echo kv; fiat/kv $1 $2 $3 $4
echo ceal; fiat/ceal $1 $2 $3 $4
echo mesh; fiat/mesh $1 $2 $3 $4
echo mnz; fiat/mnz $1 $2 $3 $4
echo axo; fiat/axo $1 $2 $3 $4
echo etomic; fiat/etomic $1 $2 $3 $4
echo btch; fiat/btch $1 $2 $3 $4
echo pizza; fiat/pizza $1 $2 $3 $4
echo beer; fiat/beer $1 $2 $3 $4
echo vote2018; fiat/vote2018 $1 $2 $3 $4
echo ninja; fiat/ninja $1 $2 $3 $4
echo oot; fiat/oot $1 $2 $3 $4
echo bntn; fiat/bntn $1 $2 $3 $4
echo chain; fiat/chain $1 $2 $3 $4
echo prlpay; fiat/prlpay $1 $2 $3 $4
args="$@"
./listassetchains | while read chain; do
echo $chain
./komodo-cli --ac_name=$chain $args
done

2
src/fiat/dsec

@ -0,0 +1,2 @@
#!/bin/bash
./komodo-cli -ac_name=DSEC $1 $2 $3 $4 $5 $6

2
src/fiat/eql

@ -0,0 +1,2 @@
#!/bin/bash
./komodo-cli -ac_name=EQL $1 $2 $3 $4 $5 $6

2
src/fiat/glxt

@ -0,0 +1,2 @@
#!/bin/bash
./komodo-cli -ac_name=GLXT $1 $2 $3 $4 $5 $6

2
src/fiat/rfox

@ -0,0 +1,2 @@
#!/bin/bash
./komodo-cli -ac_name=RFOX $1 $2 $3 $4 $5 $6

2
src/fiat/sec

@ -0,0 +1,2 @@
#!/bin/bash
./komodo-cli -ac_name=SEC $1 $2 $3 $4 $5 $6

2
src/fiat/vrsc

@ -0,0 +1,2 @@
#!/bin/bash
./komodo-cli -ac_name=VRSC $1 $2 $3 $4 $5 $6

2
src/fiat/zilla

@ -0,0 +1,2 @@
#!/bin/bash
./komodo-cli -ac_name=ZILLA $1 $2 $3 $4 $5 $6

121
src/importcoin.cpp

@ -0,0 +1,121 @@
#include "crosschain.h"
#include "importcoin.h"
#include "cc/utils.h"
#include "coins.h"
#include "hash.h"
#include "script/cc.h"
#include "primitives/transaction.h"
CTransaction MakeImportCoinTransaction(const TxProof proof, const CTransaction burnTx, const std::vector<CTxOut> payouts)
{
std::vector<uint8_t> payload = E_MARSHAL(ss << EVAL_IMPORTCOIN);
CMutableTransaction mtx;
mtx.vin.push_back(CTxIn(COutPoint(burnTx.GetHash(), 10e8), CScript() << payload));
mtx.vout = payouts;
auto importData = E_MARSHAL(ss << proof; ss << burnTx);
mtx.vout.insert(mtx.vout.begin(), CTxOut(0, CScript() << OP_RETURN << importData));
return CTransaction(mtx);
}
CTxOut MakeBurnOutput(CAmount value, uint32_t targetCCid, std::string targetSymbol, const std::vector<CTxOut> payouts)
{
std::vector<uint8_t> opret = E_MARSHAL(ss << VARINT(targetCCid);
ss << targetSymbol;
ss << SerializeHash(payouts));
return CTxOut(value, CScript() << OP_RETURN << opret);
}
bool UnmarshalImportTx(const CTransaction &importTx, TxProof &proof, CTransaction &burnTx,
std::vector<CTxOut> &payouts)
{
std::vector<uint8_t> vData;
GetOpReturnData(importTx.vout[0].scriptPubKey, vData);
if (importTx.vout.size() < 1) return false;
payouts = std::vector<CTxOut>(importTx.vout.begin()+1, importTx.vout.end());
return importTx.vin.size() == 1 &&
importTx.vin[0].scriptSig == (CScript() << E_MARSHAL(ss << EVAL_IMPORTCOIN)) &&
E_UNMARSHAL(vData, ss >> proof; ss >> burnTx);
}
bool UnmarshalBurnTx(const CTransaction &burnTx, std::string &targetSymbol, uint32_t *targetCCid, uint256 &payoutsHash)
{
std::vector<uint8_t> burnOpret;
if (burnTx.vout.size() == 0) return false;
GetOpReturnData(burnTx.vout[0].scriptPubKey, burnOpret);
return E_UNMARSHAL(burnOpret, ss >> VARINT(*targetCCid);
ss >> targetSymbol;
ss >> payoutsHash);
}
/*
* Required by main
*/
CAmount GetCoinImportValue(const CTransaction &tx)
{
TxProof proof;
CTransaction burnTx;
std::vector<CTxOut> payouts;
if (UnmarshalImportTx(tx, proof, burnTx, payouts)) {
return burnTx.vout.size() ? burnTx.vout[0].nValue : 0;
}
return 0;
}
/*
* CoinImport is different enough from normal script execution that it's not worth
* making all the mods neccesary in the interpreter to do the dispatch correctly.
*/
bool VerifyCoinImport(const CScript& scriptSig, TransactionSignatureChecker& checker, CValidationState &state)
{
auto pc = scriptSig.begin();
opcodetype opcode;
std::vector<uint8_t> evalScript;
auto f = [&] () {
if (!scriptSig.GetOp(pc, opcode, evalScript))
return false;
if (pc != scriptSig.end())
return false;
if (evalScript.size() == 0)
return false;
if (evalScript.begin()[0] != EVAL_IMPORTCOIN)
return false;
// Ok, all looks good so far...
CC *cond = CCNewEval(evalScript);
bool out = checker.CheckEvalCondition(cond);
cc_free(cond);
return out;
};
return f() ? true : state.Invalid(false, 0, "invalid-coin-import");
}
void AddImportTombstone(const CTransaction &importTx, CCoinsViewCache &inputs, int nHeight)
{
uint256 burnHash = importTx.vin[0].prevout.hash;
CCoinsModifier modifier = inputs.ModifyCoins(burnHash);
modifier->nHeight = nHeight;
modifier->nVersion = 1;
modifier->vout.push_back(CTxOut(0, CScript() << OP_0));
}
void RemoveImportTombstone(const CTransaction &importTx, CCoinsViewCache &inputs)
{
uint256 burnHash = importTx.vin[0].prevout.hash;
inputs.ModifyCoins(burnHash)->Clear();
}
int ExistsImportTombstone(const CTransaction &importTx, const CCoinsViewCache &inputs)
{
uint256 burnHash = importTx.vin[0].prevout.hash;
return inputs.HaveCoins(burnHash);
}

28
src/importcoin.h

@ -0,0 +1,28 @@
#ifndef IMPORTCOIN_H
#define IMPORTCOIN_H
#include "cc/eval.h"
#include "coins.h"
#include "primitives/transaction.h"
#include "script/interpreter.h"
#include <cryptoconditions.h>
CAmount GetCoinImportValue(const CTransaction &tx);
CTransaction MakeImportCoinTransaction(const TxProof proof,
const CTransaction burnTx, const std::vector<CTxOut> payouts);
CTxOut MakeBurnOutput(CAmount value, uint32_t targetCCid, std::string targetSymbol, const std::vector<CTxOut> payouts);
bool UnmarshalBurnTx(const CTransaction &burnTx, std::string &targetSymbol, uint32_t *targetCCid, uint256 &payoutsHash);
bool UnmarshalImportTx(const CTransaction &importTx, TxProof &proof, CTransaction &burnTx,
std::vector<CTxOut> &payouts);
bool VerifyCoinImport(const CScript& scriptSig, TransactionSignatureChecker& checker, CValidationState &state);
void AddImportTombstone(const CTransaction &importTx, CCoinsViewCache &inputs, int nHeight);
void RemoveImportTombstone(const CTransaction &importTx, CCoinsViewCache &inputs);
int ExistsImportTombstone(const CTransaction &importTx, const CCoinsViewCache &inputs);
#endif /* IMPORTCOIN_H */

15
src/init.cpp

@ -22,6 +22,7 @@
#include "httpserver.h"
#include "httprpc.h"
#include "key.h"
#include "notarisationdb.h"
#include "main.h"
#include "metrics.h"
#include "miner.h"
@ -499,7 +500,7 @@ std::string HelpMessage(HelpMessageMode mode)
#ifdef ENABLE_MINING
strUsage += HelpMessageGroup(_("Mining options:"));
strUsage += HelpMessageOpt("-gen", strprintf(_("Generate coins (default: %u)"), 0));
strUsage += HelpMessageOpt("-genproclimit=<n>", strprintf(_("Set the number of threads for coin generation if enabled (-1 = all cores, default: %d)"), 1));
strUsage += HelpMessageOpt("-genproclimit=<n>", strprintf(_("Set the number of threads for coin generation if enabled (-1 = all cores, default: %d)"), 0));
strUsage += HelpMessageOpt("-equihashsolver=<name>", _("Specify the Equihash solver to be used if enabled (default: \"default\")"));
strUsage += HelpMessageOpt("-mineraddress=<addr>", _("Send mined coins to a specific single address"));
strUsage += HelpMessageOpt("-minetolocalwallet", strprintf(
@ -1424,11 +1425,14 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler)
delete pcoinsdbview;
delete pcoinscatcher;
delete pblocktree;
delete pnotarisations;
pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex, dbCompression, dbMaxOpenFiles);
pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex);
pcoinscatcher = new CCoinsViewErrorCatcher(pcoinsdbview);
pcoinsTip = new CCoinsViewCache(pcoinscatcher);
pnotarisations = new NotarisationDB(100*1024*1024, false, fReindex);
if (fReindex) {
pblocktree->WriteReindexing(true);
@ -1763,19 +1767,14 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler)
StartNode(threadGroup, scheduler);
// Monitor the chain, and alert if we get blocks much quicker or slower than expected
int64_t nPowTargetSpacing = Params().GetConsensus().nPowTargetSpacing;
CScheduler::Function f = boost::bind(&PartitionCheck, &IsInitialBlockDownload,
boost::ref(cs_main), boost::cref(pindexBestHeader), nPowTargetSpacing);
scheduler.scheduleEvery(f, nPowTargetSpacing);
#ifdef ENABLE_MINING
// Generate coins in the background
#ifdef ENABLE_WALLET
if (pwalletMain || !GetArg("-mineraddress", "").empty())
GenerateBitcoins(GetBoolArg("-gen", false), pwalletMain, GetArg("-genproclimit", 1));
GenerateBitcoins(GetBoolArg("-gen", false), pwalletMain, GetArg("-genproclimit", 0));
#else
GenerateBitcoins(GetBoolArg("-gen", false), GetArg("-genproclimit", 1));
GenerateBitcoins(GetBoolArg("-gen", false), GetArg("-genproclimit", 0));
#endif
#endif

59
src/komodo.h

@ -113,7 +113,7 @@ int32_t komodo_parsestatefile(struct komodo_state *sp,FILE *fp,char *symbol,char
if ( fread(&MoMdepth,1,sizeof(MoMdepth),fp) != sizeof(MoMdepth) )
errs++;
if ( 1 && ASSETCHAINS_SYMBOL[0] != 0 && sp != 0 )
printf("%s load[%s.%d -> %s] NOTARIZED %d %s MoM.%s %d\n",ASSETCHAINS_SYMBOL,symbol,sp->NUM_NPOINTS,dest,notarized_height,notarized_hash.ToString().c_str(),MoM.ToString().c_str(),MoMdepth);
printf("%s load[%s.%d -> %s] NOTARIZED %d %s MoM.%s %d CCid.%u\n",ASSETCHAINS_SYMBOL,symbol,sp->NUM_NPOINTS,dest,notarized_height,notarized_hash.ToString().c_str(),MoM.ToString().c_str(),MoMdepth&0xffff,(MoMdepth>>16)&0xffff);
}
else
{
@ -201,8 +201,7 @@ int32_t komodo_parsestatefile(struct komodo_state *sp,FILE *fp,char *symbol,char
komodo_eventadd_pricefeed(sp,symbol,ht,pvals,numpvals);
//printf("load pvals ht.%d numpvals.%d\n",ht,numpvals);
} else printf("error loading pvals[%d]\n",numpvals);
}
else printf("[%s] %s illegal func.(%d %c)\n",ASSETCHAINS_SYMBOL,symbol,func,func);
} // else printf("[%s] %s illegal func.(%d %c)\n",ASSETCHAINS_SYMBOL,symbol,func,func);
return(func);
} else return(-1);
}
@ -259,7 +258,7 @@ int32_t komodo_parsestatefiledata(struct komodo_state *sp,uint8_t *filedata,long
if ( memread(&MoMdepth,sizeof(MoMdepth),filedata,&fpos,datalen) != sizeof(MoMdepth) )
errs++;
if ( 1 && ASSETCHAINS_SYMBOL[0] != 0 && sp != 0 )
printf("%s load[%s.%d -> %s] NOTARIZED %d %s MoM.%s %d\n",ASSETCHAINS_SYMBOL,symbol,sp->NUM_NPOINTS,dest,notarized_height,notarized_hash.ToString().c_str(),MoM.ToString().c_str(),MoMdepth);
printf("%s load[%s.%d -> %s] NOTARIZED %d %s MoM.%s %d CCid.%u\n",ASSETCHAINS_SYMBOL,symbol,sp->NUM_NPOINTS,dest,notarized_height,notarized_hash.ToString().c_str(),MoM.ToString().c_str(),MoMdepth&0xffff,(MoMdepth>>16)&0xffff);
}
else
{
@ -312,7 +311,7 @@ int32_t komodo_parsestatefiledata(struct komodo_state *sp,uint8_t *filedata,long
{
if ( memread(opret,olen,filedata,&fpos,datalen) != olen )
errs++;
if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 && matched != 0 )
if ( 1 && ASSETCHAINS_SYMBOL[0] != 0 && matched != 0 )
{
int32_t i; for (i=0; i<olen; i++)
printf("%02x",opret[i]);
@ -342,8 +341,7 @@ int32_t komodo_parsestatefiledata(struct komodo_state *sp,uint8_t *filedata,long
komodo_eventadd_pricefeed(sp,symbol,ht,pvals,numpvals);
//printf("load pvals ht.%d numpvals.%d\n",ht,numpvals);
} else printf("error loading pvals[%d]\n",numpvals);
}
else printf("[%s] %s illegal func.(%d %c)\n",ASSETCHAINS_SYMBOL,symbol,func,func);
} // else printf("[%s] %s illegal func.(%d %c)\n",ASSETCHAINS_SYMBOL,symbol,func,func);
*fposp = fpos;
return(func);
}
@ -429,7 +427,7 @@ void komodo_stateupdate(int32_t height,uint8_t notarypubs[][33],uint8_t numnotar
errs++;
if ( fwrite(opretbuf,1,olen,fp) != olen )
errs++;
//printf("ht.%d R opret[%d] sp.%p\n",height,olen,sp);
printf("create ht.%d R opret[%d] sp.%p\n",height,olen,sp);
//komodo_opreturn(height,opretvalue,opretbuf,olen,txhash,vout);
komodo_eventadd_opreturn(sp,symbol,height,txhash,opretvalue,vout,opretbuf,olen);
}
@ -482,7 +480,7 @@ void komodo_stateupdate(int32_t height,uint8_t notarypubs[][33],uint8_t numnotar
//printf("ht.%d func N ht.%d errs.%d\n",height,NOTARIZED_HEIGHT,errs);
if ( sp != 0 )
{
if ( sp->MoMdepth > 0 && sp->MoM != zero )
if ( sp->MoMdepth != 0 && sp->MoM != zero )
fputc('M',fp);
else fputc('N',fp);
if ( fwrite(&height,1,sizeof(height),fp) != sizeof(height) )
@ -493,7 +491,7 @@ void komodo_stateupdate(int32_t height,uint8_t notarypubs[][33],uint8_t numnotar
errs++;
if ( fwrite(&sp->NOTARIZED_DESTTXID,1,sizeof(sp->NOTARIZED_DESTTXID),fp) != sizeof(sp->NOTARIZED_DESTTXID) )
errs++;
if ( sp->MoMdepth > 0 && sp->MoM != zero )
if ( sp->MoMdepth != 0 && sp->MoM != zero )
{
if ( fwrite(&sp->MoM,1,sizeof(sp->MoM),fp) != sizeof(sp->MoM) )
errs++;
@ -540,7 +538,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr
return(-1);
if ( scriptlen == 35 && scriptbuf[0] == 33 && scriptbuf[34] == 0xac )
{
if ( i == 0 && j == 0 && memcmp(NOTARY_PUBKEY33,scriptbuf+1,33) == 0 && NOTARY_PUBKEY33[0] != 0 )
if ( i == 0 && j == 0 && memcmp(NOTARY_PUBKEY33,scriptbuf+1,33) == 0 && IS_KOMODO_NOTARY != 0 )
{
printf("%s KOMODO_LASTMINED.%d -> %d\n",ASSETCHAINS_SYMBOL,KOMODO_LASTMINED,height);
prevKOMODO_LASTMINED = KOMODO_LASTMINED;
@ -600,14 +598,18 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr
}
else
{
if ( scriptbuf[len] == 'K' )
{
fprintf(stderr,"i.%d j.%d KV OPRET len.%d %.8f\n",i,j,opretlen,dstr(value));
komodo_stateupdate(height,0,0,0,txhash,0,0,0,0,0,0,value,&scriptbuf[len],opretlen,j,zero,0);
return(-1);
}
if ( strcmp(ASSETCHAINS_SYMBOL,(char *)&scriptbuf[len+32*2+4]) == 0 )
matched = 1;
}
offset = 32 * (1 + matched) + 4;
nameoffset = (int32_t)strlen((char *)&scriptbuf[len+offset]);
if ( nameoffset == 2 )
nameoffset += 2;
else nameoffset++;
nameoffset++;
memset(&ccdata,0,sizeof(ccdata));
strncpy(ccdata.symbol,(char *)&scriptbuf[len+offset],sizeof(ccdata.symbol));
if ( j == 1 && opretlen >= len+offset-opoffset )
@ -637,16 +639,18 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr
ccdata.MoMdata.notarized_height = *notarizedheightp;
ccdata.MoMdata.height = height;
ccdata.MoMdata.txi = i;
//printf("nameoffset.%d len.%d + 36 %d vs opretlen.%d\n",nameoffset,len,len+36,opretlen);
//printf("nameoffset.%d len.%d + 36 %d opoffset.%d vs opretlen.%d\n",nameoffset,len,len+36,opoffset,opretlen);
if ( len+36-opoffset <= opretlen )
{
len += iguana_rwbignum(0,&scriptbuf[len],32,(uint8_t *)&MoM);
len += iguana_rwnum(0,&scriptbuf[len],sizeof(MoMdepth),(uint8_t *)&MoMdepth);
ccdata.MoMdata.MoM = MoM;
ccdata.MoMdata.MoMdepth = MoMdepth;
ccdata.MoMdata.MoMdepth = MoMdepth & 0xffff;
if ( len+sizeof(ccdata.CCid)-opoffset <= opretlen )
{
len += iguana_rwnum(0,&scriptbuf[len],sizeof(ccdata.CCid),(uint8_t *)&ccdata.CCid);
//if ( ((MoMdepth>>16) & 0xffff) != (ccdata.CCid & 0xffff) )
// fprintf(stderr,"%s CCid mismatch %u != %u\n",ASSETCHAINS_SYMBOL,((MoMdepth>>16) & 0xffff),(ccdata.CCid & 0xffff));
ccdata.len = sizeof(ccdata.CCid);
if ( ASSETCHAINS_SYMBOL[0] != 0 )
{
@ -672,7 +676,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr
} else ccdata.len = MoMoMdata.len = 0;
}
}
if ( MoM == zero || MoMdepth > *notarizedheightp || MoMdepth < 0 )
if ( MoM == zero || (MoMdepth&0xffff) > *notarizedheightp || (MoMdepth&0xffff) < 0 )
{
memset(&MoM,0,sizeof(MoM));
MoMdepth = 0;
@ -681,7 +685,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr
{
komodo_rwccdata(ASSETCHAINS_SYMBOL,1,&ccdata,&MoMoMdata);
if ( matched != 0 )
printf("[%s] matched.%d VALID (%s) MoM.%s [%d]\n",ASSETCHAINS_SYMBOL,matched,ccdata.symbol,MoM.ToString().c_str(),MoMdepth);
printf("[%s] matched.%d VALID (%s) MoM.%s [%d] CCid.%u\n",ASSETCHAINS_SYMBOL,matched,ccdata.symbol,MoM.ToString().c_str(),MoMdepth&0xffff,(MoMdepth>>16)&0xffff);
}
if ( MoMoMdata.pairs != 0 )
free(MoMoMdata.pairs);
@ -695,8 +699,11 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr
sp->NOTARIZED_HEIGHT = *notarizedheightp;
sp->NOTARIZED_HASH = srchash;
sp->NOTARIZED_DESTTXID = desttxid;
sp->MoM = MoM;
sp->MoMdepth = MoMdepth;
if ( MoM != zero && (MoMdepth&0xffff) > 0 )
{
sp->MoM = MoM;
sp->MoMdepth = MoMdepth;
}
komodo_stateupdate(height,0,0,0,zero,0,0,0,0,0,0,0,0,0,0,sp->MoM,sp->MoMdepth);
if ( ASSETCHAINS_SYMBOL[0] != 0 )
printf("[%s] ht.%d NOTARIZED.%d %s.%s %sTXID.%s lens.(%d %d) MoM.%s %d\n",ASSETCHAINS_SYMBOL,height,*notarizedheightp,ASSETCHAINS_SYMBOL[0]==0?"KMD":ASSETCHAINS_SYMBOL,srchash.ToString().c_str(),ASSETCHAINS_SYMBOL[0]==0?"BTC":"KMD",desttxid.ToString().c_str(),opretlen,len,sp->MoM.ToString().c_str(),sp->MoMdepth);
@ -816,7 +823,7 @@ void komodo_connectblock(CBlockIndex *pindex,CBlock& block)
komodo_event_rewind(sp,symbol,pindex->nHeight);
komodo_stateupdate(pindex->nHeight,0,0,0,zero,0,0,0,0,-pindex->nHeight,pindex->nTime,0,0,0,0,zero,0);
}
komodo_currentheight_set(chainActive.Tip()->nHeight);
komodo_currentheight_set(chainActive.LastTip()->nHeight);
if ( pindex != 0 )
{
height = pindex->nHeight;
@ -872,7 +879,7 @@ void komodo_connectblock(CBlockIndex *pindex,CBlock& block)
}
notarized = 1;
}
if ( NOTARY_PUBKEY33[0] != 0 && ASSETCHAINS_SYMBOL[0] == 0 )
if ( IS_KOMODO_NOTARY != 0 && ASSETCHAINS_SYMBOL[0] == 0 )
printf("(tx.%d: ",i);
for (j=0; j<numvouts; j++)
{
@ -890,7 +897,7 @@ void komodo_connectblock(CBlockIndex *pindex,CBlock& block)
}
}
}*/
if ( NOTARY_PUBKEY33[0] != 0 && ASSETCHAINS_SYMBOL[0] == 0 )
if ( IS_KOMODO_NOTARY != 0 && ASSETCHAINS_SYMBOL[0] == 0 )
printf("%.8f ",dstr(block.vtx[i].vout[j].nValue));
len = block.vtx[i].vout[j].scriptPubKey.size();
if ( len >= sizeof(uint32_t) && len <= sizeof(scriptbuf) )
@ -900,7 +907,7 @@ void komodo_connectblock(CBlockIndex *pindex,CBlock& block)
#else
memcpy(scriptbuf,(uint8_t *)&block.vtx[i].vout[j].scriptPubKey[0],len);
#endif
notaryid = komodo_voutupdate(&isratification,notaryid,scriptbuf,len,height,txhash,i,j,&voutmask,&specialtx,&notarizedheight,(uint64_t)block.vtx[i].vout[j].nValue,notarized,signedmask,(uint32_t)chainActive.Tip()->GetBlockTime());
notaryid = komodo_voutupdate(&isratification,notaryid,scriptbuf,len,height,txhash,i,j,&voutmask,&specialtx,&notarizedheight,(uint64_t)block.vtx[i].vout[j].nValue,notarized,signedmask,(uint32_t)chainActive.LastTip()->GetBlockTime());
if ( 0 && i > 0 )
{
for (k=0; k<len; k++)
@ -909,7 +916,7 @@ void komodo_connectblock(CBlockIndex *pindex,CBlock& block)
}
}
}
if ( NOTARY_PUBKEY33[0] != 0 && ASSETCHAINS_SYMBOL[0] == 0 )
if ( IS_KOMODO_NOTARY != 0 && ASSETCHAINS_SYMBOL[0] == 0 )
printf(") ");
if ( 0 && ASSETCHAINS_SYMBOL[0] == 0 )
printf("[%s] ht.%d txi.%d signedmask.%llx numvins.%d numvouts.%d notarized.%d special.%d isratification.%d\n",ASSETCHAINS_SYMBOL,height,i,(long long)signedmask,numvins,numvouts,notarized,specialtx,isratification);
@ -952,7 +959,7 @@ void komodo_connectblock(CBlockIndex *pindex,CBlock& block)
}
}
}
if ( NOTARY_PUBKEY33[0] != 0 && ASSETCHAINS_SYMBOL[0] == 0 )
if ( IS_KOMODO_NOTARY != 0 && ASSETCHAINS_SYMBOL[0] == 0 )
printf("%s ht.%d\n",ASSETCHAINS_SYMBOL[0] == 0 ? "KMD" : ASSETCHAINS_SYMBOL,height);
if ( pindex->nHeight == hwmheight )
komodo_stateupdate(height,0,0,0,zero,0,0,0,0,height,(uint32_t)pindex->nTime,0,0,0,0,zero,0);

517
src/komodo_bitcoind.h

@ -568,7 +568,7 @@ uint32_t komodo_txtime(uint64_t *valuep,uint256 hash, int32_t n, char *destaddr)
#endif
hashBlock, true))
{
fprintf(stderr,"ERROR: %s/v%d locktime.%u\n",hash.ToString().c_str(),n,(uint32_t)tx.nLockTime);
//fprintf(stderr,"ERROR: %s/v%d locktime.%u\n",hash.ToString().c_str(),n,(uint32_t)tx.nLockTime);
return(0);
}
//fprintf(stderr,"%s/v%d locktime.%u\n",hash.ToString().c_str(),n,(uint32_t)tx.nLockTime);
@ -581,6 +581,56 @@ uint32_t komodo_txtime(uint64_t *valuep,uint256 hash, int32_t n, char *destaddr)
return(tx.nLockTime);
}
uint32_t komodo_txtime2(uint64_t *valuep,uint256 hash,int32_t n,char *destaddr)
{
CTxDestination address; CBlockIndex *pindex; CTransaction tx; uint256 hashBlock; uint32_t txtime = 0;
*valuep = 0;
if (!GetTransaction(hash, tx,
#ifndef KOMODO_ZCASH
Params().GetConsensus(),
#endif
hashBlock, true))
{
//fprintf(stderr,"ERROR: %s/v%d locktime.%u\n",hash.ToString().c_str(),n,(uint32_t)tx.nLockTime);
return(0);
}
if ( (pindex= mapBlockIndex[hashBlock]) != 0 )
txtime = pindex->nTime;
else txtime = tx.nLockTime;
//fprintf(stderr,"%s/v%d locktime.%u\n",hash.ToString().c_str(),n,(uint32_t)tx.nLockTime);
if ( n < tx.vout.size() )
{
*valuep = tx.vout[n].nValue;
if (ExtractDestination(tx.vout[n].scriptPubKey, address))
strcpy(destaddr,CBitcoinAddress(address).ToString().c_str());
}
return(txtime);
}
int32_t komodo_isPoS(CBlock *pblock)
{
int32_t n,vout; uint32_t txtime; uint64_t value; char voutaddr[64],destaddr[64]; CTxDestination voutaddress; uint256 txid;
if ( ASSETCHAINS_STAKED != 0 )
{
if ( (n= pblock->vtx.size()) > 1 && pblock->vtx[n-1].vin.size() == 1 && pblock->vtx[n-1].vout.size() == 1 )
{
txid = pblock->vtx[n-1].vin[0].prevout.hash;
vout = pblock->vtx[n-1].vin[0].prevout.n;
txtime = komodo_txtime(&value,txid,vout,destaddr);
if ( ExtractDestination(pblock->vtx[n-1].vout[0].scriptPubKey,voutaddress) )
{
strcpy(voutaddr,CBitcoinAddress(voutaddress).ToString().c_str());
if ( strcmp(destaddr,voutaddr) == 0 && pblock->vtx[n-1].vout[0].nValue == value )
{
//fprintf(stderr,"is PoS block!\n");
return(1);
}
}
}
}
return(0);
}
void komodo_disconnect(CBlockIndex *pindex,CBlock& block)
{
char symbol[KOMODO_ASSETCHAIN_MAXLEN],dest[KOMODO_ASSETCHAIN_MAXLEN]; struct komodo_state *sp;
@ -703,20 +753,20 @@ int32_t komodo_blockload(CBlock& block,CBlockIndex *pindex)
uint32_t komodo_chainactive_timestamp()
{
if ( chainActive.Tip() != 0 )
return((uint32_t)chainActive.Tip()->GetBlockTime());
if ( chainActive.LastTip() != 0 )
return((uint32_t)chainActive.LastTip()->GetBlockTime());
else return(0);
}
CBlockIndex *komodo_chainactive(int32_t height)
{
if ( chainActive.Tip() != 0 )
if ( chainActive.LastTip() != 0 )
{
if ( height <= chainActive.Tip()->nHeight )
if ( height <= chainActive.LastTip()->nHeight )
return(chainActive[height]);
// else fprintf(stderr,"komodo_chainactive height %d > active.%d\n",height,chainActive.Tip()->nHeight);
// else fprintf(stderr,"komodo_chainactive height %d > active.%d\n",height,chainActive.LastTip()->nHeight);
}
//fprintf(stderr,"komodo_chainactive null chainActive.Tip() height %d\n",height);
//fprintf(stderr,"komodo_chainactive null chainActive.LastTip() height %d\n",height);
return(0);
}
@ -934,7 +984,7 @@ int32_t komodo_MoM(int32_t *notarized_heightp,uint256 *MoMp,uint256 *kmdtxidp,in
memset(MoMp,0,sizeof(*MoMp));
memset(kmdtxidp,0,sizeof(*kmdtxidp));
*notarized_heightp = 0;
if ( depth > 0 && notarized_ht > 0 && nHeight > notarized_ht-depth && nHeight <= notarized_ht )
if ( depth != 0 && notarized_ht > 0 && nHeight > notarized_ht-depth && nHeight <= notarized_ht )
{
*MoMp = MoM;
*notarized_heightp = notarized_ht;
@ -946,7 +996,7 @@ int32_t komodo_MoM(int32_t *notarized_heightp,uint256 *MoMp,uint256 *kmdtxidp,in
int32_t komodo_checkpoint(int32_t *notarized_heightp,int32_t nHeight,uint256 hash)
{
int32_t notarized_height,MoMdepth; uint256 MoM,notarized_hash,notarized_desttxid; CBlockIndex *notary,*pindex;
if ( (pindex= chainActive.Tip()) == 0 )
if ( (pindex= chainActive.LastTip()) == 0 )
return(-1);
notarized_height = komodo_notarizeddata(pindex->nHeight,&notarized_hash,&notarized_desttxid);
*notarized_heightp = notarized_height;
@ -988,7 +1038,7 @@ uint32_t komodo_interest_args(uint32_t *txheighttimep,int32_t *txheightp,uint32_
*valuep = tx.vout[n].nValue;
*txheightp = pindex->nHeight;
*txheighttimep = pindex->nTime;
if ( *tiptimep == 0 && (tipindex= chainActive.Tip()) != 0 )
if ( *tiptimep == 0 && (tipindex= chainActive.LastTip()) != 0 )
*tiptimep = (uint32_t)tipindex->nTime;
locktime = tx.nLockTime;
//fprintf(stderr,"tx locktime.%u %.8f height.%d | tiptime.%u\n",locktime,(double)*valuep/COIN,*txheightp,*tiptimep);
@ -1021,30 +1071,29 @@ int32_t komodo_isrealtime(int32_t *kmdheightp)
if ( (sp= komodo_stateptrget((char *)"KMD")) != 0 )
*kmdheightp = sp->CURRENT_HEIGHT;
else *kmdheightp = 0;
if ( (pindex= chainActive.Tip()) != 0 && pindex->nHeight >= (int32_t)komodo_longestchain() )
if ( (pindex= chainActive.LastTip()) != 0 && pindex->nHeight >= (int32_t)komodo_longestchain() )
return(1);
else return(0);
}
int32_t komodo_validate_interest(const CTransaction &tx,int32_t txheight,uint32_t nTime,int32_t dispflag)
int32_t komodo_validate_interest(const CTransaction &tx,int32_t txheight,uint32_t cmptime,int32_t dispflag)
{
uint32_t cmptime = nTime;
if ( KOMODO_REWIND == 0 && ASSETCHAINS_SYMBOL[0] == 0 && (int64_t)tx.nLockTime >= LOCKTIME_THRESHOLD ) //1473793441 )
{
if ( txheight > 246748 )
{
if ( txheight < 247205 )
cmptime -= 16000;
if ( (int64_t)tx.nLockTime < cmptime-3600 )
if ( (int64_t)tx.nLockTime < cmptime-KOMODO_MAXMEMPOOLTIME )
{
if ( tx.nLockTime != 1477258935 && dispflag != 0 )
{
fprintf(stderr,"komodo_validate_interest.%d reject.%d [%d] locktime %u cmp2.%u\n",dispflag,txheight,(int32_t)(tx.nLockTime - (cmptime-3600)),(uint32_t)tx.nLockTime,cmptime);
fprintf(stderr,"komodo_validate_interest.%d reject.%d [%d] locktime %u cmp2.%u\n",dispflag,txheight,(int32_t)(tx.nLockTime - (cmptime-KOMODO_MAXMEMPOOLTIME)),(uint32_t)tx.nLockTime,cmptime);
}
return(-1);
}
if ( 0 && dispflag != 0 )
fprintf(stderr,"validateinterest.%d accept.%d [%d] locktime %u cmp2.%u\n",dispflag,(int32_t)txheight,(int32_t)(tx.nLockTime - (cmptime-3600)),(int32_t)tx.nLockTime,cmptime);
fprintf(stderr,"validateinterest.%d accept.%d [%d] locktime %u cmp2.%u\n",dispflag,(int32_t)txheight,(int32_t)(tx.nLockTime - (cmptime-KOMODO_MAXMEMPOOLTIME)),(int32_t)tx.nLockTime,cmptime);
}
}
return(0);
@ -1057,9 +1106,8 @@ int32_t komodo_validate_interest(const CTransaction &tx,int32_t txheight,uint32_
commission must be in coinbase.vout[1] and must be >= 10000 sats
PoS stake must be without txfee and in the last tx in the block at vout[0]
PoW mining on PoS chain must solve a harder diff that adjusts, but never less than KOMODO_POWMINMULT
*/
#define KOMODO_POWMINMULT 16
//#define KOMODO_POWMINMULT 16
uint64_t komodo_commission(const CBlock *pblock)
{
@ -1082,114 +1130,244 @@ uint64_t komodo_commission(const CBlock *pblock)
return(commission);
}
uint32_t komodo_segid32(char *coinaddr)
{
bits256 addrhash;
vcalc_sha256(0,(uint8_t *)&addrhash,(uint8_t *)coinaddr,(int32_t)strlen(coinaddr));
return(addrhash.uints[0]);
}
int8_t komodo_segid(int32_t height)
{
CTxDestination voutaddress; CBlock block; CBlockIndex *pindex; uint64_t value; uint32_t txtime; char voutaddr[64],destaddr[64]; int32_t txn_count,vout; uint256 txid; int8_t segid = -1;
if ( height > 0 && (pindex= komodo_chainactive(height)) != 0 )
{
if ( komodo_blockload(block,pindex) == 0 )
{
txn_count = block.vtx.size();
if ( txn_count > 1 && block.vtx[txn_count-1].vin.size() == 1 && block.vtx[txn_count-1].vout.size() == 1 )
{
txid = block.vtx[txn_count-1].vin[0].prevout.hash;
vout = block.vtx[txn_count-1].vin[0].prevout.n;
txtime = komodo_txtime(&value,txid,vout,destaddr);
if ( ExtractDestination(block.vtx[txn_count-1].vout[0].scriptPubKey,voutaddress) )
{
strcpy(voutaddr,CBitcoinAddress(voutaddress).ToString().c_str());
if ( strcmp(destaddr,voutaddr) == 0 && block.vtx[txn_count-1].vout[0].nValue == value )
{
segid = komodo_segid32(voutaddr) & 0x3f;
}
} else fprintf(stderr,"komodo_segid ht.%d couldnt extract voutaddress\n",height);
}
}
}
return(segid);
}
int32_t komodo_segids(uint8_t *hashbuf,int32_t height,int32_t n)
{
static uint8_t prevhashbuf[100]; static int32_t prevheight;
int32_t i;
if ( height == prevheight && n == 100 )
memcpy(hashbuf,prevhashbuf,100);
else
{
memset(hashbuf,0xff,n);
for (i=0; i<n; i++)
{
hashbuf[i] = (uint8_t)komodo_segid(height+i);
//fprintf(stderr,"%02x ",hashbuf[i]);
}
if ( n == 100 )
{
memcpy(prevhashbuf,hashbuf,100);
prevheight = height;
//fprintf(stderr,"prevsegids.%d\n",height+n);
}
}
}
uint32_t komodo_stakehash(uint256 *hashp,char *address,uint8_t *hashbuf,uint256 txid,int32_t vout)
{
bits256 addrhash;
vcalc_sha256(0,(uint8_t *)&addrhash,(uint8_t *)address,(int32_t)strlen(address));
memcpy(&hashbuf[100],&addrhash,sizeof(addrhash));
memcpy(&hashbuf[100+sizeof(addrhash)],&txid,sizeof(txid));
memcpy(&hashbuf[100+sizeof(addrhash)+sizeof(txid)],&vout,sizeof(vout));
vcalc_sha256(0,(uint8_t *)hashp,hashbuf,100 + (int32_t)sizeof(uint256)*2 + sizeof(vout));
return(addrhash.uints[0]);
}
uint32_t komodo_stake(int32_t validateflag,arith_uint256 bnTarget,int32_t nHeight,uint256 txid,int32_t vout,uint32_t blocktime,uint32_t prevtime,char *destaddr)
{
CBlockIndex *pindex; uint8_t hashbuf[128]; char address[64]; bits256 addrhash; arith_uint256 hashval; uint256 hash,pasthash; int64_t diff=0; int32_t segid,minage,i,iter=0; uint32_t txtime,winner = 0;
uint64_t value,coinage,supply = komodo_current_supply(nHeight);
txtime = komodo_txtime(&value,txid,vout,address);
if ( blocktime < prevtime+57 )
blocktime = prevtime+57;
bool fNegative,fOverflow; uint8_t hashbuf[256]; char address[64]; bits256 addrhash; arith_uint256 hashval,mindiff,ratio,coinage256; uint256 hash,pasthash; int32_t diff=0,segid,minage,i,iter=0; uint32_t txtime,segid32,winner = 0 ; uint64_t value,coinage;
txtime = komodo_txtime2(&value,txid,vout,address);
if ( validateflag == 0 )
{
//fprintf(stderr,"blocktime.%u -> ",blocktime);
if ( blocktime < prevtime+3 )
blocktime = prevtime+3;
if ( blocktime < GetAdjustedTime()-60 )
blocktime = GetAdjustedTime()+30;
//fprintf(stderr,"blocktime.%u txtime.%u\n",blocktime,txtime);
}
if ( value == 0 || txtime == 0 || blocktime == 0 || prevtime == 0 )
{
//fprintf(stderr,"komodo_stake null %.8f %u %u %u\n",dstr(value),txtime,blocktime,prevtime);
return(0);
if ( (minage= nHeight*3) > 6000 )
}
if ( value < SATOSHIDEN )
return(0);
value /= SATOSHIDEN;
mindiff.SetCompact(KOMODO_MINDIFF_NBITS,&fNegative,&fOverflow);
ratio = (mindiff / bnTarget);
if ( (minage= nHeight*3) > 6000 ) // about 100 blocks
minage = 6000;
if ( blocktime > txtime+minage && (pindex= komodo_chainactive(nHeight>200?nHeight-200:1)) != 0 )
{
vcalc_sha256(0,(uint8_t *)&addrhash,(uint8_t *)address,(int32_t)strlen(address));
segid = ((nHeight + addrhash.uints[0]) & 0x3f);
pasthash = pindex->GetBlockHash();
memcpy(hashbuf,&pasthash,sizeof(pasthash));
memcpy(&hashbuf[sizeof(pasthash)],&addrhash,sizeof(addrhash));
vcalc_sha256(0,(uint8_t *)&hash,hashbuf,(int32_t)sizeof(uint256)*2);
//fprintf(stderr,"(%s) vs. (%s) %s %.8f txtime.%u\n",address,destaddr,hash.ToString().c_str(),dstr(value),txtime);
for (iter=0; iter<3600; iter++)
komodo_segids(hashbuf,nHeight-101,100);
segid32 = komodo_stakehash(&hash,address,hashbuf,txid,vout);
segid = ((nHeight + segid32) & 0x3f);
/*vcalc_sha256(0,(uint8_t *)&addrhash,(uint8_t *)address,(int32_t)strlen(address));
segid = ((nHeight + addrhash.uints[0]) & 0x3f);
komodo_segids(hashbuf,nHeight-101,100);
memcpy(&hashbuf[100],&addrhash,sizeof(addrhash));
memcpy(&hashbuf[100+sizeof(addrhash)],&txid,sizeof(txid));
memcpy(&hashbuf[100+sizeof(addrhash)+sizeof(txid)],&vout,sizeof(vout));
vcalc_sha256(0,(uint8_t *)&hash,hashbuf,100 + (int32_t)sizeof(uint256)*2 + sizeof(vout));*/
for (iter=0; iter<600; iter++)
{
if ( blocktime+iter+segid*2 < txtime+minage )
continue;
diff = (iter + blocktime - txtime - minage);
if ( diff < 0 )
diff = 60;
else if ( diff > 3600*24*30 )
{
diff = (iter + blocktime - txtime - minage);
if ( diff > 3600*24 )
break;
coinage = (value * diff) * ((diff >> 16) + 1);
hashval = arith_uint256(supply * 64) * (UintToArith256(hash) / arith_uint256(coinage+1));
if ( hashval <= bnTarget )
{
winner = 1;
if ( validateflag == 0 )
{
blocktime += iter;
blocktime += segid * 2;
}
break;
}
if ( validateflag != 0 )
//printf("diff.%d (iter.%d blocktime.%u txtime.%u minage.%d)\n",(int32_t)diff,iter,blocktime,txtime,(int32_t)minage);
diff = 3600*24*30;
}
if ( iter > 0 )
diff += segid*2;
coinage = (value * diff);
if ( blocktime+iter+segid*2 > prevtime+480 )
coinage *= ((blocktime+iter+segid*2) - (prevtime+400));
//if ( nHeight >= 2500 && blocktime+iter+segid*2 > prevtime+180 )
// coinage *= ((blocktime+iter+segid*2) - (prevtime+60));
coinage256 = arith_uint256(coinage+1);
hashval = ratio * (UintToArith256(hash) / coinage256);
//if ( nHeight >= 900 && nHeight < 916 )
// hashval = (hashval / coinage256);
if ( hashval <= bnTarget )
{
winner = 1;
if ( validateflag == 0 )
{
for (i=31; i>=24; i--)
fprintf(stderr,"%02x",((uint8_t *)&hashval)[i]);
fprintf(stderr," vs target ");
for (i=31; i>=24; i--)
fprintf(stderr,"%02x",((uint8_t *)&bnTarget)[i]);
fprintf(stderr," segid.%d iter.%d winner.%d coinage.%llu %d ht.%d gap.%d %.8f diff.%d\n",segid,iter,winner,(long long)coinage,(int32_t)(blocktime - txtime),nHeight,(int32_t)(blocktime - prevtime),dstr(value),(int32_t)diff);
break;
//fprintf(stderr,"winner blocktime.%u iter.%d segid.%d\n",blocktime,iter,segid);
blocktime += iter;
blocktime += segid * 2;
}
break;
}
//fprintf(stderr,"iterated until i.%d winner.%d\n",i,winner);
if ( 0 )
if ( validateflag != 0 )
{
for (i=31; i>=24; i--)
/*for (i=31; i>=24; i--)
fprintf(stderr,"%02x",((uint8_t *)&hashval)[i]);
fprintf(stderr," vs ");
for (i=31; i>=24; i--)
fprintf(stderr,"%02x",((uint8_t *)&bnTarget)[i]);
fprintf(stderr," segid.%d iter.%d winner.%d coinage.%llu %d ht.%d t.%u %.8f diff.%d\n",segid,iter,winner,(long long)coinage,(int32_t)(blocktime - txtime),nHeight,blocktime,dstr(value),(int32_t)diff);
fprintf(stderr," segid.%d iter.%d winner.%d coinage.%llu %d ht.%d t.%u v%d diff.%d\n",segid,iter,winner,(long long)coinage,(int32_t)(blocktime - txtime),nHeight,blocktime,(int32_t)value,(int32_t)diff);*/
break;
}
}
if ( nHeight < 2 )
//fprintf(stderr,"iterated until i.%d winner.%d\n",i,winner);
if ( 0 && validateflag != 0 )
{
for (i=31; i>=24; i--)
fprintf(stderr,"%02x",((uint8_t *)&hashval)[i]);
fprintf(stderr," vs ");
for (i=31; i>=24; i--)
fprintf(stderr,"%02x",((uint8_t *)&bnTarget)[i]);
fprintf(stderr," segid.%d iter.%d winner.%d coinage.%llu %d ht.%d t.%u v%d diff.%d ht.%d\n",segid,iter,winner,(long long)coinage,(int32_t)(blocktime - txtime),nHeight,blocktime,(int32_t)value,(int32_t)diff,nHeight);
}
if ( nHeight < 10 )
return(blocktime);
return(blocktime * winner);
}
arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t height,int32_t goalperc)
{
CBlockIndex *pindex; arith_uint256 bnTarget,hashval,sum,ave; bool fNegative,fOverflow; int32_t i,n,ht,percPoS,diff,val;
int32_t oldflag = 0;
CBlockIndex *pindex; arith_uint256 easydiff,bnTarget,hashval,sum,ave; bool fNegative,fOverflow; int32_t i,n,m,ht,percPoS,diff,val;
*percPoSp = percPoS = 0;
if ( height < 3 )
if ( height <= 10 || (ASSETCHAINS_STAKED == 100 && height <= 100) )
return(target);
sum = arith_uint256(0);
ave = sum;
for (i=n=0; i<100; i++)
easydiff.SetCompact(KOMODO_MINDIFF_NBITS,&fNegative,&fOverflow);
for (i=n=m=0; i<100; i++)
{
ht = height - 100 + i;
if ( ht <= 1 )
continue;
if ( (pindex= komodo_chainactive(ht)) != 0 )
{
if ( komodo_segid(ht) >= 0 )
{
n++;
percPoS++;
if ( ASSETCHAINS_STAKED < 100 )
fprintf(stderr,"0");
}
else
{
if ( ASSETCHAINS_STAKED < 100 )
fprintf(stderr,"1");
sum += UintToArith256(pindex->GetBlockHash());
m++;
}
}
/*if ( (pindex= komodo_chainactive(ht)) != 0 )
{
bnTarget.SetCompact(pindex->nBits,&fNegative,&fOverflow);
bnTarget = (bnTarget / arith_uint256(KOMODO_POWMINMULT));
hashval = UintToArith256(pindex->GetBlockHash());
if ( hashval <= bnTarget ) // PoW is never as easy as PoS/64, some PoS will be counted as PoW
if ( hashval <= bnTarget ) // PoW is never as easy as PoS/16, some PoS will be counted as PoW
{
fprintf(stderr,"1");
if ( ASSETCHAINS_STAKED < 100 )
fprintf(stderr,"1");
sum += hashval;
n++;
}
else
{
n++;
percPoS++;
fprintf(stderr,"0");
if ( ASSETCHAINS_STAKED < 100 )
fprintf(stderr,"0");
}
if ( (i % 10) == 9 )
fprintf(stderr," %d, ",percPoS);
}
}*/
if ( ASSETCHAINS_STAKED < 100 && (i % 10) == 9 )
fprintf(stderr," %d, ",percPoS);
}
fprintf(stderr," -> %d%% percPoS ht.%d\n",percPoS,height);
if ( m+n < 100 )
percPoS = ((percPoS * n) + (goalperc * (100-n))) / 100;
if ( ASSETCHAINS_STAKED < 100 )
fprintf(stderr," -> %d%% percPoS vs goalperc.%d ht.%d\n",percPoS,goalperc,height);
*percPoSp = percPoS;
target = (target / arith_uint256(KOMODO_POWMINMULT));
if ( n > 0 )
//target = (target / arith_uint256(KOMODO_POWMINMULT));
if ( m > 0 )
{
ave = (sum / arith_uint256(n));
ave = (sum / arith_uint256(m));
if ( ave > target )
ave = target;
} else return(target);
} else ave = easydiff; //else return(target);
if ( percPoS == 0 )
percPoS = 1;
if ( percPoS < goalperc ) // increase PoW diff -> lower bnTarget
{
bnTarget = (ave * arith_uint256(percPoS * percPoS)) / arith_uint256((goalperc) * (goalperc));
if ( 1 )
if ( oldflag != 0 )
bnTarget = (ave * arith_uint256(percPoS * percPoS)) / arith_uint256(goalperc * goalperc * goalperc);
else bnTarget = (ave / arith_uint256(goalperc * goalperc * goalperc)) * arith_uint256(percPoS * percPoS);
if ( ASSETCHAINS_STAKED < 100 )
{
for (i=31; i>=24; i--)
fprintf(stderr,"%02x",((uint8_t *)&ave)[i]);
@ -1204,7 +1382,20 @@ arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t he
}
else if ( percPoS > goalperc ) // decrease PoW diff -> raise bnTarget
{
bnTarget = ((ave * arith_uint256(goalperc)) + (target * arith_uint256(percPoS))) / arith_uint256(percPoS + goalperc);
if ( oldflag != 0 )
{
bnTarget = ((ave * arith_uint256(goalperc)) + (easydiff * arith_uint256(percPoS))) / arith_uint256(percPoS + goalperc);
//bnTarget = (bnTarget * arith_uint256(percPoS * percPoS * percPoS)) / arith_uint256(goalperc * goalperc);
bnTarget = (bnTarget / arith_uint256(goalperc * goalperc)) * arith_uint256(percPoS * percPoS * percPoS);
} else bnTarget = (ave / arith_uint256(goalperc * goalperc)) * arith_uint256(percPoS * percPoS * percPoS);
if ( bnTarget > easydiff )
bnTarget = easydiff;
else if ( bnTarget < ave ) // overflow
{
bnTarget = ((ave * arith_uint256(goalperc)) + (easydiff * arith_uint256(percPoS))) / arith_uint256(percPoS + goalperc);
if ( bnTarget < ave )
bnTarget = ave;
}
if ( 1 )
{
for (i=31; i>=24; i--)
@ -1224,9 +1415,11 @@ arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t he
int32_t komodo_is_PoSblock(int32_t slowflag,int32_t height,CBlock *pblock,arith_uint256 bnTarget)
{
CBlockIndex *previndex; char voutaddr[64],destaddr[64]; uint256 txid; uint32_t txtime,prevtime=0; int32_t vout,txn_count,eligible,isPoS = 0; uint64_t value; CTxDestination voutaddress;
CBlockIndex *previndex; char voutaddr[64],destaddr[64]; uint256 txid; uint32_t txtime,prevtime=0; int32_t vout,txn_count,eligible=0,isPoS = 0; uint64_t value; CTxDestination voutaddress;
if ( ASSETCHAINS_STAKED == 100 && height <= 10 )
return(1);
txn_count = pblock->vtx.size();
if ( txn_count > 1 )
if ( txn_count > 1 && pblock->vtx[txn_count-1].vin.size() == 1 && pblock->vtx[txn_count-1].vout.size() == 1 )
{
if ( prevtime == 0 )
{
@ -1237,24 +1430,29 @@ int32_t komodo_is_PoSblock(int32_t slowflag,int32_t height,CBlock *pblock,arith_
vout = pblock->vtx[txn_count-1].vin[0].prevout.n;
if ( prevtime != 0 )
{
eligible = komodo_stake(1,bnTarget,height,txid,vout,pblock->nTime,prevtime,(char *)"");
if ( komodo_isPoS(pblock) != 0 )
eligible = komodo_stake(1,bnTarget,height,txid,vout,pblock->nTime,prevtime+27,(char *)"");
if ( eligible == 0 || eligible > pblock->nTime )
{
fprintf(stderr,"komodo_is_PoSblock PoS failure ht.%d eligible.%u vs blocktime.%u, lag.%d -> check to see if it is PoW block\n",height,eligible,(uint32_t)pblock->nTime,(int32_t)(eligible - pblock->nTime));
if ( ASSETCHAINS_STAKED < 100 )
fprintf(stderr,"komodo_is_PoSblock PoS failure ht.%d eligible.%u vs blocktime.%u, lag.%d -> check to see if it is PoW block\n",height,eligible,(uint32_t)pblock->nTime,(int32_t)(eligible - pblock->nTime));
} else isPoS = 1;
}
else if ( slowflag == 0 ) // maybe previous block is not seen yet, do the best approx
if ( slowflag == 0 ) // maybe previous block is not seen yet, do the best approx
{
txtime = komodo_txtime(&value,txid,vout,destaddr);
if ( komodo_isPoS(pblock) != 0 )
isPoS = 1;
/*txtime = komodo_txtime(&value,txid,vout,destaddr);
if ( ExtractDestination(pblock->vtx[txn_count-1].vout[0].scriptPubKey,voutaddress) )
{
strcpy(voutaddr,CBitcoinAddress(voutaddress).ToString().c_str());
if ( strcmp(destaddr,voutaddr) == 0 && pblock->vtx[txn_count-1].vout[0].nValue == value )
isPoS = 1; // close enough for a pre-filter
else fprintf(stderr,"komodo_is_PoSblock ht.%d (%s) != (%s) or %.8f != %.8f\n",height,destaddr,voutaddr,dstr(value),dstr(pblock->vtx[txn_count-1].vout[0].nValue));
} else fprintf(stderr,"komodo_is_PoSblock ht.%d couldnt extract voutaddress\n",height);
} else return(-1);
//else fprintf(stderr,"komodo_is_PoSblock ht.%d (%s) != (%s) or %.8f != %.8f\n",height,destaddr,voutaddr,dstr(value),dstr(pblock->vtx[txn_count-1].vout[0].nValue));
} else fprintf(stderr,"komodo_is_PoSblock ht.%d couldnt extract voutaddress\n",height);*/
} //else return(-1);
}
//fprintf(stderr,"slow.%d ht.%d isPoS.%d\n",slowflag,height,isPoS);
return(isPoS);
}
@ -1378,6 +1576,31 @@ bool verusCheckPOSBlock(int32_t slowflag, CBlock *pblock, int32_t height)
return(isPOS);
}
int64_t komodo_checkcommission(CBlock *pblock,int32_t height)
{
int64_t checktoshis=0; uint8_t *script;
if ( ASSETCHAINS_COMMISSION != 0 )
{
checktoshis = komodo_commission(pblock);
if ( checktoshis > 10000 && pblock->vtx[0].vout.size() != 2 )
return(-1);
else if ( checktoshis != 0 )
{
script = (uint8_t *)pblock->vtx[0].vout[1].scriptPubKey.data();
if ( script[0] != 33 || script[34] != OP_CHECKSIG || memcmp(script+1,ASSETCHAINS_OVERRIDE_PUBKEY33,33) != 0 )
return(-1);
if ( pblock->vtx[0].vout[1].nValue != checktoshis )
{
fprintf(stderr,"ht.%d checktoshis %.8f vs actual vout[1] %.8f\n",height,dstr(checktoshis),dstr(pblock->vtx[0].vout[1].nValue));
return(-1);
}
}
}
return(checktoshis);
}
bool KOMODO_TEST_ASSETCHAIN_SKIP_POW = 0;
int32_t komodo_checkPOW(int32_t slowflag,CBlock *pblock,int32_t height)
{
uint256 hash; arith_uint256 bnTarget,bhash; bool fNegative,fOverflow; uint8_t *script,pubkey33[33],pubkeys[64][33]; int32_t i,possible,PoSperc,is_PoSblock=0,n,failed = 0,notaryid = -1; int64_t checktoshis,value; CBlockIndex *pprev;
@ -1390,11 +1613,13 @@ int32_t komodo_checkPOW(int32_t slowflag,CBlock *pblock,int32_t height)
bnTarget.SetCompact(pblock->nBits,&fNegative,&fOverflow);
bhash = UintToArith256(hash);
possible = komodo_block2pubkey33(pubkey33,pblock);
//fprintf(stderr,"height.%d slowflag.%d possible.%d cmp.%d\n",height,slowflag,possible,bhash > bnTarget);
if ( height == 0 )
{
if ( slowflag != 0 )
{
fprintf(stderr,"height.%d slowflag.%d possible.%d cmp.%d\n",height,slowflag,possible,bhash > bnTarget);
return(0);
}
if ( (pprev= mapBlockIndex[pblock->hashPrevBlock]) != 0 )
height = pprev->nHeight + 1;
if ( height == 0 )
@ -1425,21 +1650,24 @@ int32_t komodo_checkPOW(int32_t slowflag,CBlock *pblock,int32_t height)
}
else if ( possible == 0 || ASSETCHAINS_SYMBOL[0] != 0 )
{
fprintf(stderr,"pow violation and no chance it is notary ht.%d %s\n",height,hash.ToString().c_str());
return(-1);
if ( KOMODO_TEST_ASSETCHAIN_SKIP_POW )
return(0);
if ( ASSETCHAINS_STAKED == 0 ) // komodo_is_PoSblock will check bnTarget
return(-1);
}
}
else if ( ASSETCHAINS_STAKED != 0 && height >= 2 ) // must PoS or have at least 16x better PoW
if ( ASSETCHAINS_STAKED != 0 && height >= 2 ) // must PoS or have at least 16x better PoW
{
if ( (is_PoSblock= komodo_is_PoSblock(slowflag,height,pblock,bnTarget)) == 0 )
{
if ( ASSETCHAINS_STAKED == 100 && height > 100 ) // only PoS allowed!
if ( ASSETCHAINS_STAKED == 100 && height > 100 ) // only PoS allowed! POSTEST64
return(-1);
else
{
if ( slowflag == 0 ) // need all past 100 blocks to calculate PoW target
return(0);
if ( slowflag != 0 )
bnTarget = komodo_PoWtarget(&PoSperc,bnTarget,height,ASSETCHAINS_STAKED);
else bnTarget = (bnTarget / arith_uint256(KOMODO_POWMINMULT)); // lower bound
if ( bhash > bnTarget )
{
for (i=31; i>=16; i--)
@ -1449,26 +1677,27 @@ int32_t komodo_checkPOW(int32_t slowflag,CBlock *pblock,int32_t height)
fprintf(stderr,"%02x",((uint8_t *)&bnTarget)[i]);
fprintf(stderr," ht.%d PoW diff violation PoSperc.%d vs goalperc.%d\n",height,PoSperc,(int32_t)ASSETCHAINS_STAKED);
return(-1);
}
} else failed = 0;
}
} else if ( is_PoSblock < 0 )
}
else if ( is_PoSblock < 0 )
{
fprintf(stderr,"unexpected negative is_PoSblock.%d\n",is_PoSblock);
return(-1);
}
}
if ( failed == 0 && ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 && ASSETCHAINS_COMMISSION != 0 )
if ( failed == 0 && ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 )
{
checktoshis = komodo_commission(pblock);
if ( checktoshis > 10000 && pblock->vtx[0].vout.size() != 2 )
return(-1);
else if ( checktoshis != 0 )
if ( height == 1 )
{
script = (uint8_t *)pblock->vtx[0].vout[1].scriptPubKey.data();
script = (uint8_t *)pblock->vtx[0].vout[0].scriptPubKey.data();
if ( script[0] != 33 || script[34] != OP_CHECKSIG || memcmp(script+1,ASSETCHAINS_OVERRIDE_PUBKEY33,33) != 0 )
return(-1);
if ( pblock->vtx[0].vout[1].nValue != checktoshis )
{
fprintf(stderr,"checktoshis %.8f vs actual vout[1] %.8f\n",dstr(checktoshis),dstr(pblock->vtx[0].vout[1].nValue));
}
else
{
if ( komodo_checkcommission(pblock,height) < 0 )
return(-1);
}
}
}
//fprintf(stderr,"komodo_checkPOW possible.%d slowflag.%d ht.%d notaryid.%d failed.%d\n",possible,slowflag,height,notaryid,failed);
@ -1477,3 +1706,79 @@ int32_t komodo_checkPOW(int32_t slowflag,CBlock *pblock,int32_t height)
else return(0);
}
int64_t komodo_newcoins(int64_t *zfundsp,int32_t nHeight,CBlock *pblock)
{
CTxDestination address; int32_t i,j,m,n,vout; uint8_t *script; uint256 txid,hashBlock; int64_t zfunds=0,vinsum=0,voutsum=0;
n = pblock->vtx.size();
for (i=0; i<n; i++)
{
CTransaction vintx,&tx = pblock->vtx[i];
zfunds += (tx.GetJoinSplitValueOut() - tx.GetJoinSplitValueIn());
if ( (m= tx.vin.size()) > 0 )
{
for (j=0; j<m; j++)
{
if ( i == 0 )
continue;
txid = tx.vin[j].prevout.hash;
vout = tx.vin[j].prevout.n;
if ( !GetTransaction(txid,vintx,hashBlock, false) || vout >= vintx.vout.size() )
{
fprintf(stderr,"ERROR: %s/v%d cant find\n",txid.ToString().c_str(),vout);
return(0);
}
vinsum += vintx.vout[vout].nValue;
}
}
if ( (m= tx.vout.size()) > 0 )
{
for (j=0; j<m-1; j++)
{
if ( ExtractDestination(tx.vout[j].scriptPubKey,address) != 0 && strcmp("RD6GgnrMpPaTSMn8vai6yiGA7mN4QGPVMY",CBitcoinAddress(address).ToString().c_str()) != 0 )
voutsum += tx.vout[j].nValue;
else printf("skip %.8f -> %s\n",dstr(tx.vout[j].nValue),CBitcoinAddress(address).ToString().c_str());
}
script = (uint8_t *)tx.vout[j].scriptPubKey.data();
if ( script == 0 || script[0] != 0x6a )
{
if ( ExtractDestination(tx.vout[j].scriptPubKey,address) != 0 && strcmp("RD6GgnrMpPaTSMn8vai6yiGA7mN4QGPVMY",CBitcoinAddress(address).ToString().c_str()) != 0 )
voutsum += tx.vout[j].nValue;
}
}
}
*zfundsp = zfunds;
if ( ASSETCHAINS_SYMBOL[0] == 0 && (voutsum-vinsum) == 100003*SATOSHIDEN ) // 15 times
return(3 * SATOSHIDEN);
//if ( voutsum-vinsum+zfunds > 100000*SATOSHIDEN || voutsum-vinsum+zfunds < 0 )
//. fprintf(stderr,"ht.%d vins %.8f, vouts %.8f -> %.8f zfunds %.8f\n",nHeight,dstr(vinsum),dstr(voutsum),dstr(voutsum)-dstr(vinsum),dstr(zfunds));
return(voutsum - vinsum);
}
int64_t komodo_coinsupply(int64_t *zfundsp,int32_t height)
{
CBlockIndex *pindex; CBlock block; int64_t zfunds=0,supply = 0;
//fprintf(stderr,"coinsupply %d\n",height);
*zfundsp = 0;
if ( (pindex= komodo_chainactive(height)) != 0 )
{
while ( pindex != 0 && pindex->nHeight > 0 )
{
if ( pindex->newcoins == 0 && pindex->zfunds == 0 )
{
if ( komodo_blockload(block,pindex) == 0 )
pindex->newcoins = komodo_newcoins(&pindex->zfunds,pindex->nHeight,&block);
else
{
fprintf(stderr,"error loading block.%d\n",pindex->nHeight);
return(0);
}
}
supply += pindex->newcoins;
zfunds += pindex->zfunds;
//printf("start ht.%d new %.8f -> supply %.8f zfunds %.8f -> %.8f\n",pindex->nHeight,dstr(pindex->newcoins),dstr(supply),dstr(pindex->zfunds),dstr(zfunds));
pindex = pindex->pprev;
}
}
*zfundsp = zfunds;
return(supply);
}

46
src/komodo_ccdata.h

@ -19,53 +19,29 @@
struct komodo_ccdata *CC_data;
int32_t CC_firstheight;
bits256 iguana_merkle(bits256 *tree,int32_t txn_count)
{
int32_t i,n=0,prev; uint8_t serialized[sizeof(bits256) * 2];
if ( txn_count == 1 )
return(tree[0]);
prev = 0;
while ( txn_count > 1 )
{
if ( (txn_count & 1) != 0 )
tree[prev + txn_count] = tree[prev + txn_count-1], txn_count++;
n += txn_count;
for (i=0; i<txn_count; i+=2)
{
iguana_rwbignum(1,serialized,sizeof(*tree),tree[prev + i].bytes);
iguana_rwbignum(1,&serialized[sizeof(*tree)],sizeof(*tree),tree[prev + i + 1].bytes);
tree[n + (i >> 1)] = bits256_doublesha256(0,serialized,sizeof(serialized));
}
prev = n;
txn_count >>= 1;
}
return(tree[n]);
}
uint256 BuildMerkleTree(bool* fMutated, const std::vector<uint256> leaves, std::vector<uint256> &vMerkleTree);
uint256 komodo_calcMoM(int32_t height,int32_t MoMdepth)
{
static uint256 zero; bits256 MoM,*tree; CBlockIndex *pindex; int32_t i;
static uint256 zero; CBlockIndex *pindex; int32_t i; std::vector<uint256> tree, leaves;
bool fMutated;
MoMdepth &= 0xffff; // In case it includes the ccid
if ( MoMdepth >= height )
return(zero);
tree = (bits256 *)calloc(MoMdepth * 3,sizeof(*tree));
for (i=0; i<MoMdepth; i++)
{
if ( (pindex= komodo_chainactive(height - i)) != 0 )
memcpy(&tree[i],&pindex->hashMerkleRoot,sizeof(bits256));
leaves.push_back(pindex->hashMerkleRoot);
else
{
free(tree);
return(zero);
}
}
MoM = iguana_merkle(tree,MoMdepth);
free(tree);
return(*(uint256 *)&MoM);
return BuildMerkleTree(&fMutated, leaves, tree);
}
struct komodo_ccdata_entry *komodo_allMoMs(int32_t *nump,uint256 *MoMoMp,int32_t kmdstarti,int32_t kmdendi)
{
struct komodo_ccdata_entry *allMoMs=0; bits256 *tree,tmp; struct komodo_ccdata *ccdata,*tmpptr; int32_t i,num,max;
struct komodo_ccdata_entry *allMoMs=0; struct komodo_ccdata *ccdata,*tmpptr; int32_t i,num,max;
bool fMutated; std::vector<uint256> tree, leaves;
num = max = 0;
portable_mutex_lock(&KOMODO_CC_mutex);
DL_FOREACH_SAFE(CC_data,ccdata,tmpptr)
@ -90,11 +66,9 @@ struct komodo_ccdata_entry *komodo_allMoMs(int32_t *nump,uint256 *MoMoMp,int32_t
portable_mutex_unlock(&KOMODO_CC_mutex);
if ( (*nump= num) > 0 )
{
tree = (bits256 *)calloc(sizeof(bits256),num*3);
for (i=0; i<num; i++)
memcpy(&tree[i],&allMoMs[i].MoM,sizeof(tree[i]));
tmp = iguana_merkle(tree,num);
memcpy(MoMoMp,&tmp,sizeof(*MoMoMp));
leaves.push_back(allMoMs[i].MoM);
*MoMoMp = BuildMerkleTree(&fMutated, leaves, tree);
}
else
{

2
src/komodo_defs.h

@ -7,5 +7,7 @@
#define ROUNDROBIN_DELAY 61
#define KOMODO_ASSETCHAIN_MAXLEN 65
#define KOMODO_LIMITED_NETWORKSIZE 4
#define KOMODO_MAXMEMPOOLTIME 3600 // affects consensus
#define CRYPTO777_PUBSECPSTR "020e46e79a2a8d12b9b5d12c7a91adb4e454edfae43c0a0cb805427d2ac7613fd9"
#endif

6
src/komodo_events.h

@ -41,14 +41,14 @@ void komodo_eventadd_notarized(struct komodo_state *sp,char *symbol,int32_t heig
{
static uint32_t counter; int32_t verified=0; char *coin; struct komodo_event_notarized N;
coin = (ASSETCHAINS_SYMBOL[0] == 0) ? (char *)"KMD" : ASSETCHAINS_SYMBOL;
if ( (ASSETCHAINS_SYMBOL[0] == 0 && height > 814000) && NOTARY_PUBKEY33[0] != 0 && (verified= komodo_verifynotarization(symbol,dest,height,notarizedheight,notarized_hash,notarized_desttxid)) < 0 )
if ( IS_KOMODO_NOTARY != 0 && (verified= komodo_verifynotarization(symbol,dest,height,notarizedheight,notarized_hash,notarized_desttxid)) < 0 )
{
if ( ASSETCHAINS_SYMBOL[0] == 0 && height > 814000 && counter++ < 10 )
if ( counter++ < 100 )
printf("[%s] error validating notarization ht.%d notarized_height.%d, if on a pruned %s node this can be ignored\n",ASSETCHAINS_SYMBOL,height,notarizedheight,dest);
}
else if ( strcmp(symbol,coin) == 0 )
{
if ( 0 && NOTARY_PUBKEY33[0] != 0 && verified != 0 )
if ( 0 && IS_KOMODO_NOTARY != 0 && verified != 0 )
fprintf(stderr,"validated [%s] ht.%d notarized %d\n",coin,height,notarizedheight);
memset(&N,0,sizeof(N));
N.blockhash = notarized_hash;

27
src/komodo_gateway.h

@ -653,7 +653,7 @@ void komodo_passport_iteration();
int32_t komodo_check_deposit(int32_t height,const CBlock& block,uint32_t prevtime) // verify above block is valid pax pricing
{
static uint256 array[64]; static int32_t numbanned,indallvouts;
int32_t i,j,k,n,ht,baseid,txn_count,activation,num,opretlen,offset=1,errs=0,matched=0,kmdheights[256],otherheights[256],notmatched=0; uint256 hash,txids[256]; char symbol[KOMODO_ASSETCHAIN_MAXLEN],base[KOMODO_ASSETCHAIN_MAXLEN]; uint16_t vouts[256]; int8_t baseids[256]; uint8_t *script,opcode,rmd160s[256*20]; uint64_t total,subsidy,available,deposited,issued,withdrawn,approved,redeemed,checktoshis,seed; int64_t values[256],srcvalues[256]; struct pax_transaction *pax; struct komodo_state *sp; CTransaction tx;
int32_t i,j,k,n,ht,baseid,txn_count,activation,num,opretlen,offset=1,errs=0,notmatched=0,matched=0,kmdheights[256],otherheights[256]; uint256 hash,txids[256]; char symbol[KOMODO_ASSETCHAIN_MAXLEN],base[KOMODO_ASSETCHAIN_MAXLEN]; uint16_t vouts[256]; int8_t baseids[256]; uint8_t *script,opcode,rmd160s[256*20]; uint64_t total,subsidy,available,deposited,issued,withdrawn,approved,redeemed,seed; int64_t checktoshis,values[256],srcvalues[256]; struct pax_transaction *pax; struct komodo_state *sp; CTransaction tx;
activation = 235300;
if ( *(int32_t *)&array[0] == 0 )
numbanned = komodo_bannedset(&indallvouts,array,(int32_t)(sizeof(array)/sizeof(*array)));
@ -717,7 +717,8 @@ int32_t komodo_check_deposit(int32_t height,const CBlock& block,uint32_t prevtim
{
if ( height >= activation )
{
fprintf(stderr,">>>>>>>> <<<<<<<<<< ht.%d illegal nonz output %.8f n.%d\n",height,dstr(block.vtx[0].vout[1].nValue),n);
if ( height > 800000 )
fprintf(stderr,">>>>>>>> <<<<<<<<<< ht.%d illegal nonz output %.8f n.%d\n",height,dstr(block.vtx[0].vout[1].nValue),n);
return(-1);
}
}
@ -729,7 +730,7 @@ int32_t komodo_check_deposit(int32_t height,const CBlock& block,uint32_t prevtim
}
if ( strangeout != 0 || notmatched != 0 )
{
if ( strcmp(NOTARY_PUBKEY.c_str(),"03b7621b44118017a16043f19b30cc8a4cfe068ac4e42417bae16ba460c80f3828") == 0 )
if ( 0 && strcmp(NOTARY_PUBKEY.c_str(),"03b7621b44118017a16043f19b30cc8a4cfe068ac4e42417bae16ba460c80f3828") == 0 )
fprintf(stderr,">>>>>>>>>>>>> DUST ht.%d strangout.%d notmatched.%d <<<<<<<<<\n",height,strangeout,notmatched);
if ( height > 1000000 && strangeout != 0 )
return(-1);
@ -742,10 +743,24 @@ int32_t komodo_check_deposit(int32_t height,const CBlock& block,uint32_t prevtim
}
else
{
if ( overflow != 0 || total > 0 || strangeout != 0 )
checktoshis = 0;
if ( ASSETCHAINS_COMMISSION != 0 && height > 1 )
{
if ( (checktoshis= komodo_checkcommission((CBlock *)&block,height)) < 0 )
{
fprintf(stderr,"ht.%d checktoshis %.8f overflow.%d total %.8f strangeout.%d\n",height,dstr(checktoshis),overflow,dstr(total),strangeout);
return(-1);
}
}
if ( height > 1 && checktoshis == 0 )
{
checktoshis = ((uint64_t)GetBlockSubsidy(height, Params().GetConsensus()) - block.vtx[0].vout[0].nValue);
}
if ( height >= 2 && (overflow != 0 || total > checktoshis || strangeout != 0) )
{
fprintf(stderr,"checkdeposit: ht.%d checktoshis %.8f overflow.%d total %.8f strangeout.%d\n",height,dstr(checktoshis),overflow,dstr(total),strangeout);
if ( strangeout != 0 )
fprintf(stderr,">>>>>>>>>>>>> DUST ht.%d strangout.%d notmatched.%d <<<<<<<<<\n",height,strangeout,notmatched);
fprintf(stderr,">>>>>>>>>>>>> %s DUST ht.%d strangout.%d notmatched.%d <<<<<<<<<\n",ASSETCHAINS_SYMBOL,height,strangeout,notmatched);
return(-1);
}
}
@ -1475,7 +1490,7 @@ void komodo_passport_iteration()
komodo_statefname(fname,baseid<32?base:(char *)"",(char *)"realtime");
if ( (fp= fopen(fname,"wb")) != 0 )
{
buf[0] = (uint32_t)chainActive.Tip()->nHeight;
buf[0] = (uint32_t)chainActive.LastTip()->nHeight;
buf[1] = (uint32_t)komodo_longestchain();
if ( buf[0] != 0 && buf[0] == buf[1] )
{

10
src/komodo_globals.h

@ -46,13 +46,13 @@ struct komodo_state KOMODO_STATES[34];
int COINBASE_MATURITY = _COINBASE_MATURITY;//100;
int32_t IS_KOMODO_NOTARY,USE_EXTERNAL_PUBKEY,KOMODO_CHOSEN_ONE,ASSETCHAINS_SEED,KOMODO_ON_DEMAND,KOMODO_EXTERNAL_NOTARIES,KOMODO_PASSPORT_INITDONE,KOMODO_PAX,KOMODO_EXCHANGEWALLET,KOMODO_REWIND;
int32_t KOMODO_LASTMINED,prevKOMODO_LASTMINED,JUMBLR_PAUSE = 1;
std::string NOTARY_PUBKEY,ASSETCHAINS_NOTARIES,ASSETCHAINS_OVERRIDE_PUBKEY;
uint8_t NOTARY_PUBKEY33[33],ASSETCHAINS_OVERRIDE_PUBKEY33[33];
int32_t KOMODO_INSYNC,KOMODO_LASTMINED,prevKOMODO_LASTMINED,JUMBLR_PAUSE = 1;
std::string NOTARY_PUBKEY,ASSETCHAINS_NOTARIES,ASSETCHAINS_OVERRIDE_PUBKEY,DONATION_PUBKEY;
uint8_t NOTARY_PUBKEY33[33],ASSETCHAINS_OVERRIDE_PUBKEY33[33],ASSETCHAINS_PUBLIC,ASSETCHAINS_PRIVATE;
char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN],ASSETCHAINS_USERPASS[4096];
uint16_t ASSETCHAINS_P2PPORT,ASSETCHAINS_RPCPORT;
uint32_t ASSETCHAIN_INIT,ASSETCHAINS_CC;
uint32_t ASSETCHAIN_INIT,ASSETCHAINS_CC,KOMODO_STOPAT;
uint32_t ASSETCHAINS_MAGIC = 2387029918;
int64_t ASSETCHAINS_GENESISTXVAL = 5000000000;
@ -89,7 +89,7 @@ uint64_t KOMODO_INTERESTSUM,KOMODO_WALLETBALANCE;
uint64_t ASSETCHAINS_COMMISSION,ASSETCHAINS_STAKED,ASSETCHAINS_SUPPLY = 10;
uint32_t KOMODO_INITDONE;
char KMDUSERPASS[4096],BTCUSERPASS[4096]; uint16_t KMD_PORT = 7771,BITCOIND_RPCPORT = 7771;
char KMDUSERPASS[8192],BTCUSERPASS[8192]; uint16_t KMD_PORT = 7771,BITCOIND_RPCPORT = 7771;
uint64_t PENDING_KOMODO_TX;
extern int32_t KOMODO_LOADINGBLOCKS;
unsigned int MAX_BLOCK_SIGOPS = 20000;

4
src/komodo_interest.h

@ -83,13 +83,13 @@ uint64_t komodo_moneysupply(int32_t height)
uint64_t _komodo_interestnew(int32_t txheight,uint64_t nValue,uint32_t nLockTime,uint32_t tiptime)
{
int32_t minutes; uint64_t interest = 0;
if ( nLockTime >= LOCKTIME_THRESHOLD && tiptime > nLockTime && (minutes= (tiptime - nLockTime) / 60) >= 60 )
if ( nLockTime >= LOCKTIME_THRESHOLD && tiptime > nLockTime && (minutes= (tiptime - nLockTime) / 60) >= (KOMODO_MAXMEMPOOLTIME/60) )
{
if ( minutes > 365 * 24 * 60 )
minutes = 365 * 24 * 60;
if ( txheight >= 1000000 && minutes > 31 * 24 * 60 )
minutes = 31 * 24 * 60;
minutes -= 59;
minutes -= ((KOMODO_MAXMEMPOOLTIME/60) - 1);
interest = ((nValue / 10512000) * minutes);
}
return(interest);

2
src/komodo_jumblr.h

@ -648,7 +648,7 @@ void jumblr_iteration()
free(retstr);
}
}
height = (int32_t)chainActive.Tip()->nHeight;
height = (int32_t)chainActive.LastTip()->nHeight;
if ( time(NULL) < lasttime+40 )
return;
lasttime = (uint32_t)time(NULL);

15
src/komodo_kv.h

@ -64,7 +64,7 @@ int32_t komodo_kvsearch(uint256 *pubkeyp,int32_t current_height,uint32_t *flagsp
if ( ptr != 0 )
{
duration = komodo_kvduration(ptr->flags);
//printf("duration.%d flags.%d current.%d ht.%d keylen.%d valuesize.%d\n",duration,ptr->flags,current_height,ptr->height,ptr->keylen,ptr->valuesize);
fprintf(stderr,"duration.%d flags.%d current.%d ht.%d keylen.%d valuesize.%d\n",duration,ptr->flags,current_height,ptr->height,ptr->keylen,ptr->valuesize);
if ( current_height > (ptr->height + duration) )
{
HASH_DELETE(hh,KOMODO_KV,ptr);
@ -88,7 +88,7 @@ int32_t komodo_kvsearch(uint256 *pubkeyp,int32_t current_height,uint32_t *flagsp
if ( (retval= ptr->valuesize) > 0 )
memcpy(value,ptr->value,retval);
}
}
} else fprintf(stderr,"couldnt find (%s)\n",(char *)key);
portable_mutex_unlock(&KOMODO_KV_mutex);
if ( retval < 0 )
{
@ -112,12 +112,12 @@ void komodo_kvupdate(uint8_t *opretbuf,int32_t opretlen,uint64_t value)
{
static uint32_t counter;
if ( ++counter < 1 )
printf("komodo_kvupdate: keylen.%d + 13 > opretlen.%d, this can be ignored\n",keylen,opretlen);
fprintf(stderr,"komodo_kvupdate: keylen.%d + 13 > opretlen.%d, this can be ignored\n",keylen,opretlen);
return;
}
valueptr = &key[keylen];
fee = komodo_kvfee(flags,opretlen,keylen);
//printf("fee %.8f vs %.8f flags.%d keylen.%d valuesize.%d height.%d (%02x %02x %02x) (%02x %02x %02x)\n",(double)fee/COIN,(double)value/COIN,flags,keylen,valuesize,height,key[0],key[1],key[2],valueptr[0],valueptr[1],valueptr[2]);
printf("fee %.8f vs %.8f flags.%d keylen.%d valuesize.%d height.%d (%02x %02x %02x) (%02x %02x %02x)\n",(double)fee/COIN,(double)value/COIN,flags,keylen,valuesize,height,key[0],key[1],key[2],valueptr[0],valueptr[1],valueptr[2]);
if ( value >= fee )
{
coresize = (int32_t)(sizeof(flags)+sizeof(height)+sizeof(keylen)+sizeof(valuesize)+keylen+valuesize+1);
@ -142,7 +142,7 @@ void komodo_kvupdate(uint8_t *opretbuf,int32_t opretlen,uint64_t value)
{
if ( komodo_kvsigverify(keyvalue,keylen+refvaluesize,refpubkey,sig) < 0 )
{
printf("komodo_kvsigverify error [%d]\n",coresize-13);
fprintf(stderr,"komodo_kvsigverify error [%d]\n",coresize-13);
return;
}
}
@ -151,6 +151,7 @@ void komodo_kvupdate(uint8_t *opretbuf,int32_t opretlen,uint64_t value)
HASH_FIND(hh,KOMODO_KV,key,keylen,ptr);
if ( ptr != 0 )
{
fprintf(stderr,"(%s) already there\n",(char *)key);
//if ( (ptr->flags & KOMODO_KVPROTECTED) != 0 )
{
tstr = (char *)"transfer:";
@ -171,7 +172,7 @@ void komodo_kvupdate(uint8_t *opretbuf,int32_t opretlen,uint64_t value)
memcpy(ptr->key,key,keylen);
newflag = 1;
HASH_ADD_KEYPTR(hh,KOMODO_KV,ptr->key,ptr->keylen,ptr);
//printf("KV add.(%s) (%s)\n",ptr->key,valueptr);
fprintf(stderr,"KV add.(%s) (%s)\n",ptr->key,valueptr);
}
if ( newflag != 0 || (ptr->flags & KOMODO_KVPROTECTED) == 0 )
{
@ -193,7 +194,7 @@ void komodo_kvupdate(uint8_t *opretbuf,int32_t opretlen,uint64_t value)
ptr->height = height;
ptr->flags = flags; // jl777 used to or in KVPROTECTED
portable_mutex_unlock(&KOMODO_KV_mutex);
} else fprintf(stderr,"size mismatch %d vs %d\n",opretlen,coresize);
} else fprintf(stderr,"KV update size mismatch %d vs %d\n",opretlen,coresize);
} else fprintf(stderr,"not enough fee\n");
}

23
src/komodo_notary.h

@ -384,18 +384,35 @@ int32_t komodo_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33,
//struct komodo_state *komodo_stateptr(char *symbol,char *dest);
struct notarized_checkpoint *komodo_npptr(int32_t height)
struct notarized_checkpoint *komodo_npptr_for_height(int32_t height, int *idx)
{
char symbol[KOMODO_ASSETCHAIN_MAXLEN],dest[KOMODO_ASSETCHAIN_MAXLEN]; int32_t i; struct komodo_state *sp; struct notarized_checkpoint *np = 0;
if ( (sp= komodo_stateptr(symbol,dest)) != 0 )
{
for (i=sp->NUM_NPOINTS-1; i>=0; i--)
{
*idx = i;
np = &sp->NPOINTS[i];
if ( np->MoMdepth > 0 && height > np->notarized_height-np->MoMdepth && height <= np->notarized_height )
if ( np->MoMdepth != 0 && height > np->notarized_height-(np->MoMdepth&0xffff) && height <= np->notarized_height )
return(np);
}
}
*idx = -1;
return(0);
}
struct notarized_checkpoint *komodo_npptr(int32_t height)
{
int idx;
return komodo_npptr_for_height(height, &idx);
}
struct notarized_checkpoint *komodo_npptr_at(int idx)
{
char symbol[KOMODO_ASSETCHAIN_MAXLEN],dest[KOMODO_ASSETCHAIN_MAXLEN]; struct komodo_state *sp;
if ( (sp= komodo_stateptr(symbol,dest)) != 0 )
if (idx < sp->NUM_NPOINTS)
return &sp->NPOINTS[idx];
return(0);
}
@ -447,7 +464,7 @@ int32_t komodo_MoMdata(int32_t *notarized_htp,uint256 *MoMp,uint256 *kmdtxidp,in
*MoMoMdepthp = np->MoMoMdepth;
*kmdstartip = np->kmdstarti;
*kmdendip = np->kmdendi;
return(np->MoMdepth);
return(np->MoMdepth & 0xffff);
}
*notarized_htp = *MoMoMoffsetp = *MoMoMdepthp = *kmdstartip = *kmdendip = 0;
memset(MoMp,0,sizeof(*MoMp));

4
src/komodo_pax.h

@ -637,13 +637,13 @@ uint64_t komodo_paxpriceB(uint64_t seed,int32_t height,char *base,char *rel,uint
uint64_t komodo_paxprice(uint64_t *seedp,int32_t height,char *base,char *rel,uint64_t basevolume)
{
int32_t i,nonz=0; int64_t diff; uint64_t price,seed,sum = 0;
if ( ASSETCHAINS_SYMBOL[0] == 0 && chainActive.Tip() != 0 && height > chainActive.Tip()->nHeight )
if ( ASSETCHAINS_SYMBOL[0] == 0 && chainActive.LastTip() != 0 && height > chainActive.LastTip()->nHeight )
{
if ( height < 100000000 )
{
static uint32_t counter;
if ( counter++ < 3 )
printf("komodo_paxprice height.%d vs tip.%d\n",height,chainActive.Tip()->nHeight);
printf("komodo_paxprice height.%d vs tip.%d\n",height,chainActive.LastTip()->nHeight);
}
return(0);
}

20
src/komodo_port.c

@ -809,7 +809,7 @@ uint16_t komodo_calcport(char *name,uint64_t supply,uint64_t endsubsidy,uint64_t
decay = 0;
printf("decay cant be more than 100000000\n");
}
if ( endsubsidy != 0 || reward != 0 || halving != 0 || decay != 0 || commission != 0 || cc != 0 || staked != 0 )
if ( endsubsidy != 0 || reward != 0 || halving != 0 || decay != 0 || commission != 0 || cc != 0 || staked != 0 || ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 )
{
//printf("end.%llu reward.%llu halving.%llu decay.%llu perc.%llu\n",(long long)endsubsidy,(long long)reward,(long long)halving,(long long)decay,(long long)commission);
extraptr = extrabuf;
@ -826,7 +826,7 @@ uint16_t komodo_calcport(char *name,uint64_t supply,uint64_t endsubsidy,uint64_t
int main(int argc, char * argv[])
{
uint16_t rpcport; int32_t i,j,offset=0,num = 1; uint64_t supply=10,commission=0,endsubsidy,reward,halving,decay; uint8_t *allocated=0,staked=0; uint32_t cc = 1;
uint16_t rpcport; int32_t i,j,offset=0,jsonflag=0,num = 1; uint64_t supply=10,commission=0,endsubsidy,reward,halving,decay; uint8_t *allocated=0,staked=0; uint32_t cc = 3;
endsubsidy = reward = halving = decay = 0;
if ( argc < 2 )
{
@ -835,9 +835,11 @@ int main(int argc, char * argv[])
printf("%s -gen num name supply endsubsidy reward halving decay\n",argv[0]);
return(-1);
}
if ( strcmp(argv[1],"-gen") == 0 )
if ( strncmp(argv[1],"-gen",3) == 0 )
{
num = atoi(argv[2]);
if ( strcmp(argv[1],"-genjson") == 0 )
jsonflag = 1;
offset = 2;
allocated = calloc(1,1 << 16);
}
@ -852,7 +854,7 @@ int main(int argc, char * argv[])
if ( argc > offset + 6 )
decay = (long long)atof(argv[offset + 6]);
rpcport = 1 + komodo_calcport(argv[offset + 1],supply,endsubsidy,reward,halving,decay,commission,staked,cc);
printf("./komodod -ac_name=%s -ac_cc=%u -ac_supply=%llu -ac_end=%llu -ac_reward=%llu -ac_halving=%llu -ac_decay=%llu & # rpcport %u\n",argv[offset + 1],cc,(long long)supply,(long long)endsubsidy,(long long)reward,(long long)halving,(long long)decay,rpcport);
printf("./komodod -ac_name=%s -ac_cc=%u -ac_supply=%llu -ac_end=%llu -ac_reward=%llu -ac_halving=%llu -ac_decay=%llu & # rpcport %u\n[",argv[offset + 1],cc,(long long)supply,(long long)endsubsidy,(long long)reward,(long long)halving,(long long)decay,rpcport);
if ( allocated != 0 )
{
char name[64],newname[64];
@ -868,7 +870,14 @@ int main(int argc, char * argv[])
rpcport = 1 + komodo_calcport(newname,supply+j,endsubsidy,reward,halving,decay,commission,staked,cc);
if ( allocated[rpcport] == 0 && allocated[rpcport-1] == 0 )
{
printf("./komodod -ac_name=%s -ac_cc=%u -ac_supply=%llu -ac_end=%llu -ac_reward=%llu -ac_halving=%llu -ac_decay=%llu & # rpcport %u\n",newname,cc,(long long)supply+j,(long long)endsubsidy,(long long)reward,(long long)halving,(long long)decay,rpcport);
if ( jsonflag == 0 )
{
printf("./komodod -ac_name=%s -ac_cc=%u -ac_supply=%llu -ac_end=%llu -ac_reward=%llu -ac_halving=%llu -ac_decay=%llu & # rpcport %u\n",newname,cc,(long long)supply+j,(long long)endsubsidy,(long long)reward,(long long)halving,(long long)decay,rpcport);
}
else
{
printf("{ \"assetname\": \"%s\", \"p2p\": %u, \"rpc\": %u, \"supply\": %llu, \"ac_cc\": %u, \"ac_reward\": %llu, \"notarize\": %s }%s ",newname,rpcport-1,rpcport,(long long)supply+j,cc,(long long)reward,i<64?"true":"false",i<num-1?",":"");
}
allocated[rpcport] = 1;
allocated[rpcport-1] = 1;
break;
@ -878,5 +887,6 @@ int main(int argc, char * argv[])
}
free(allocated);
}
printf("]\n");
return(0);
}

19
src/komodo_utils.h

@ -1646,14 +1646,26 @@ uint64_t komodo_ac_block_subsidy(int nHeight)
void komodo_args(char *argv0)
{
extern int64_t MAX_MONEY;
extern const char *Notaries_elected1[][2];
std::string name,addn; char *dirname,fname[512],arg0str[64],magicstr[9]; uint8_t magic[4],extrabuf[256],*extraptr=0; FILE *fp; uint64_t val; uint16_t port; int32_t i,baseid,len,n,extralen = 0;
IS_KOMODO_NOTARY = GetBoolArg("-notary", false);
if ( (KOMODO_EXCHANGEWALLET= GetBoolArg("-exchange", false)) != 0 )
fprintf(stderr,"KOMODO_EXCHANGEWALLET mode active\n");
DONATION_PUBKEY = GetArg("-donation", "");
NOTARY_PUBKEY = GetArg("-pubkey", "");
if ( strlen(NOTARY_PUBKEY.c_str()) == 66 )
{
USE_EXTERNAL_PUBKEY = 1;
if ( IS_KOMODO_NOTARY == 0 )
{
for (i=0; i<64; i++)
if ( strcmp(NOTARY_PUBKEY.c_str(),Notaries_elected1[i][1]) == 0 )
{
IS_KOMODO_NOTARY = 1;
fprintf(stderr,"running as notary.%d %s\n",i,Notaries_elected1[i][0]);
break;
}
}
//KOMODO_PAX = 1;
} //else KOMODO_PAX = GetArg("-pax",0);
name = GetArg("-ac_name","");
@ -1671,7 +1683,10 @@ void komodo_args(char *argv0)
}
}
}
KOMODO_STOPAT = GetArg("-stopat",0);
ASSETCHAINS_CC = GetArg("-ac_cc",0);
ASSETCHAINS_PUBLIC = GetArg("-ac_public",0);
ASSETCHAINS_PRIVATE = GetArg("-ac_private",0);
if ( (KOMODO_REWIND= GetArg("-rewind",0)) != 0 )
{
printf("KOMODO_REWIND %d\n",KOMODO_REWIND);
@ -1750,7 +1765,7 @@ void komodo_args(char *argv0)
printf("ASSETCHAINS_COMMISSION needs an ASSETCHAINS_OVERRIDE_PUBKEY and cant be more than 100000000 (100%%)\n");
}
if ( ASSETCHAINS_ENDSUBSIDY[0] != 0 || ASSETCHAINS_REWARD[0] != 0 || ASSETCHAINS_HALVING[0] != 0 || ASSETCHAINS_DECAY[0] != 0 || ASSETCHAINS_COMMISSION != 0 )
if ( ASSETCHAINS_ENDSUBSIDY[0] != 0 || ASSETCHAINS_REWARD[0] != 0 || ASSETCHAINS_HALVING[0] != 0 || ASSETCHAINS_DECAY[0] != 0 || ASSETCHAINS_COMMISSION != 0 || ASSETCHAINS_PUBLIC != 0 || ASSETCHAINS_PRIVATE != 0 )
{
printf("perc.%llu\n",(long long)ASSETCHAINS_COMMISSION);
@ -1797,7 +1812,7 @@ void komodo_args(char *argv0)
extralen += iguana_rwnum(1,&extraptr[extralen],sizeof(ASSETCHAINS_LWMAPOS),(void *)&ASSETCHAINS_LWMAPOS);
}
val = ASSETCHAINS_COMMISSION | (((uint64_t)ASSETCHAINS_STAKED & 0xff) << 32) | (((uint64_t)ASSETCHAINS_CC & 0xffffff) << 40);
val = ASSETCHAINS_COMMISSION | (((uint64_t)ASSETCHAINS_STAKED & 0xff) << 32) | (((uint64_t)ASSETCHAINS_CC & 0xffff) << 40) | ((ASSETCHAINS_PUBLIC != 0) << 7) | ((ASSETCHAINS_PRIVATE != 0) << 6);
extralen += iguana_rwnum(1,&extraptr[extralen],sizeof(val),(void *)&val);
}

20
src/listassetchainparams

@ -0,0 +1,20 @@
#!/usr/bin/env python2
import os
import json
def format_param(param, value):
return '-' + param + '=' + value
script_dir = os.path.dirname(__file__)
with open(script_dir + '/assetchains.json') as file:
assetchains = json.load(file)
for chain in assetchains:
params = []
for param, value in chain.items():
if isinstance(value, list):
for dupe_value in value:
params.append(format_param(param, dupe_value))
else:
params.append(format_param(param, value))
print(' '.join(params))

10
src/listassetchains

@ -0,0 +1,10 @@
#!/usr/bin/env python2
import os
import json
script_dir = os.path.dirname(__file__)
with open(script_dir + '/assetchains.json') as file:
assetchains = json.load(file)
for chain in assetchains:
print(chain['ac_name'])

518
src/main.cpp

File diff suppressed because it is too large

5
src/main.h

@ -103,7 +103,8 @@ static const unsigned int DATABASE_FLUSH_INTERVAL = 24 * 60 * 60;
/** Maximum length of reject messages. */
static const unsigned int MAX_REJECT_MESSAGE_LENGTH = 111;
static const bool DEFAULT_ADDRESSINDEX = false;
//static const bool DEFAULT_ADDRESSINDEX = false;
#define DEFAULT_ADDRESSINDEX (GetArg("-ac_cc",0) != 0)
static const bool DEFAULT_TIMESTAMPINDEX = false;
static const bool DEFAULT_SPENTINDEX = false;
static const unsigned int DEFAULT_DB_MAX_OPEN_FILES = 1000;
@ -223,6 +224,8 @@ void ThreadScriptCheck();
void PartitionCheck(bool (*initialDownloadCheck)(), CCriticalSection& cs, const CBlockIndex *const &bestHeader, int64_t nPowTargetSpacing);
/** Check whether we are doing an initial block download (synchronizing from disk or network) */
bool IsInitialBlockDownload();
/** Check if the daemon is in sync */
bool IsInSync();
/** Format a string that describes several potential problems detected by the core */
std::string GetWarnings(const std::string& strFor);
/** Retrieve a transaction (from memory pool, or from disk, if possible) */

2
src/metrics.cpp

@ -233,7 +233,7 @@ int printStats(bool mining)
{
LOCK2(cs_main, cs_vNodes);
height = chainActive.Height();
tipmediantime = chainActive.Tip()->GetMedianTimePast();
tipmediantime = chainActive.LastTip()->GetMedianTimePast();
connections = vNodes.size();
netsolps = GetNetworkHashPS(120, -1);
}

426
src/miner.cpp

@ -11,6 +11,7 @@
#include "amount.h"
#include "base58.h"
#include "chainparams.h"
#include "importcoin.h"
#include "consensus/consensus.h"
#include "consensus/upgrades.h"
#include "consensus/validation.h"
@ -108,34 +109,36 @@ void UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams,
#include "komodo_defs.h"
extern CCriticalSection cs_metrics;
extern int32_t ASSETCHAINS_SEED,IS_KOMODO_NOTARY,USE_EXTERNAL_PUBKEY,KOMODO_CHOSEN_ONE,ASSETCHAIN_INIT,KOMODO_INITDONE,KOMODO_ON_DEMAND,KOMODO_INITDONE,KOMODO_PASSPORT_INITDONE;
extern int32_t KOMODO_LONGESTCHAIN,ASSETCHAINS_SEED,IS_KOMODO_NOTARY,USE_EXTERNAL_PUBKEY,KOMODO_CHOSEN_ONE,ASSETCHAIN_INIT,KOMODO_INITDONE,KOMODO_ON_DEMAND,KOMODO_INITDONE,KOMODO_PASSPORT_INITDONE;
extern uint64_t ASSETCHAINS_COMMISSION, ASSETCHAINS_STAKED;
extern uint64_t ASSETCHAINS_REWARD[ASSETCHAINS_MAX_ERAS], ASSETCHAINS_TIMELOCKGTE, ASSETCHAINS_NONCEMASK[];
extern const char *ASSETCHAINS_ALGORITHMS[];
extern int32_t VERUS_MIN_STAKEAGE, ASSETCHAINS_ALGO, ASSETCHAINS_EQUIHASH, ASSETCHAINS_VERUSHASH, ASSETCHAINS_LASTERA, ASSETCHAINS_LWMAPOS, ASSETCHAINS_NONCESHIFT[], ASSETCHAINS_HASHESPERROUND[];
extern char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN];
extern std::string NOTARY_PUBKEY;
extern std::string NOTARY_PUBKEY,ASSETCHAINS_OVERRIDE_PUBKEY;
void vcalc_sha256(char deprecated[(256 >> 3) * 2 + 1],uint8_t hash[256 >> 3],uint8_t *src,int32_t len);
extern uint8_t NOTARY_PUBKEY33[33],ASSETCHAINS_OVERRIDE_PUBKEY33[33];
uint32_t Mining_start,Mining_height;
int32_t My_notaryid = -1;
int32_t komodo_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33,uint32_t timestamp);
int32_t komodo_pax_opreturn(int32_t height,uint8_t *opret,int32_t maxsize);
//uint64_t komodo_paxtotal();
int32_t komodo_baseid(char *origbase);
//int32_t komodo_is_issuer();
//int32_t komodo_gateway_deposits(CMutableTransaction *txNew,char *symbol,int32_t tokomodo);
//int32_t komodo_isrealtime(int32_t *kmdheightp);
int32_t komodo_validate_interest(const CTransaction &tx,int32_t txheight,uint32_t nTime,int32_t dispflag);
int64_t komodo_block_unlocktime(uint32_t nHeight);
uint64_t komodo_commission(const CBlock *block);
int32_t komodo_staked(CPubKey &pubkey, CMutableTransaction &txNew,uint32_t nBits,uint32_t *blocktimep,uint32_t *txtimep,uint256 *utxotxidp,int32_t *utxovoutp,uint64_t *utxovaluep,uint8_t *utxosig);
int32_t verus_staked(CBlock *pBlock, CPubKey &pubkey, CMutableTransaction &txNew, uint32_t &nBits, arith_uint256 &hashResult, uint8_t *utxosig);
int32_t komodo_staked(CMutableTransaction &txNew,uint32_t nBits,uint32_t *blocktimep,uint32_t *txtimep,uint256 *utxotxidp,int32_t *utxovoutp,uint64_t *utxovaluep,uint8_t *utxosig);
int32_t verus_staked(CBlock *pBlock, CMutableTransaction &txNew, uint32_t &nBits, arith_uint256 &hashResult, uint8_t *utxosig);
int32_t komodo_notaryvin(CMutableTransaction &txNew,uint8_t *notarypub33);
CBlockTemplate* CreateNewBlock(const CScript& _scriptPubKeyIn, bool isStake)
CBlockTemplate* CreateNewBlock(const CScript& _scriptPubKeyIn, int32_t gpucount, bool isStake)
{
CScript scriptPubKeyIn(_scriptPubKeyIn);
uint64_t deposits; int32_t isrealtime,kmdheight; uint32_t blocktime; const CChainParams& chainparams = Params();
// Create new block
//fprintf(stderr,"create new block\n");
// Create new block
if ( gpucount < 0 )
gpucount = KOMODO_MAXGPUCOUNT;
std::unique_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate());
if(!pblocktemplate.get())
{
@ -143,29 +146,7 @@ CBlockTemplate* CreateNewBlock(const CScript& _scriptPubKeyIn, bool isStake)
return NULL;
}
CBlock *pblock = &pblocktemplate->block; // pointer for convenience
/*if ( ASSETCHAINS_SYMBOL[0] != 0 && komodo_baseid(ASSETCHAINS_SYMBOL) >= 0 && chainActive.Tip()->nHeight >= ASSETCHAINS_MINHEIGHT )
{
isrealtime = komodo_isrealtime(&kmdheight);
deposits = komodo_paxtotal();
while ( KOMODO_ON_DEMAND == 0 && deposits == 0 && (int32_t)mempool.GetTotalTxSize() == 0 )
{
deposits = komodo_paxtotal();
if ( KOMODO_PASSPORT_INITDONE == 0 || KOMODO_INITDONE == 0 || (komodo_baseid(ASSETCHAINS_SYMBOL) >= 0 && (isrealtime= komodo_isrealtime(&kmdheight)) == 0) )
{
//fprintf(stderr,"INITDONE.%d RT.%d deposits %.8f ht.%d\n",KOMODO_INITDONE,isrealtime,(double)deposits/COIN,kmdheight);
}
else if ( komodo_isrealtime(&kmdheight) != 0 && (deposits != 0 || (int32_t)mempool.GetTotalTxSize() > 0) )
{
fprintf(stderr,"start CreateNewBlock %s initdone.%d deposit %.8f mempool.%d RT.%u KOMODO_ON_DEMAND.%d\n",ASSETCHAINS_SYMBOL,KOMODO_INITDONE,(double)komodo_paxtotal()/COIN,(int32_t)mempool.GetTotalTxSize(),isrealtime,KOMODO_ON_DEMAND);
break;
}
sleep(10);
}
KOMODO_ON_DEMAND = 0;
if ( 0 && deposits != 0 )
printf("miner KOMODO_DEPOSIT %llu pblock->nHeight %d mempool.GetTotalTxSize(%d)\n",(long long)komodo_paxtotal(),(int32_t)chainActive.Tip()->nHeight,(int32_t)mempool.GetTotalTxSize());
}*/
// -regtest only: allow overriding block.nVersion with
// -regtest only: allow overriding block.nVersion with
// -blockversion=N to test forking scenarios
if (Params().MineBlocksOnDemand())
pblock->nVersion = GetArg("-blockversion", pblock->nVersion);
@ -192,10 +173,10 @@ CBlockTemplate* CreateNewBlock(const CScript& _scriptPubKeyIn, bool isStake)
// Collect memory pool transactions into the block
CAmount nFees = 0;
CBlockIndex* pindexPrev = 0;
{
LOCK2(cs_main, mempool.cs);
CBlockIndex* pindexPrev = chainActive.Tip();
pindexPrev = chainActive.LastTip();
const int nHeight = pindexPrev->nHeight + 1;
uint32_t consensusBranchId = CurrentEpochBranchId(nHeight, chainparams.GetConsensus());
@ -248,48 +229,55 @@ CBlockTemplate* CreateNewBlock(const CScript& _scriptPubKeyIn, bool isStake)
double dPriority = 0;
CAmount nTotalIn = 0;
bool fMissingInputs = false;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
if (tx.IsCoinImport())
{
// Read prev transaction
if (!view.HaveCoins(txin.prevout.hash))
CAmount nValueIn = GetCoinImportValue(tx);
nTotalIn += nValueIn;
dPriority += (double)nValueIn * 1000; // flat multiplier
} else {
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
// This should never happen; all transactions in the memory
// pool should connect to either transactions in the chain
// or other transactions in the memory pool.
if (!mempool.mapTx.count(txin.prevout.hash))
// Read prev transaction
if (!view.HaveCoins(txin.prevout.hash))
{
LogPrintf("ERROR: mempool transaction missing input\n");
if (fDebug) assert("mempool transaction missing input" == 0);
fMissingInputs = true;
if (porphan)
vOrphan.pop_back();
break;
}
// Has to wait for dependencies
if (!porphan)
{
// Use list for automatic deletion
vOrphan.push_back(COrphan(&tx));
porphan = &vOrphan.back();
// This should never happen; all transactions in the memory
// pool should connect to either transactions in the chain
// or other transactions in the memory pool.
if (!mempool.mapTx.count(txin.prevout.hash))
{
LogPrintf("ERROR: mempool transaction missing input\n");
if (fDebug) assert("mempool transaction missing input" == 0);
fMissingInputs = true;
if (porphan)
vOrphan.pop_back();
break;
}
// Has to wait for dependencies
if (!porphan)
{
// Use list for automatic deletion
vOrphan.push_back(COrphan(&tx));
porphan = &vOrphan.back();
}
mapDependers[txin.prevout.hash].push_back(porphan);
porphan->setDependsOn.insert(txin.prevout.hash);
nTotalIn += mempool.mapTx.find(txin.prevout.hash)->GetTx().vout[txin.prevout.n].nValue;
continue;
}
mapDependers[txin.prevout.hash].push_back(porphan);
porphan->setDependsOn.insert(txin.prevout.hash);
nTotalIn += mempool.mapTx.find(txin.prevout.hash)->GetTx().vout[txin.prevout.n].nValue;
continue;
const CCoins* coins = view.AccessCoins(txin.prevout.hash);
assert(coins);
CAmount nValueIn = coins->vout[txin.prevout.n].nValue;
nTotalIn += nValueIn;
int nConf = nHeight - coins->nHeight;
dPriority += (double)nValueIn * nConf;
}
const CCoins* coins = view.AccessCoins(txin.prevout.hash);
assert(coins);
CAmount nValueIn = coins->vout[txin.prevout.n].nValue;
nTotalIn += nValueIn;
int nConf = nHeight - coins->nHeight;
dPriority += (double)nValueIn * nConf;
nTotalIn += tx.GetJoinSplitValueIn();
}
nTotalIn += tx.GetJoinSplitValueIn();
if (fMissingInputs) continue;
// Priority is sum(valuein * age) / modified_txsize
@ -431,28 +419,6 @@ CBlockTemplate* CreateNewBlock(const CScript& _scriptPubKeyIn, bool isStake)
//LogPrintf("CreateNewBlock(): total size %u blocktime.%u nBits.%08x\n", nBlockSize,blocktime,pblock->nBits);
if ( ASSETCHAINS_SYMBOL[0] != 0 && isStake )
{
CPubKey key;
if ( NOTARY_PUBKEY33[0] != 0 )
{
key = CPubKey(ParseHex(NOTARY_PUBKEY));
}
else
{
vector<vector<unsigned char>> vSolutions;
txnouttype whichType;
if (Solver(scriptPubKeyIn, whichType, vSolutions) && !vSolutions.empty())
{
key = CPubKey(vSolutions[0]);
}
else
{
fprintf(stderr,"CreateNewBlock() invalid scriptPubKeyIn\n");
return(0);
}
}
uint64_t txfees,utxovalue; uint32_t txtime; uint256 utxotxid; int32_t i,siglen,numsigs,utxovout; uint8_t utxosig[128],*ptr;
CMutableTransaction txStaked = CreateNewContextualCMutableTransaction(Params().GetConsensus(), chainActive.Height() + 1);
@ -463,7 +429,7 @@ CBlockTemplate* CreateNewBlock(const CScript& _scriptPubKeyIn, bool isStake)
uint32_t nBitsPOS;
arith_uint256 posHash;
siglen = verus_staked(pblock, key, txStaked, nBitsPOS, posHash, utxosig);
siglen = verus_staked(pblock, txStaked, nBitsPOS, posHash, utxosig);
blocktime = GetAdjustedTime();
// change the scriptPubKeyIn to the same output script exactly as the staking transaction
@ -472,20 +438,20 @@ CBlockTemplate* CreateNewBlock(const CScript& _scriptPubKeyIn, bool isStake)
}
else
{
siglen = komodo_staked(key, txStaked, pblock->nBits, &blocktime, &txtime, &utxotxid, &utxovout, &utxovalue, utxosig);
siglen = komodo_staked(txStaked, pblock->nBits, &blocktime, &txtime, &utxotxid, &utxovout, &utxovalue, utxosig);
}
if ( siglen > 0 )
{
CAmount txfees = 0;
if ( GetAdjustedTime() < blocktime-13 )
return(0);
//if ( (int32_t)chainActive.LastTip()->nHeight+1 > 100 && GetAdjustedTime() < blocktime-157 )
// return(0);
pblock->vtx.push_back(txStaked);
pblocktemplate->vTxFees.push_back(txfees);
pblocktemplate->vTxSigOps.push_back(GetLegacySigOpCount(txStaked));
nFees += txfees;
pblock->nTime = blocktime;
//printf("PoS ht.%d t%u\n",(int32_t)chainActive.LastTip()->nHeight+1,blocktime);
//printf("staking PoS ht.%d t%u lag.%u\n",(int32_t)chainActive.LastTip()->nHeight+1,blocktime,(uint32_t)(GetAdjustedTime() - (blocktime-13)));
} else return(0); //fprintf(stderr,"no utxos eligible for staking\n");
}
@ -501,6 +467,9 @@ CBlockTemplate* CreateNewBlock(const CScript& _scriptPubKeyIn, bool isStake)
txNew.nExpiryHeight = 0;
txNew.nLockTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
if ( ASSETCHAINS_SYMBOL[0] == 0 && IS_KOMODO_NOTARY != 0 && My_notaryid >= 0 )
txNew.vout[0].nValue += 5000;
// check if coinbase transactions must be time locked at current subsidy and prepend the time lock
// to transaction if so, cast for GTE operator
if ((uint64_t)(txNew.vout[0].nValue) >= ASSETCHAINS_TIMELOCKGTE)
@ -520,7 +489,7 @@ CBlockTemplate* CreateNewBlock(const CScript& _scriptPubKeyIn, bool isStake)
txNew.vout[1].scriptPubKey = CScriptExt().OpReturnScript(opretScript, OPRETTYPE_TIMELOCK);
txNew.vout[1].nValue = 0;
} // timelocks and commissions are currently incompatible due to validation complexity of the combination
else if ( ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 && ASSETCHAINS_COMMISSION != 0 && (commission= komodo_commission((CBlock*)&pblocktemplate->block)) != 0 )
else if ( nHeight > 1 && ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 && ASSETCHAINS_COMMISSION != 0 && (commission= komodo_commission((CBlock*)&pblocktemplate->block)) != 0 )
{
int32_t i; uint8_t *ptr;
txNew.vout.resize(2);
@ -552,26 +521,38 @@ CBlockTemplate* CreateNewBlock(const CScript& _scriptPubKeyIn, bool isStake)
// Fill in header
pblock->hashPrevBlock = pindexPrev->GetBlockHash();
pblock->hashReserved = uint256();
if ( ASSETCHAINS_SYMBOL[0] == 0 || ASSETCHAINS_STAKED == 0 || NOTARY_PUBKEY33[0] == 0 )
if ( ASSETCHAINS_SYMBOL[0] == 0 || ASSETCHAINS_STAKED == 0 || GetArg("-genproclimit", 0) > 0 )
{
UpdateTime(pblock, Params().GetConsensus(), pindexPrev);
pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
}
pblock->nSolution.clear();
pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]);
if ( ASSETCHAINS_SYMBOL[0] == 0 && NOTARY_PUBKEY33[0] != 0 )
if ( ASSETCHAINS_SYMBOL[0] == 0 && IS_KOMODO_NOTARY != 0 && My_notaryid >= 0 )
{
uint32_t r;
CMutableTransaction txNotary = CreateNewContextualCMutableTransaction(Params().GetConsensus(), chainActive.Height() + 1);
if ( pblock->nTime < pindexPrev->nTime+65 )
pblock->nTime = pindexPrev->nTime + 65;
if ( pblock->nTime < pindexPrev->nTime+60 )
pblock->nTime = pindexPrev->nTime + 60;
if ( gpucount < 33 )
{
uint8_t tmpbuffer[40]; uint32_t r; int32_t n=0; uint256 randvals;
memcpy(&tmpbuffer[n],&My_notaryid,sizeof(My_notaryid)), n += sizeof(My_notaryid);
memcpy(&tmpbuffer[n],&Mining_height,sizeof(Mining_height)), n += sizeof(Mining_height);
memcpy(&tmpbuffer[n],&pblock->hashPrevBlock,sizeof(pblock->hashPrevBlock)), n += sizeof(pblock->hashPrevBlock);
vcalc_sha256(0,(uint8_t *)&randvals,tmpbuffer,n);
memcpy(&r,&randvals,sizeof(r));
pblock->nTime += (r % (33 - gpucount)*(33 - gpucount));
}
if ( komodo_notaryvin(txNotary,NOTARY_PUBKEY33) > 0 )
{
CAmount txfees = 0;
CAmount txfees = 5000;
pblock->vtx.push_back(txNotary);
pblocktemplate->vTxFees.push_back(txfees);
pblocktemplate->vTxSigOps.push_back(GetLegacySigOpCount(txNotary));
nFees += txfees;
pblocktemplate->vTxFees[0] = -nFees;
//*(uint64_t *)(&pblock->vtx[0].vout[0].nValue) += txfees;
//fprintf(stderr,"added notaryvin\n");
}
else
@ -580,18 +561,38 @@ CBlockTemplate* CreateNewBlock(const CScript& _scriptPubKeyIn, bool isStake)
return(0);
}
}
else
else if ( ASSETCHAINS_CC == 0 && pindexPrev != 0 && ASSETCHAINS_STAKED == 0 && (ASSETCHAINS_SYMBOL[0] != 0 || IS_KOMODO_NOTARY == 0 || My_notaryid < 0) )
{
CValidationState state;
if ( !TestBlockValidity(state, *pblock, pindexPrev, false, false))
//fprintf(stderr,"check validity\n");
if ( !TestBlockValidity(state, *pblock, pindexPrev, false, false)) // invokes CC checks
{
//static uint32_t counter;
//if ( counter++ < 100 && ASSETCHAINS_STAKED == 0 )
// fprintf(stderr,"warning: miner testblockvalidity failed\n");
fprintf(stderr,"invalid\n");
return(0);
}
//fprintf(stderr,"valid\n");
}
}
/* skip checking validity outside of lock. if inside lock and CC contract is being validated, can deadlock.
if ( ASSETCHAINS_CC != 0 && pindexPrev != 0 && ASSETCHAINS_STAKED == 0 && (ASSETCHAINS_SYMBOL[0] != 0 || IS_KOMODO_NOTARY == 0 || My_notaryid < 0) )
{
CValidationState state;
//fprintf(stderr,"check validity\n");
if ( !TestBlockValidity(state, *pblock, pindexPrev, false, false)) // invokes CC checks
{
//static uint32_t counter;
//if ( counter++ < 100 && ASSETCHAINS_STAKED == 0 )
// fprintf(stderr,"warning: miner testblockvalidity failed\n");
fprintf(stderr,"invalid\n");
return(0);
}
//fprintf(stderr,"valid\n");
}*/
//fprintf(stderr,"done new block\n");
return pblocktemplate.release();
}
@ -670,10 +671,14 @@ void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int&
// Internal miner
//
CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey, bool isStake)
CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey, int32_t nHeight, int32_t gpucount, bool isStake)
{
CPubKey pubkey; CScript scriptPubKey; uint8_t *script,*ptr; int32_t i;
if ( USE_EXTERNAL_PUBKEY != 0 )
if ( nHeight == 1 && ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 )
{
scriptPubKey = CScript() << ParseHex(ASSETCHAINS_OVERRIDE_PUBKEY) << OP_CHECKSIG;
}
else if ( USE_EXTERNAL_PUBKEY != 0 )
{
//fprintf(stderr,"use notary pubkey\n");
scriptPubKey = CScript() << ParseHex(NOTARY_PUBKEY) << OP_CHECKSIG;
@ -693,7 +698,7 @@ CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey, bool isStake)
script[34] = OP_CHECKSIG;
//scriptPubKey = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
}
return CreateNewBlock(scriptPubKey, isStake);
return CreateNewBlock(scriptPubKey, gpucount, isStake);
}
void komodo_broadcast(CBlock *pblock,int32_t limit)
@ -723,19 +728,19 @@ static bool ProcessBlockFound(CBlock* pblock)
#endif // ENABLE_WALLET
{
LogPrintf("%s\n", pblock->ToString());
LogPrintf("generated %s height.%d\n", FormatMoney(pblock->vtx[0].vout[0].nValue),chainActive.LastTip()->nHeight+1);
// Found a solution
{
LOCK(cs_main);
LogPrintf("generated %s height.%d\n", FormatMoney(pblock->vtx[0].vout[0].nValue),chainActive.Tip()->nHeight+1);
if (pblock->hashPrevBlock != chainActive.Tip()->GetBlockHash())
//LOCK(cs_main);
if (pblock->hashPrevBlock != chainActive.LastTip()->GetBlockHash())
{
uint256 hash; int32_t i;
hash = pblock->hashPrevBlock;
for (i=31; i>=0; i--)
fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
fprintf(stderr," <- prev (stale)\n");
hash = chainActive.Tip()->GetBlockHash();
hash = chainActive.LastTip()->GetBlockHash();
for (i=31; i>=0; i--)
fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
fprintf(stderr," <- chainTip (stale)\n");
@ -756,11 +761,13 @@ static bool ProcessBlockFound(CBlock* pblock)
// Track how many getdata requests this block gets
//if ( 0 )
{
//fprintf(stderr,"lock cs_wallet\n");
LOCK(wallet.cs_wallet);
wallet.mapRequestCount[pblock->GetHash()] = 0;
}
#endif
//fprintf(stderr,"process new block\n");
// Process this block the same as if we had received it from another node
CValidationState state;
if (!ProcessNewBlock(1,chainActive.LastTip()->nHeight+1,state, NULL, pblock, true, NULL))
@ -775,7 +782,7 @@ int32_t komodo_baseid(char *origbase);
int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,uint32_t *blocktimes,int32_t *nonzpkeysp,int32_t height);
arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t height,int32_t goalperc);
int32_t FOUND_BLOCK,KOMODO_MAYBEMINED;
extern int32_t KOMODO_LASTMINED;
extern int32_t KOMODO_LASTMINED,KOMODO_INSYNC;
int32_t roundrobin_delay;
arith_uint256 HASHTarget,HASHTarget_POW;
@ -789,16 +796,16 @@ int32_t waitForPeers(const CChainParams &chainparams)
LOCK(cs_vNodes);
fvNodesEmpty = vNodes.empty();
}
if (fvNodesEmpty)
if (!IsInSync() || fvNodesEmpty)
{
do {
MilliSleep(5000 + rand() % 5000);
MilliSleep(100 + rand() % 400);
{
LOCK(cs_vNodes);
fvNodesEmpty = vNodes.empty();
}
} while (fvNodesEmpty);
MilliSleep(5000 + rand() % 5000);
} while (!IsInSync() || fvNodesEmpty);
MilliSleep(100 + rand() % 400);
}
}
}
@ -806,6 +813,7 @@ int32_t waitForPeers(const CChainParams &chainparams)
#ifdef ENABLE_WALLET
CBlockIndex *get_chainactive(int32_t height)
{
LOCK(cs_main);
if ( chainActive.Tip() != 0 )
{
if ( height <= chainActive.Tip()->nHeight )
@ -842,45 +850,24 @@ void static VerusStaker(CWallet *pwallet)
break;
}
SetThreadPriority(THREAD_PRIORITY_LOWEST);
// try a nice clean peer connection to start
waitForPeers(chainparams);
// try a nice clean peer connection to start
waitForPeers(chainparams);
CBlockIndex* pindexPrev, *pindexCur;
CBlockIndex *pindexPrev, *pindexCur;
do {
{
LOCK(cs_main);
pindexPrev = chainActive.Tip();
}
pindexPrev = chainActive.LastTip();
MilliSleep(5000 + rand() % 5000);
{
LOCK(cs_main);
pindexCur = chainActive.Tip();
}
waitForPeers(chainparams);
pindexCur = chainActive.LastTip();
} while (pindexPrev != pindexCur);
sleep(5);
{
LOCK(cs_main);
printf("Staking height %d for %s\n", chainActive.Tip()->nHeight + 1, ASSETCHAINS_SYMBOL);
//fprintf(stderr,"Staking height %d for %s\n", chainActive.Tip()->nHeight + 1, ASSETCHAINS_SYMBOL);
}
miningTimer.start();
try {
while (true)
{
miningTimer.stop();
waitForPeers(chainparams);
miningTimer.start();
CBlockIndex* pindexPrev = chainActive.LastTip();
printf("Staking height %d for %s\n", pindexPrev->nHeight + 1, ASSETCHAINS_SYMBOL);
// Create new block
unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
CBlockIndex* pindexPrev = chainActive.LastTip();
if ( Mining_height != pindexPrev->nHeight+1 )
{
Mining_height = pindexPrev->nHeight+1;
@ -893,7 +880,7 @@ void static VerusStaker(CWallet *pwallet)
// try to stake a block
CBlockTemplate *ptr = NULL;
if (Mining_height > VERUS_MIN_STAKEAGE)
ptr = CreateNewBlockWithKey(reservekey, true);
ptr = CreateNewBlockWithKey(reservekey, Mining_height, 0, true);
if ( ptr == 0 )
{
@ -952,8 +939,6 @@ void static VerusStaker(CWallet *pwallet)
continue;
}
SetThreadPriority(THREAD_PRIORITY_NORMAL);
int32_t unlockTime = komodo_block_unlocktime(Mining_height);
int64_t subsidy = (int64_t)(pblock->vtx[0].vout[0].nValue);
@ -981,9 +966,8 @@ void static VerusStaker(CWallet *pwallet)
// Check for stop or if block needs to be rebuilt
boost::this_thread::interruption_point();
SetThreadPriority(THREAD_PRIORITY_LOWEST);
sleep(5);
sleep(3);
// In regression test mode, stop mining after a block is found.
if (chainparams.MineBlocksOnDemand()) {
@ -993,17 +977,14 @@ void static VerusStaker(CWallet *pwallet)
}
catch (const boost::thread_interrupted&)
{
miningTimer.stop();
LogPrintf("VerusStaker terminated\n");
throw;
}
catch (const std::runtime_error &e)
{
miningTimer.stop();
LogPrintf("VerusStaker runtime error: %s\n", e.what());
return;
}
miningTimer.stop();
}
void static BitcoinMiner_noeq(CWallet *pwallet)
@ -1036,11 +1017,11 @@ void static BitcoinMiner_noeq()
SetThreadPriority(THREAD_PRIORITY_LOWEST);
// try a nice clean peer connection to start
waitForPeers(chainparams);
CBlockIndex *pindexPrev, *pindexCur;
do {
pindexPrev = chainActive.LastTip();
MilliSleep(5000 + rand() % 5000);
waitForPeers(chainparams);
pindexCur = chainActive.LastTip();
} while (pindexPrev != pindexCur);
@ -1086,7 +1067,7 @@ void static BitcoinMiner_noeq()
miningTimer.start();
#ifdef ENABLE_WALLET
CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey);
CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey, Mining_height, 0);
#else
CBlockTemplate *ptr = CreateNewBlockWithKey();
#endif
@ -1273,13 +1254,13 @@ void static BitcoinMiner_noeq()
catch (const boost::thread_interrupted&)
{
miningTimer.stop();
LogPrintf("KomodoMiner terminated\n");
LogPrintf("%s miner terminated\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
throw;
}
catch (const std::runtime_error &e)
{
miningTimer.stop();
LogPrintf("KomodoMiner runtime error: %s\n", e.what());
LogPrintf("%s miner runtime error: %s\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO], e.what());
return;
}
miningTimer.stop();
@ -1306,15 +1287,17 @@ void static BitcoinMiner()
unsigned int n = chainparams.EquihashN();
unsigned int k = chainparams.EquihashK();
uint8_t *script; uint64_t total,checktoshis; int32_t i,j,notaryid = -1;
while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) //chainActive.Tip()->nHeight != 235300 &&
uint8_t *script; uint64_t total,checktoshis; int32_t i,j,gpucount=KOMODO_MAXGPUCOUNT,notaryid = -1;
while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) )
{
sleep(1);
if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 )
break;
}
komodo_chosennotary(&notaryid,chainActive.Tip()->nHeight,NOTARY_PUBKEY33,(uint32_t)chainActive.Tip()->GetBlockTime());
if ( ASSETCHAINS_SYMBOL[0] == 0 )
komodo_chosennotary(&notaryid,chainActive.LastTip()->nHeight,NOTARY_PUBKEY33,(uint32_t)chainActive.LastTip()->GetBlockTime());
if ( notaryid != My_notaryid )
My_notaryid = notaryid;
std::string solver;
//if ( notaryid >= 0 || ASSETCHAINS_SYMBOL[0] != 0 )
solver = "tromp";
@ -1338,9 +1321,9 @@ void static BitcoinMiner()
fprintf(stderr,"try %s Mining with %s\n",ASSETCHAINS_SYMBOL,solver.c_str());
while (true)
{
if (chainparams.MiningRequiresPeers()) //chainActive.Tip()->nHeight != 235300 &&
if (chainparams.MiningRequiresPeers()) //chainActive.LastTip()->nHeight != 235300 &&
{
//if ( ASSETCHAINS_SEED != 0 && chainActive.Tip()->nHeight < 100 )
//if ( ASSETCHAINS_SEED != 0 && chainActive.LastTip()->nHeight < 100 )
// break;
// Busy-wait for the network to come online so we don't waste time mining
// on an obsolete chain. In regtest mode we expect to fly solo.
@ -1360,16 +1343,11 @@ void static BitcoinMiner()
//fprintf(stderr,"%s Found peers\n",ASSETCHAINS_SYMBOL);
miningTimer.start();
}
/*while ( ASSETCHAINS_SYMBOL[0] != 0 && chainActive.Tip()->nHeight < ASSETCHAINS_MINHEIGHT )
{
fprintf(stderr,"%s waiting for block 100, ht.%d\n",ASSETCHAINS_SYMBOL,chainActive.Tip()->nHeight);
sleep(3);
}*/
//
// Create new block
//
unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
CBlockIndex* pindexPrev = chainActive.Tip();
CBlockIndex* pindexPrev = chainActive.LastTip();
if ( Mining_height != pindexPrev->nHeight+1 )
{
Mining_height = pindexPrev->nHeight+1;
@ -1378,12 +1356,12 @@ void static BitcoinMiner()
if ( ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_STAKED == 0 )
{
//fprintf(stderr,"%s create new block ht.%d\n",ASSETCHAINS_SYMBOL,Mining_height);
sleep(3);
//sleep(3);
}
#ifdef ENABLE_WALLET
// notaries always default to staking
CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey, (ASSETCHAINS_STAKED != 0 && NOTARY_PUBKEY33[0] != 0));
CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey, pindexPrev->nHeight+1, gpucount, ASSETCHAINS_STAKED != 0 && GetArg("-genproclimit", 0) == 0);
#else
CBlockTemplate *ptr = CreateNewBlockWithKey();
#endif
@ -1395,6 +1373,7 @@ void static BitcoinMiner()
sleep(1);
continue;
}
//fprintf(stderr,"get template\n");
unique_ptr<CBlockTemplate> pblocktemplate(ptr);
if (!pblocktemplate.get())
{
@ -1422,18 +1401,20 @@ void static BitcoinMiner()
}
}
IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
//fprintf(stderr,"Running KomodoMiner.%s with %u transactions in block\n",solver.c_str(),(int32_t)pblock->vtx.size());
LogPrintf("Running KomodoMiner.%s with %u transactions in block (%u bytes)\n",solver.c_str(),pblock->vtx.size(),::GetSerializeSize(*pblock,SER_NETWORK,PROTOCOL_VERSION));
//
// Search
//
uint8_t pubkeys[66][33]; uint32_t blocktimes[66]; int mids[256],gpucount,nonzpkeys,i,j,externalflag; uint32_t savebits; int64_t nStart = GetTime();
uint8_t pubkeys[66][33]; arith_uint256 bnMaxPoSdiff; uint32_t blocktimes[66]; int mids[256],nonzpkeys,i,j,externalflag; uint32_t savebits; int64_t nStart = GetTime();
pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
savebits = pblock->nBits;
HASHTarget = arith_uint256().SetCompact(pblock->nBits);
HASHTarget = arith_uint256().SetCompact(savebits);
roundrobin_delay = ROUNDROBIN_DELAY;
if ( ASSETCHAINS_SYMBOL[0] == 0 && notaryid >= 0 )
{
j = 65;
if ( (Mining_height >= 235300 && Mining_height < 236000) || (Mining_height % KOMODO_ELECTION_GAP) > 64 || (Mining_height % KOMODO_ELECTION_GAP) == 0 )
if ( (Mining_height >= 235300 && Mining_height < 236000) || (Mining_height % KOMODO_ELECTION_GAP) > 64 || (Mining_height % KOMODO_ELECTION_GAP) == 0 || Mining_height > 1000000 )
{
int32_t dispflag = 0;
if ( notaryid <= 3 || notaryid == 32 || (notaryid >= 43 && notaryid <= 45) &&notaryid == 51 || notaryid == 52 || notaryid == 56 || notaryid == 57 )
@ -1447,7 +1428,7 @@ void static BitcoinMiner()
if ( i == 33 )
externalflag = 1;
else externalflag = 0;
if ( NOTARY_PUBKEY33[0] != 0 )
if ( IS_KOMODO_NOTARY != 0 )
{
for (i=1; i<66; i++)
if ( memcmp(pubkeys[i],pubkeys[0],33) == 0 )
@ -1465,18 +1446,8 @@ void static BitcoinMiner()
if ( mids[j] == -1 )
gpucount++;
}
if ( gpucount > j/2 )
{
double delta;
if ( notaryid < 0 )
i = (rand() % 64);
else i = ((Mining_height + notaryid) % 64);
delta = sqrt((double)gpucount - j/2) / 2.;
roundrobin_delay += ((delta * i) / 64) - delta;
//fprintf(stderr,"delta.%f %f %f\n",delta,(double)(gpucount - j/3) / 2,(delta * i) / 64);
}
if ( dispflag != 0 )
fprintf(stderr," <- prev minerids from ht.%d notary.%d gpucount.%d %.2f%% t.%u %d\n",pindexPrev->nHeight,notaryid,gpucount,100.*(double)gpucount/j,(uint32_t)time(NULL),roundrobin_delay);
fprintf(stderr," <- prev minerids from ht.%d notary.%d gpucount.%d %.2f%% t.%u\n",pindexPrev->nHeight,notaryid,gpucount,100.*(double)gpucount/j,(uint32_t)time(NULL));
}
for (j=0; j<65; j++)
if ( mids[j] == notaryid )
@ -1491,27 +1462,27 @@ void static BitcoinMiner()
} //else fprintf(stderr,"duplicate at j.%d\n",j);
} else Mining_start = 0;
} else Mining_start = 0;
if ( ASSETCHAINS_STAKED != 0 && NOTARY_PUBKEY33[0] == 0 )
if ( ASSETCHAINS_STAKED != 0 )
{
int32_t percPoS,z;
/*if ( Mining_height <= 100 )
{
sleep(60);
continue;
}*/
int32_t percPoS,z; bool fNegative,fOverflow;
HASHTarget_POW = komodo_PoWtarget(&percPoS,HASHTarget,Mining_height,ASSETCHAINS_STAKED);
for (z=31; z>=0; z--)
fprintf(stderr,"%02x",((uint8_t *)&HASHTarget_POW)[z]);
fprintf(stderr," PoW for staked coin PoS %d%% vs target %d%%\n",percPoS,(int32_t)ASSETCHAINS_STAKED);
HASHTarget.SetCompact(KOMODO_MINDIFF_NBITS,&fNegative,&fOverflow);
if ( ASSETCHAINS_STAKED < 100 )
{
for (z=31; z>=0; z--)
fprintf(stderr,"%02x",((uint8_t *)&HASHTarget_POW)[z]);
fprintf(stderr," PoW for staked coin PoS %d%% vs target %d%%\n",percPoS,(int32_t)ASSETCHAINS_STAKED);
}
}
while (true)
{
/*if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT ) // skips when it shouldnt
{
fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL);
sleep(10);
break;
}*/
if ( KOMODO_INSYNC == 0 )
{
fprintf(stderr,"Mining when blockchain might not be in sync longest.%d vs %d\n",KOMODO_LONGESTCHAIN,Mining_height);
if ( KOMODO_LONGESTCHAIN != 0 && Mining_height >= KOMODO_LONGESTCHAIN )
KOMODO_INSYNC = 1;
sleep(3);
}
// Hash state
KOMODO_CHOSEN_ONE = 0;
@ -1530,7 +1501,7 @@ void static BitcoinMiner()
// (x_1, x_2, ...) = A(I, V, n, k)
LogPrint("pow", "Running Equihash solver \"%s\" with nNonce = %s\n",solver, pblock->nNonce.ToString());
arith_uint256 hashTarget;
if ( NOTARY_PUBKEY33[0] == 0 && ASSETCHAINS_STAKED > 0 && ASSETCHAINS_STAKED <= 100 )
if ( GetArg("-genproclimit", 0) > 0 && ASSETCHAINS_STAKED > 0 && ASSETCHAINS_STAKED < 100 && Mining_height > 10 )
hashTarget = HASHTarget_POW;
else hashTarget = HASHTarget;
std::function<bool(std::vector<unsigned char>)> validBlock =
@ -1547,8 +1518,6 @@ void static BitcoinMiner()
solutionTargetChecks.increment();
B = *pblock;
h = UintToArith256(B.GetHash());
if ( h > hashTarget )
return false;
/*for (z=31; z>=16; z--)
fprintf(stderr,"%02x",((uint8_t *)&h)[z]);
fprintf(stderr," mined ");
@ -1558,13 +1527,19 @@ void static BitcoinMiner()
for (z=31; z>=16; z--)
fprintf(stderr,"%02x",((uint8_t *)&HASHTarget_POW)[z]);
fprintf(stderr," POW\n");*/
if ( NOTARY_PUBKEY33[0] != 0 && B.nTime > GetAdjustedTime() )
if ( h > hashTarget )
{
//if ( ASSETCHAINS_STAKED != 0 && GetArg("-genproclimit", 0) == 0 )
// sleep(1);
return false;
}
if ( IS_KOMODO_NOTARY != 0 && B.nTime > GetAdjustedTime() )
{
fprintf(stderr,"need to wait %d seconds to submit block\n",(int32_t)(B.nTime - GetAdjustedTime()));
//fprintf(stderr,"need to wait %d seconds to submit block\n",(int32_t)(B.nTime - GetAdjustedTime()));
while ( GetAdjustedTime() < B.nTime-2 )
{
sleep(1);
if ( chainActive.Tip()->nHeight >= Mining_height )
if ( chainActive.LastTip()->nHeight >= Mining_height )
{
fprintf(stderr,"new block arrived\n");
return(false);
@ -1573,7 +1548,7 @@ void static BitcoinMiner()
}
if ( ASSETCHAINS_STAKED == 0 )
{
if ( NOTARY_PUBKEY33[0] != 0 )
if ( IS_KOMODO_NOTARY != 0 )
{
int32_t r;
if ( (r= ((Mining_height + NOTARY_PUBKEY33[16]) % 64) / 8) > 0 )
@ -1582,22 +1557,19 @@ void static BitcoinMiner()
}
else
{
if ( NOTARY_PUBKEY33[0] != 0 )
{
printf("need to wait %d seconds to submit staked block\n",(int32_t)(B.nTime - GetAdjustedTime()));
while ( GetAdjustedTime() < B.nTime )
sleep(1);
}
else
while ( B.nTime-57 > GetAdjustedTime() )
{
uint256 tmp = B.GetHash();
int32_t z; for (z=31; z>=0; z--)
fprintf(stderr,"%02x",((uint8_t *)&tmp)[z]);
fprintf(stderr," mined block!\n");
sleep(1);
if ( chainActive.LastTip()->nHeight >= Mining_height )
return(false);
}
uint256 tmp = B.GetHash();
int32_t z; for (z=31; z>=0; z--)
fprintf(stderr,"%02x",((uint8_t *)&tmp)[z]);
fprintf(stderr," mined %s block %d!\n",ASSETCHAINS_SYMBOL,Mining_height);
}
CValidationState state;
if ( !TestBlockValidity(state,B, chainActive.Tip(), true, false))
if ( !TestBlockValidity(state,B, chainActive.LastTip(), true, false))
{
h = UintToArith256(B.GetHash());
for (z=31; z>=0; z--)
@ -1627,8 +1599,6 @@ void static BitcoinMiner()
ehSolverRuns.increment();
throw boost::thread_interrupted();
}
//if ( ASSETCHAINS_SYMBOL[0] == 0 && NOTARY_PUBKEY33[0] != 0 )
// sleep(1800);
return true;
};
std::function<bool(EhSolverCancelCheck)> cancelled = [&m_cs, &cancelSolver](EhSolverCancelCheck pos) {
@ -1719,7 +1689,7 @@ void static BitcoinMiner()
fprintf(stderr,"timeout, break\n");
break;
}
if ( pindexPrev != chainActive.Tip() )
if ( pindexPrev != chainActive.LastTip() )
{
if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
fprintf(stderr,"Tip advanced, break\n");
@ -1778,6 +1748,10 @@ void static BitcoinMiner()
minerThreads = NULL;
}
//fprintf(stderr,"nThreads.%d fGenerate.%d\n",(int32_t)nThreads,fGenerate);
if ( nThreads == 0 && ASSETCHAINS_STAKED )
nThreads = 1;
if ((nThreads == 0 && ASSETCHAINS_LWMAPOS == 0) || !fGenerate)
return;

5
src/miner.h

@ -25,12 +25,13 @@ struct CBlockTemplate
std::vector<CAmount> vTxFees;
std::vector<int64_t> vTxSigOps;
};
#define KOMODO_MAXGPUCOUNT 65
/** Generate a new block, without valid proof-of-work */
CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn, bool isStake = false);
CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn, int32_t gpucount, bool isStake = false);
#ifdef ENABLE_WALLET
boost::optional<CScript> GetMinerScriptPubKey(CReserveKey& reservekey);
CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey, bool isStake = false);
CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey, int32_t nHeight, int32_t gpucount, bool isStake = false);
#else
boost::optional<CScript> GetMinerScriptPubKey();
CBlockTemplate* CreateNewBlockWithKey();

45
src/net.cpp

@ -48,7 +48,8 @@
using namespace std;
namespace {
const int MAX_OUTBOUND_CONNECTIONS = 8;
const int MAX_OUTBOUND_CONNECTIONS = 4;
const int MAX_INBOUND_FROMIP = 3;
struct ListenSocket {
SOCKET socket;
@ -61,6 +62,8 @@ namespace {
//
// Global state variables
//
extern uint16_t ASSETCHAINS_P2PPORT;
bool fDiscover = true;
bool fListen = true;
uint64_t nLocalServices = NODE_NETWORK;
@ -907,11 +910,21 @@ static void AcceptConnection(const ListenSocket& hListenSocket) {
LogPrintf("Warning: Unknown socket family\n");
bool whitelisted = hListenSocket.whitelisted || CNode::IsWhitelistedRange(addr);
int nInboundThisIP = 0;
{
LOCK(cs_vNodes);
struct sockaddr_storage tmpsockaddr;
socklen_t tmplen = sizeof(sockaddr);
BOOST_FOREACH(CNode* pnode, vNodes)
{
if (pnode->fInbound)
{
nInbound++;
if (pnode->addr.GetSockAddr((struct sockaddr*)&tmpsockaddr, &tmplen) && (tmplen == len) && (memcmp(&sockaddr, &tmpsockaddr, tmplen) == 0))
nInboundThisIP++;
}
}
}
if (hSocket == INVALID_SOCKET)
@ -946,6 +959,14 @@ static void AcceptConnection(const ListenSocket& hListenSocket) {
}
}
if (nInboundThisIP >= MAX_INBOUND_FROMIP)
{
// No connection to evict, disconnect the new connection
LogPrint("net", "too many connections from %s, connection refused\n", addr.ToString());
CloseSocket(hSocket);
return;
}
// According to the internet TCP_NODELAY is not carried into accepted sockets
// on all platforms. Set it again here just to be sure.
int set = 1;
@ -1267,8 +1288,12 @@ void ThreadDNSAddressSeed()
int nOneDay = 24*3600;
CAddress addr = CAddress(CService(ip, Params().GetDefaultPort()));
addr.nTime = GetTime() - 3*nOneDay - GetRand(4*nOneDay); // use a random age between 3 and 7 days old
vAdd.push_back(addr);
found++;
// only add seeds with the right port
if (addr.GetPort() == ASSETCHAINS_P2PPORT)
{
vAdd.push_back(addr);
found++;
}
}
}
addrman.Add(vAdd, CNetAddr(seed.name, true));
@ -1279,16 +1304,6 @@ void ThreadDNSAddressSeed()
}
void DumpAddresses()
{
int64_t nStart = GetTimeMillis();
@ -1587,10 +1602,6 @@ void ThreadMessageHandler()
}
bool BindListenPort(const CService &addrBind, string& strError, bool fWhitelisted)
{
strError = "";

2
src/net.h

@ -56,7 +56,7 @@ static const size_t MAPASKFOR_MAX_SZ = MAX_INV_SZ;
/** The maximum number of entries in setAskFor (larger due to getdata latency)*/
static const size_t SETASKFOR_MAX_SZ = 2 * MAX_INV_SZ;
/** The maximum number of peer connections to maintain. */
static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS = 125;
static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS = 384;
/** The period before a network upgrade activates, where connections to upgrading peers are preferred (in blocks). */
static const int NETWORK_UPGRADE_PEER_PREFERENCE_BLOCK_PERIOD = 24 * 24 * 3;

84
src/notarisationdb.cpp

@ -0,0 +1,84 @@
#include "leveldbwrapper.h"
#include "notarisationdb.h"
#include "uint256.h"
#include "cc/eval.h"
#include <boost/foreach.hpp>
NotarisationDB *pnotarisations;
NotarisationDB::NotarisationDB(size_t nCacheSize, bool fMemory, bool fWipe) : CLevelDBWrapper(GetDataDir() / "notarisations", nCacheSize, fMemory, fWipe, false, 64) { }
NotarisationsInBlock ScanBlockNotarisations(const CBlock &block, int nHeight)
{
EvalRef eval;
NotarisationsInBlock vNotarisations;
for (unsigned int i = 0; i < block.vtx.size(); i++) {
CTransaction tx = block.vtx[i];
// Special case for TXSCL. Should prob be removed at some point.
bool isTxscl = 0;
{
NotarisationData data;
if (ParseNotarisationOpReturn(tx, data))
if (strlen(data.symbol) >= 5 && strncmp(data.symbol, "TXSCL", 5) == 0)
isTxscl = 1;
}
if (isTxscl || eval->CheckNotaryInputs(tx, nHeight, block.nTime)) {
NotarisationData data;
if (ParseNotarisationOpReturn(tx, data)) {
vNotarisations.push_back(std::make_pair(tx.GetHash(), data));
//printf("Parsed a notarisation for: %s, txid:%s, ccid:%i, momdepth:%i\n",
// data.symbol, tx.GetHash().GetHex().data(), data.ccId, data.MoMDepth);
//if (!data.MoMoM.IsNull()) printf("MoMoM:%s\n", data.MoMoM.GetHex().data());
}
else
LogPrintf("WARNING: Couldn't parse notarisation for tx: %s at height %i\n",
tx.GetHash().GetHex().data(), nHeight);
}
}
return vNotarisations;
}
bool GetBlockNotarisations(uint256 blockHash, NotarisationsInBlock &nibs)
{
return pnotarisations->Read(blockHash, nibs);
}
bool GetBackNotarisation(uint256 notarisationHash, Notarisation &n)
{
return pnotarisations->Read(notarisationHash, n);
}
/*
* Write an index of KMD notarisation id -> backnotarisation
*/
void WriteBackNotarisations(const NotarisationsInBlock notarisations, CLevelDBBatch &batch)
{
int wrote = 0;
BOOST_FOREACH(const Notarisation &n, notarisations)
{
if (!n.second.txHash.IsNull()) {
batch.Write(n.second.txHash, n);
wrote++;
}
}
}
void EraseBackNotarisations(const NotarisationsInBlock notarisations, CLevelDBBatch &batch)
{
BOOST_FOREACH(const Notarisation &n, notarisations)
{
if (!n.second.txHash.IsNull())
batch.Erase(n.second.txHash);
}
}

27
src/notarisationdb.h

@ -0,0 +1,27 @@
#ifndef NOTARISATIONDB_H
#define NOTARISATIONDB_H
#include "uint256.h"
#include "leveldbwrapper.h"
#include "cc/eval.h"
class NotarisationDB : public CLevelDBWrapper
{
public:
NotarisationDB(size_t nCacheSize, bool fMemory = false, bool fWipe = false);
};
extern NotarisationDB *pnotarisations;
typedef std::pair<uint256,NotarisationData> Notarisation;
typedef std::vector<Notarisation> NotarisationsInBlock;
NotarisationsInBlock ScanBlockNotarisations(const CBlock &block, int nHeight);
bool GetBlockNotarisations(uint256 blockHash, NotarisationsInBlock &nibs);
bool GetBackNotarisation(uint256 notarisationHash, Notarisation &n);
void WriteBackNotarisations(const NotarisationsInBlock notarisations, CLevelDBBatch &batch);
void EraseBackNotarisations(const NotarisationsInBlock notarisations, CLevelDBBatch &batch);
#endif /* NOTARISATIONDB_H */

12
src/pow.cpp

@ -21,7 +21,7 @@
#endif // ENABLE_RUST
uint32_t komodo_chainactive_timestamp();
extern uint32_t ASSETCHAINS_ALGO, ASSETCHAINS_EQUIHASH;
extern uint32_t ASSETCHAINS_ALGO, ASSETCHAINS_EQUIHASH, ASSETCHAINS_STAKED;
extern char ASSETCHAINS_SYMBOL[65];
extern int32_t VERUS_BLOCK_POSUNITS, VERUS_CONSECUTIVE_POS_THRESHOLD, VERUS_NOPOS_THRESHHOLD;
unsigned int lwmaGetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params);
@ -306,6 +306,8 @@ bool CheckEquihashSolution(const CBlockHeader *pblock, const CChainParams& param
unsigned int n = params.EquihashN();
unsigned int k = params.EquihashK();
if ( Params().NetworkIDString() == "regtest" )
return(true);
// Hash state
crypto_generichash_blake2b_state state;
EhInitialiseState(n, k, state);
@ -390,7 +392,7 @@ bool CheckProofOfWork(const CBlockHeader &blkHeader, uint8_t *pubkey33, int32_t
else if ( height >= 80000 && height < 108000 && special2 > 0 )
flag = 1;
else if ( height >= 108000 && special2 > 0 )
flag = ((height % KOMODO_ELECTION_GAP) > 64 || (height % KOMODO_ELECTION_GAP) == 0);
flag = (height > 1000000 || (height % KOMODO_ELECTION_GAP) > 64 || (height % KOMODO_ELECTION_GAP) == 0);
else if ( height == 790833 )
flag = 1;
else if ( special2 < 0 )
@ -409,7 +411,11 @@ bool CheckProofOfWork(const CBlockHeader &blkHeader, uint8_t *pubkey33, int32_t
arith_uint256 bnLimit = (height <= 1 || ASSETCHAINS_ALGO == ASSETCHAINS_EQUIHASH) ? UintToArith256(params.powLimit) : UintToArith256(params.powAlternate);
if (fNegative || bnTarget == 0 || fOverflow || bnTarget > bnLimit)
return error("CheckProofOfWork(): nBits below minimum work");
if ( ASSETCHAINS_STAKED != 0 )
{
arith_uint256 bnMaxPoSdiff;
bnTarget.SetCompact(KOMODO_MINDIFF_NBITS,&fNegative,&fOverflow);
}
// Check proof of work matches claimed amount
if ( UintToArith256(hash = blkHeader.GetHash()) > bnTarget && !blkHeader.IsVerusPOSBlock() )
{

44
src/primitives/block.cpp

@ -87,7 +87,8 @@ uint256 CBlockHeader::GetVerusEntropyHash(int32_t height) const
return GetHash();
}
uint256 CBlock::BuildMerkleTree(bool* fMutated) const
uint256 BuildMerkleTree(bool* fMutated, const std::vector<uint256> leaves,
std::vector<uint256> &vMerkleTree)
{
/* WARNING! If you're reading this because you're learning about crypto
and/or designing a new system that will use merkle trees, keep in mind
@ -100,10 +101,10 @@ uint256 CBlock::BuildMerkleTree(bool* fMutated) const
transactions leading to the same merkle root. For example, these two
trees:
A A
/ \ / \
B C B C
/ \ | / \ / \
A A
/ \ / \
B C B C
/ \ \ / \ / \
D E F D E F F
/ \ / \ / \ / \ / \ / \ / \
1 2 3 4 5 6 1 2 3 4 5 6 5 6
@ -124,13 +125,14 @@ uint256 CBlock::BuildMerkleTree(bool* fMutated) const
known ways of changing the transactions without affecting the merkle
root.
*/
vMerkleTree.clear();
vMerkleTree.reserve(vtx.size() * 2 + 16); // Safe upper bound for the number of total nodes.
for (std::vector<CTransaction>::const_iterator it(vtx.begin()); it != vtx.end(); ++it)
vMerkleTree.push_back(it->GetHash());
vMerkleTree.reserve(leaves.size() * 2 + 16); // Safe upper bound for the number of total nodes.
for (std::vector<uint256>::const_iterator it(leaves.begin()); it != leaves.end(); ++it)
vMerkleTree.push_back(*it);
int j = 0;
bool mutated = false;
for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
for (int nSize = leaves.size(); nSize > 1; nSize = (nSize + 1) / 2)
{
for (int i = 0; i < nSize; i += 2)
{
@ -150,13 +152,20 @@ uint256 CBlock::BuildMerkleTree(bool* fMutated) const
return (vMerkleTree.empty() ? uint256() : vMerkleTree.back());
}
std::vector<uint256> CBlock::GetMerkleBranch(int nIndex) const
uint256 CBlock::BuildMerkleTree(bool* fMutated) const
{
std::vector<uint256> leaves;
for (int i=0; i<vtx.size(); i++) leaves.push_back(vtx[i].GetHash());
return ::BuildMerkleTree(fMutated, leaves, vMerkleTree);
}
std::vector<uint256> GetMerkleBranch(int nIndex, int nLeaves, const std::vector<uint256> &vMerkleTree)
{
if (vMerkleTree.empty())
BuildMerkleTree();
std::vector<uint256> vMerkleBranch;
int j = 0;
for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
for (int nSize = nLeaves; nSize > 1; nSize = (nSize + 1) / 2)
{
int i = std::min(nIndex^1, nSize-1);
vMerkleBranch.push_back(vMerkleTree[j+i]);
@ -166,6 +175,15 @@ std::vector<uint256> CBlock::GetMerkleBranch(int nIndex) const
return vMerkleBranch;
}
std::vector<uint256> CBlock::GetMerkleBranch(int nIndex) const
{
if (vMerkleTree.empty())
BuildMerkleTree();
return ::GetMerkleBranch(nIndex, vtx.size(), vMerkleTree);
}
uint256 CBlock::CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
{
if (nIndex == -1)

6
src/primitives/block.h

@ -229,6 +229,12 @@ public:
};
uint256 BuildMerkleTree(bool* fMutated, const std::vector<uint256> leaves,
std::vector<uint256> &vMerkleTree);
std::vector<uint256> GetMerkleBranch(int nIndex, int nLeaves, const std::vector<uint256> &vMerkleTree);
/**
* Custom serializer for CBlockHeader that omits the nonce and solution, for use
* as input to Equihash.

17
src/primitives/transaction.cpp

@ -232,11 +232,26 @@ CAmount CTransaction::GetJoinSplitValueIn() const
{
// NB: vpub_new "gives" money to the value pool just as inputs do
nValue += it->vpub_new;
if (!MoneyRange(it->vpub_new) || !MoneyRange(nValue))
throw std::runtime_error("CTransaction::GetJoinSplitValueIn(): value out of range");
}
return nValue;
}
CAmount CTransaction::GetJoinSplitValueOut() const
{
CAmount nValue = 0;
for (std::vector<JSDescription>::const_iterator it(vjoinsplit.begin()); it != vjoinsplit.end(); ++it)
{
// NB: vpub_new "gives" money to the value pool just as inputs do
nValue += it->vpub_old;
if (!MoneyRange(it->vpub_old) || !MoneyRange(nValue))
throw std::runtime_error("CTransaction::GetJoinSplitValueOut(): value out of range");
}
return nValue;
}

12
src/primitives/transaction.h

@ -450,6 +450,8 @@ public:
// Return sum of JoinSplit vpub_new
CAmount GetJoinSplitValueIn() const;
// Return sum of JoinSplit vpub_old
CAmount GetJoinSplitValueOut() const;
// Compute priority, given priority of inputs and (optionally) tx size
double ComputePriority(double dPriorityInputs, unsigned int nTxSize=0) const;
@ -457,6 +459,11 @@ public:
// Compute modified tx size for priority calculation (optionally given tx size)
unsigned int CalculateModifiedSize(unsigned int nTxSize=0) const;
bool IsMint() const
{
return IsCoinImport() || IsCoinBase();
}
bool IsCoinBase() const
{
return (vin.size() == 1 && vin[0].prevout.IsNull());
@ -464,6 +471,11 @@ public:
int64_t UnlockTime(uint32_t voutNum) const;
bool IsCoinImport() const
{
return (vin.size() == 1 && vin[0].prevout.n == 10e8);
}
friend bool operator==(const CTransaction& a, const CTransaction& b)
{
return a.hash == b.hash;

7
src/rest.cpp

@ -530,7 +530,7 @@ static bool rest_getutxos(HTTPRequest* req, const std::string& strURIPart)
// serialize data
// use exact same output as mentioned in Bip64
CDataStream ssGetUTXOResponse(SER_NETWORK, PROTOCOL_VERSION);
ssGetUTXOResponse << chainActive.Height() << chainActive.Tip()->GetBlockHash() << bitmap << outs;
ssGetUTXOResponse << chainActive.Height() << chainActive.LastTip()->GetBlockHash() << bitmap << outs;
string ssGetUTXOResponseString = ssGetUTXOResponse.str();
req->WriteHeader("Content-Type", "application/octet-stream");
@ -540,7 +540,7 @@ static bool rest_getutxos(HTTPRequest* req, const std::string& strURIPart)
case RF_HEX: {
CDataStream ssGetUTXOResponse(SER_NETWORK, PROTOCOL_VERSION);
ssGetUTXOResponse << chainActive.Height() << chainActive.Tip()->GetBlockHash() << bitmap << outs;
ssGetUTXOResponse << chainActive.Height() << chainActive.LastTip()->GetBlockHash() << bitmap << outs;
string strHex = HexStr(ssGetUTXOResponse.begin(), ssGetUTXOResponse.end()) + "\n";
req->WriteHeader("Content-Type", "text/plain");
@ -554,7 +554,7 @@ static bool rest_getutxos(HTTPRequest* req, const std::string& strURIPart)
// pack in some essentials
// use more or less the same output as mentioned in Bip64
objGetUTXOResponse.push_back(Pair("chainHeight", chainActive.Height()));
objGetUTXOResponse.push_back(Pair("chaintipHash", chainActive.Tip()->GetBlockHash().GetHex()));
objGetUTXOResponse.push_back(Pair("chaintipHash", chainActive.LastTip()->GetBlockHash().GetHex()));
objGetUTXOResponse.push_back(Pair("bitmap", bitmapStringRepresentation));
UniValue utxos(UniValue::VARR);
@ -563,7 +563,6 @@ static bool rest_getutxos(HTTPRequest* req, const std::string& strURIPart)
utxo.push_back(Pair("txvers", (int32_t)coin.nTxVer));
utxo.push_back(Pair("height", (int32_t)coin.nHeight));
utxo.push_back(Pair("value", ValueFromAmount(coin.out.nValue)));
//utxo.push_back(Pair("interest", ValueFromAmount(komodo_interest(coin.out.nValue,coin.nLockTime,chainActive.Tip()->nTime))));
// include the script in a json output
UniValue o(UniValue::VOBJ);

306
src/rpcblockchain.cpp

@ -7,9 +7,10 @@
#include "chain.h"
#include "chainparams.h"
#include "checkpoints.h"
#include "crosschain.h"
#include "base58.h"
#include "consensus/validation.h"
#include "cc/betprotocol.h"
#include "cc/eval.h"
#include "main.h"
#include "primitives/transaction.h"
#include "rpcserver.h"
@ -37,10 +38,10 @@ double GetDifficultyINTERNAL(const CBlockIndex* blockindex, bool networkDifficul
// minimum difficulty = 1.0.
if (blockindex == NULL)
{
if (chainActive.Tip() == NULL)
if (chainActive.LastTip() == NULL)
return 1.0;
else
blockindex = chainActive.Tip();
blockindex = chainActive.LastTip();
}
uint32_t bits;
@ -171,9 +172,11 @@ UniValue blockToDeltasJSON(const CBlock& block, const CBlockIndex* blockindex)
if (GetSpentIndex(spentKey, spentInfo)) {
if (spentInfo.addressType == 1) {
delta.push_back(Pair("address", CBitcoinAddress(CKeyID(spentInfo.addressHash)).ToString()));
} else if (spentInfo.addressType == 2) {
}
else if (spentInfo.addressType == 2) {
delta.push_back(Pair("address", CBitcoinAddress(CScriptID(spentInfo.addressHash)).ToString()));
} else {
}
else {
continue;
}
delta.push_back(Pair("satoshis", -1 * spentInfo.satoshis));
@ -202,10 +205,21 @@ UniValue blockToDeltasJSON(const CBlock& block, const CBlockIndex* blockindex)
vector<unsigned char> hashBytes(out.scriptPubKey.begin()+2, out.scriptPubKey.begin()+22);
delta.push_back(Pair("address", CBitcoinAddress(CScriptID(uint160(hashBytes))).ToString()));
} else if (out.scriptPubKey.IsPayToPublicKeyHash()) {
}
else if (out.scriptPubKey.IsPayToPublicKeyHash()) {
vector<unsigned char> hashBytes(out.scriptPubKey.begin()+3, out.scriptPubKey.begin()+23);
delta.push_back(Pair("address", CBitcoinAddress(CKeyID(uint160(hashBytes))).ToString()));
} else {
}
else if (out.scriptPubKey.IsPayToPublicKey() || out.scriptPubKey.IsPayToCryptoCondition()) {
CTxDestination address;
if (ExtractDestination(out.scriptPubKey, address))
{
//vector<unsigned char> hashBytes(out.scriptPubKey.begin()+1, out.scriptPubKey.begin()+34);
//xxx delta.push_back(Pair("address", CBitcoinAddress(CKeyID(uint160(hashBytes))).ToString()));
delta.push_back(Pair("address", CBitcoinAddress(address).ToString()));
}
}
else {
continue;
}
@ -313,7 +327,7 @@ UniValue getbestblockhash(const UniValue& params, bool fHelp)
);
LOCK(cs_main);
return chainActive.Tip()->GetBlockHash().GetHex();
return chainActive.LastTip()->GetBlockHash().GetHex();
}
UniValue getdifficulty(const UniValue& params, bool fHelp)
@ -753,35 +767,50 @@ UniValue gettxoutsetinfo(const UniValue& params, bool fHelp)
#define KOMODO_KVDURATION 1440
#define KOMODO_KVBINARY 2
extern char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN];
uint64_t komodo_interest(int32_t txheight,uint64_t nValue,uint32_t nLockTime,uint32_t tiptime);
uint64_t komodo_paxprice(uint64_t *seedp,int32_t height,char *base,char *rel,uint64_t basevolume);
int32_t komodo_paxprices(int32_t *heights,uint64_t *prices,int32_t max,char *base,char *rel);
int32_t komodo_notaries(uint8_t pubkeys[64][33],int32_t height,uint32_t timestamp);
char *bitcoin_address(char *coinaddr,uint8_t addrtype,uint8_t *pubkey_or_rmd160,int32_t len);
//uint32_t komodo_interest_args(int32_t *txheightp,uint32_t *tiptimep,uint64_t *valuep,uint256 hash,int32_t n);
int32_t komodo_minerids(uint8_t *minerids,int32_t height,int32_t width);
int32_t komodo_kvsearch(uint256 *refpubkeyp,int32_t current_height,uint32_t *flagsp,int32_t *heightp,uint8_t value[IGUANA_MAXSCRIPTSIZE],uint8_t *key,int32_t keylen);
int32_t komodo_MoM(int32_t *notarized_htp,uint256 *MoMp,uint256 *kmdtxidp,int32_t nHeight,uint256 *MoMoMp,int32_t *MoMoMoffsetp,int32_t *MoMoMdepthp,int32_t *kmdstartip,int32_t *kmdendip);
int32_t komodo_MoMoMdata(char *hexstr,int32_t hexsize,struct komodo_ccdataMoMoM *mdata,char *symbol,int32_t kmdheight,int32_t notarized_height);
struct komodo_ccdata_entry *komodo_allMoMs(int32_t *nump,uint256 *MoMoMp,int32_t kmdstarti,int32_t kmdendi);
uint256 komodo_calcMoM(int32_t height,int32_t MoMdepth);
UniValue kvsearch(const UniValue& params, bool fHelp)
{
UniValue ret(UniValue::VOBJ); uint32_t flags; uint8_t value[IGUANA_MAXSCRIPTSIZE],key[IGUANA_MAXSCRIPTSIZE]; int32_t duration,j,height,valuesize,keylen; uint256 refpubkey; static uint256 zeroes;
if (fHelp || params.size() != 1 )
throw runtime_error("kvsearch key");
throw runtime_error(
"kvsearch key\n"
"\nSearch for a key stored via the kvupdate command. This feature is only available for asset chains.\n"
"\nArguments:\n"
"1. key (string, required) search the chain for this key\n"
"\nResult:\n"
"{\n"
" \"coin\": \"xxxxx\", (string) chain the key is stored on\n"
" \"currentheight\": xxxxx, (numeric) current height of the chain\n"
" \"key\": \"xxxxx\", (string) key\n"
" \"keylen\": xxxxx, (string) length of the key \n"
" \"owner\": \"xxxxx\" (string) hex string representing the owner of the key \n"
" \"height\": xxxxx, (numeric) height the key was stored at\n"
" \"expiration\": xxxxx, (numeric) height the key will expire\n"
" \"flags\": x (numeric) 1 if the key was created with a password; 0 otherwise.\n"
" \"value\": \"xxxxx\", (string) stored value\n"
" \"valuesize\": xxxxx (string) amount of characters stored\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("kvsearch", "examplekey")
+ HelpExampleRpc("kvsearch", "examplekey")
);
LOCK(cs_main);
if ( (keylen= (int32_t)strlen(params[0].get_str().c_str())) > 0 )
{
ret.push_back(Pair("coin",(char *)(ASSETCHAINS_SYMBOL[0] == 0 ? "KMD" : ASSETCHAINS_SYMBOL)));
ret.push_back(Pair("currentheight", (int64_t)chainActive.Tip()->nHeight));
ret.push_back(Pair("currentheight", (int64_t)chainActive.LastTip()->nHeight));
ret.push_back(Pair("key",params[0].get_str()));
ret.push_back(Pair("keylen",keylen));
if ( keylen < sizeof(key) )
{
memcpy(key,params[0].get_str().c_str(),keylen);
if ( (valuesize= komodo_kvsearch(&refpubkey,chainActive.Tip()->nHeight,&flags,&height,value,key,keylen)) >= 0 )
if ( (valuesize= komodo_kvsearch(&refpubkey,chainActive.LastTip()->nHeight,&flags,&height,value,key,keylen)) >= 0 )
{
std::string val; char *valuestr;
val.resize(valuesize);
@ -801,221 +830,6 @@ UniValue kvsearch(const UniValue& params, bool fHelp)
return ret;
}
UniValue allMoMs(const UniValue& params, bool fHelp)
{
struct komodo_ccdata_entry *allMoMs; uint256 MoMoM; int32_t num,i,kmdstarti,kmdendi; UniValue ret(UniValue::VOBJ); UniValue a(UniValue::VARR);
if ( fHelp || params.size() != 2 )
throw runtime_error("allMoMs kmdstarti kmdendi\n");
LOCK(cs_main);
kmdstarti = atoi(params[0].get_str().c_str());
kmdendi = atoi(params[1].get_str().c_str());
ret.push_back(Pair("kmdstarti",kmdstarti));
ret.push_back(Pair("kmdendi",kmdendi));
if ( (allMoMs= komodo_allMoMs(&num,&MoMoM,kmdstarti,kmdendi)) != 0 )
{
for (i=0; i<num; i++)
{
UniValue item(UniValue::VOBJ);
item.push_back(Pair("MoM",allMoMs[i].MoM.ToString()));
item.push_back(Pair("coin",allMoMs[i].symbol));
item.push_back(Pair("notarized_height",allMoMs[i].notarized_height));
item.push_back(Pair("kmdheight",allMoMs[i].kmdheight));
item.push_back(Pair("txi",allMoMs[i].txi));
a.push_back(item);
}
ret.push_back(Pair("MoMs",a));
ret.push_back(Pair("MoMoM",MoMoM.ToString()));
ret.push_back(Pair("MoMoMdepth",(int)num));
free(allMoMs);
}
return(ret);
}
UniValue MoMoMdata(const UniValue& params, bool fHelp)
{
char *symbol,hexstr[16384+1]; struct komodo_ccdataMoMoM mdata; int32_t i,kmdheight,notarized_height; UniValue ret(UniValue::VOBJ); UniValue a(UniValue::VARR);
if ( fHelp || params.size() != 3 )
throw runtime_error("MoMoMdata symbol kmdheight notarized_height\n");
LOCK(cs_main);
symbol = (char *)params[0].get_str().c_str();
kmdheight = atoi(params[1].get_str().c_str());
notarized_height = atoi(params[2].get_str().c_str());
ret.push_back(Pair("coin",symbol));
ret.push_back(Pair("kmdheight",kmdheight));
ret.push_back(Pair("notarized_height",notarized_height));
memset(&mdata,0,sizeof(mdata));
if ( komodo_MoMoMdata(hexstr,sizeof(hexstr),&mdata,symbol,kmdheight,notarized_height) == 0 )
{
ret.push_back(Pair("kmdstarti",mdata.kmdstarti));
ret.push_back(Pair("kmdendi",mdata.kmdendi));
ret.push_back(Pair("MoMoM",mdata.MoMoM.ToString()));
ret.push_back(Pair("MoMoMdepth",mdata.MoMoMdepth));
ret.push_back(Pair("numnotarizations",mdata.numpairs));
if ( mdata.pairs != 0 )
{
//fprintf(stderr,"mdata.pairs free %p, numpairs.%d\n",mdata.pairs,mdata.numpairs);
for (i=0; i<mdata.numpairs; i++)
{
UniValue item(UniValue::VOBJ);
item.push_back(Pair("height",(int)mdata.pairs[i].notarized_height));
item.push_back(Pair("MoMoMoffset",(int)mdata.pairs[i].MoMoMoffset));
a.push_back(item);
}
free(mdata.pairs);
}
ret.push_back(Pair("notarizations",a));
ret.push_back(Pair("data",hexstr));
} else ret.push_back(Pair("error","cant calculate MoMoM"));
return(ret);
}
UniValue calc_MoM(const UniValue& params, bool fHelp)
{
int32_t height,MoMdepth; uint256 MoM; UniValue ret(UniValue::VOBJ); UniValue a(UniValue::VARR);
if ( fHelp || params.size() != 2 )
throw runtime_error("calc_MoM height MoMdepth\n");
LOCK(cs_main);
height = atoi(params[0].get_str().c_str());
MoMdepth = atoi(params[1].get_str().c_str());
if ( height <= 0 || MoMdepth <= 0 || MoMdepth >= height )
throw runtime_error("calc_MoM illegal height or MoMdepth\n");
//fprintf(stderr,"height_MoM height.%d\n",height);
MoM = komodo_calcMoM(height,MoMdepth);
ret.push_back(Pair("coin",(char *)(ASSETCHAINS_SYMBOL[0] == 0 ? "KMD" : ASSETCHAINS_SYMBOL)));
ret.push_back(Pair("height",height));
ret.push_back(Pair("MoMdepth",MoMdepth));
ret.push_back(Pair("MoM",MoM.GetHex()));
return ret;
}
UniValue height_MoM(const UniValue& params, bool fHelp)
{
int32_t height,depth,notarized_height,MoMoMdepth,MoMoMoffset,kmdstarti,kmdendi; uint256 MoM,MoMoM,kmdtxid; uint32_t timestamp = 0; UniValue ret(UniValue::VOBJ); UniValue a(UniValue::VARR);
if ( fHelp || params.size() != 1 )
throw runtime_error("height_MoM height\n");
LOCK(cs_main);
height = atoi(params[0].get_str().c_str());
if ( height <= 0 )
{
if ( chainActive.Tip() == 0 )
{
ret.push_back(Pair("error",(char *)"no active chain yet"));
return(ret);
}
height = chainActive.Tip()->nHeight;
}
//fprintf(stderr,"height_MoM height.%d\n",height);
depth = komodo_MoM(&notarized_height,&MoM,&kmdtxid,height,&MoMoM,&MoMoMoffset,&MoMoMdepth,&kmdstarti,&kmdendi);
ret.push_back(Pair("coin",(char *)(ASSETCHAINS_SYMBOL[0] == 0 ? "KMD" : ASSETCHAINS_SYMBOL)));
ret.push_back(Pair("height",height));
ret.push_back(Pair("timestamp",(uint64_t)timestamp));
if ( depth > 0 )
{
ret.push_back(Pair("depth",depth));
ret.push_back(Pair("notarized_height",notarized_height));
ret.push_back(Pair("MoM",MoM.GetHex()));
ret.push_back(Pair("kmdtxid",kmdtxid.GetHex()));
if ( ASSETCHAINS_SYMBOL[0] != 0 )
{
ret.push_back(Pair("MoMoM",MoMoM.GetHex()));
ret.push_back(Pair("MoMoMoffset",MoMoMoffset));
ret.push_back(Pair("MoMoMdepth",MoMoMdepth));
ret.push_back(Pair("kmdstarti",kmdstarti));
ret.push_back(Pair("kmdendi",kmdendi));
}
} else ret.push_back(Pair("error",(char *)"no MoM for height"));
return ret;
}
UniValue txMoMproof(const UniValue& params, bool fHelp)
{
uint256 hash, notarisationHash, MoM,MoMoM; int32_t notarisedHeight, depth; CBlockIndex* blockIndex;
std::vector<uint256> branch;
int nIndex,MoMoMdepth,MoMoMoffset,kmdstarti,kmdendi;
// parse params and get notarisation data for tx
{
if ( fHelp || params.size() != 1)
throw runtime_error("txMoMproof needs a txid");
hash = uint256S(params[0].get_str());
uint256 blockHash;
CTransaction tx;
if (!GetTransaction(hash, tx, blockHash, true))
throw runtime_error("cannot find transaction");
blockIndex = mapBlockIndex[blockHash];
depth = komodo_MoM(&notarisedHeight, &MoM, &notarisationHash, blockIndex->nHeight,&MoMoM,&MoMoMoffset,&MoMoMdepth,&kmdstarti,&kmdendi);
if (!depth)
throw runtime_error("notarisation not found");
// index of block in MoM leaves
nIndex = notarisedHeight - blockIndex->nHeight;
}
// build merkle chain from blocks to MoM
{
// since the merkle branch code is tied up in a block class
// and we want to make a merkle branch for something that isnt transactions
CBlock fakeBlock;
for (int i=0; i<depth; i++) {
uint256 mRoot = chainActive[notarisedHeight - i]->hashMerkleRoot;
CTransaction fakeTx;
// first value in CTransaction memory is it's hash
memcpy((void*)&fakeTx, mRoot.begin(), 32);
fakeBlock.vtx.push_back(fakeTx);
}
branch = fakeBlock.GetMerkleBranch(nIndex);
// Check branch
if (MoM != CBlock::CheckMerkleBranch(blockIndex->hashMerkleRoot, branch, nIndex))
throw JSONRPCError(RPC_INTERNAL_ERROR, "Failed merkle block->MoM");
}
// Now get the tx merkle branch
{
CBlock block;
if (fHavePruned && !(blockIndex->nStatus & BLOCK_HAVE_DATA) && blockIndex->nTx > 0)
throw JSONRPCError(RPC_INTERNAL_ERROR, "Block not available (pruned data)");
if(!ReadBlockFromDisk(block, blockIndex,1))
throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk");
// Locate the transaction in the block
int nTxIndex;
for (nTxIndex = 0; nTxIndex < (int)block.vtx.size(); nTxIndex++)
if (block.vtx[nTxIndex].GetHash() == hash)
break;
if (nTxIndex == (int)block.vtx.size())
throw JSONRPCError(RPC_INTERNAL_ERROR, "Error locating tx in block");
std::vector<uint256> txBranch = block.GetMerkleBranch(nTxIndex);
// Check branch
if (block.hashMerkleRoot != CBlock::CheckMerkleBranch(hash, txBranch, nTxIndex))
throw JSONRPCError(RPC_INTERNAL_ERROR, "Failed merkle tx->block");
// concatenate branches
nIndex = (nIndex << txBranch.size()) + nTxIndex;
branch.insert(branch.begin(), txBranch.begin(), txBranch.end());
}
// Check the proof
if (MoM != CBlock::CheckMerkleBranch(hash, branch, nIndex))
throw JSONRPCError(RPC_INTERNAL_ERROR, "Failed validating MoM");
// Encode and return
CDataStream ssProof(SER_NETWORK, PROTOCOL_VERSION);
ssProof << MoMProof(nIndex, branch, notarisationHash);
return HexStr(ssProof.begin(), ssProof.end());
}
UniValue minerids(const UniValue& params, bool fHelp)
{
uint32_t timestamp = 0; UniValue ret(UniValue::VOBJ); UniValue a(UniValue::VARR); uint8_t minerids[2000],pubkeys[65][33]; int32_t i,j,n,numnotaries,tally[129];
@ -1024,7 +838,7 @@ UniValue minerids(const UniValue& params, bool fHelp)
LOCK(cs_main);
int32_t height = atoi(params[0].get_str().c_str());
if ( height <= 0 )
height = chainActive.Tip()->nHeight;
height = chainActive.LastTip()->nHeight;
else
{
CBlockIndex *pblockindex = chainActive[height];
@ -1086,8 +900,8 @@ UniValue notaries(const UniValue& params, bool fHelp)
else timestamp = (uint32_t)time(NULL);
if ( height < 0 )
{
height = chainActive.Tip()->nHeight;
timestamp = chainActive.Tip()->GetBlockTime();
height = chainActive.LastTip()->nHeight;
timestamp = chainActive.LastTip()->GetBlockTime();
}
else if ( params.size() < 2 )
{
@ -1106,14 +920,14 @@ UniValue notaries(const UniValue& params, bool fHelp)
for (j=0; j<33; j++)
sprintf(&hexstr[j*2],"%02x",pubkeys[i][j]);
item.push_back(Pair("pubkey", hex));
bitcoin_address(btcaddr,0,pubkeys[i],33);
m = (int32_t)strlen(btcaddr);
btcaddress.resize(m);
ptr = (char *)btcaddress.data();
memcpy(ptr,btcaddr,m);
item.push_back(Pair("BTCaddress", btcaddress));
bitcoin_address(kmdaddr,60,pubkeys[i],33);
m = (int32_t)strlen(kmdaddr);
kmdaddress.resize(m);
@ -1175,7 +989,7 @@ UniValue paxprice(const UniValue& params, bool fHelp)
std::string rel = params[1].get_str();
int32_t height;
if ( params.size() == 2 )
height = chainActive.Tip()->nHeight;
height = chainActive.LastTip()->nHeight;
else height = atoi(params[2].get_str().c_str());
//if ( params.size() == 3 || (basevolume= COIN * atof(params[3].get_str().c_str())) == 0 )
basevolume = 100000;
@ -1261,8 +1075,8 @@ UniValue gettxout(const UniValue& params, bool fHelp)
" \"hex\" : \"hex\", (string) \n"
" \"reqSigs\" : n, (numeric) Number of required signatures\n"
" \"type\" : \"pubkeyhash\", (string) The type, eg pubkeyhash\n"
" \"addresses\" : [ (array of string) array of Zcash addresses\n"
" \"zcashaddress\" (string) Zcash address\n"
" \"addresses\" : [ (array of string) array of Komodo addresses\n"
" \"komodoaddress\" (string) Komodo address\n"
" ,...\n"
" ]\n"
" },\n"
@ -1467,10 +1281,10 @@ UniValue getblockchaininfo(const UniValue& params, bool fHelp)
obj.push_back(Pair("chain", Params().NetworkIDString()));
obj.push_back(Pair("blocks", (int)chainActive.Height()));
obj.push_back(Pair("headers", pindexBestHeader ? pindexBestHeader->nHeight : -1));
obj.push_back(Pair("bestblockhash", chainActive.Tip()->GetBlockHash().GetHex()));
obj.push_back(Pair("bestblockhash", chainActive.LastTip()->GetBlockHash().GetHex()));
obj.push_back(Pair("difficulty", (double)GetNetworkDifficulty()));
obj.push_back(Pair("verificationprogress", Checkpoints::GuessVerificationProgress(Params().Checkpoints(), chainActive.Tip())));
obj.push_back(Pair("chainwork", chainActive.Tip()->nChainWork.GetHex()));
obj.push_back(Pair("verificationprogress", Checkpoints::GuessVerificationProgress(Params().Checkpoints(), chainActive.LastTip())));
obj.push_back(Pair("chainwork", chainActive.LastTip()->nChainWork.GetHex()));
obj.push_back(Pair("pruned", fPruneMode));
ZCIncrementalMerkleTree tree;
@ -1481,7 +1295,7 @@ UniValue getblockchaininfo(const UniValue& params, bool fHelp)
obj.push_back(Pair("commitments", tree.size()));
#endif
CBlockIndex* tip = chainActive.Tip();
CBlockIndex* tip = chainActive.LastTip();
UniValue valuePools(UniValue::VARR);
valuePools.push_back(ValuePoolDesc("sprout", tip->nChainSproutValue, boost::none));
obj.push_back(Pair("valuePools", valuePools));
@ -1506,7 +1320,7 @@ UniValue getblockchaininfo(const UniValue& params, bool fHelp)
if (fPruneMode)
{
CBlockIndex *block = chainActive.Tip();
CBlockIndex *block = chainActive.LastTip();
while (block && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA))
block = block->pprev;
@ -1581,7 +1395,7 @@ UniValue getchaintips(const UniValue& params, bool fHelp)
}
// Always report the currently active tip.
setTips.insert(chainActive.Tip());
setTips.insert(chainActive.LastTip());
/* Construct the output array. */
UniValue res(UniValue::VARR); const CBlockIndex *forked;

13
src/rpcclient.cpp

@ -134,17 +134,20 @@ static const CRPCConvertParam vRPCConvertParams[] =
{ "paxprices", 3 },
{ "paxpending", 0 },
{ "notaries", 2 },
{ "height_MoM", 1 },
{ "MoMoMdata", 3 },
{ "allMoMs", 2 },
{ "txMoMproof", 1 },
{ "minerids", 1 },
{ "kvsearch", 1 },
{ "kvupdate", 4 },
{ "z_importkey", 2 },
{ "z_importviewingkey", 2 },
{ "z_getpaymentdisclosure", 1},
{ "z_getpaymentdisclosure", 2}
{ "z_getpaymentdisclosure", 2},
// crosschain
{ "assetchainproof", 1},
{ "crosschainproof", 1},
{ "getproofroot", 2},
{ "height_MoM", 1},
{ "calc_MoM", 2},
};
class CRPCConvertTable

253
src/rpccrosschain.cpp

@ -0,0 +1,253 @@
#include "amount.h"
#include "chain.h"
#include "chainparams.h"
#include "checkpoints.h"
#include "crosschain.h"
#include "importcoin.h"
#include "base58.h"
#include "consensus/validation.h"
#include "cc/eval.h"
#include "cc/utils.h"
#include "main.h"
#include "primitives/transaction.h"
#include "rpcserver.h"
#include "sync.h"
#include "util.h"
#include "script/script.h"
#include "script/script_error.h"
#include "script/sign.h"
#include "script/standard.h"
#include <stdint.h>
#include <univalue.h>
#include <regex>
using namespace std;
int32_t komodo_MoM(int32_t *notarized_htp,uint256 *MoMp,uint256 *kmdtxidp,int32_t nHeight,uint256 *MoMoMp,int32_t *MoMoMoffsetp,int32_t *MoMoMdepthp,int32_t *kmdstartip,int32_t *kmdendip);
int32_t komodo_MoMoMdata(char *hexstr,int32_t hexsize,struct komodo_ccdataMoMoM *mdata,char *symbol,int32_t kmdheight,int32_t notarized_height);
struct komodo_ccdata_entry *komodo_allMoMs(int32_t *nump,uint256 *MoMoMp,int32_t kmdstarti,int32_t kmdendi);
uint256 komodo_calcMoM(int32_t height,int32_t MoMdepth);
UniValue assetchainproof(const UniValue& params, bool fHelp)
{
uint256 hash;
// parse params and get notarisation data for tx
if ( fHelp || params.size() != 1)
throw runtime_error("assetchainproof needs a txid");
hash = uint256S(params[0].get_str());
auto proof = GetAssetchainProof(hash);
auto proofData = E_MARSHAL(ss << proof);
return HexStr(proofData);
}
UniValue crosschainproof(const UniValue& params, bool fHelp)
{
}
UniValue height_MoM(const UniValue& params, bool fHelp)
{
int32_t height,depth,notarized_height,MoMoMdepth,MoMoMoffset,kmdstarti,kmdendi; uint256 MoM,MoMoM,kmdtxid; uint32_t timestamp = 0; UniValue ret(UniValue::VOBJ); UniValue a(UniValue::VARR);
if ( fHelp || params.size() != 1 )
throw runtime_error("height_MoM height\n");
LOCK(cs_main);
height = atoi(params[0].get_str().c_str());
if ( height <= 0 )
{
if ( chainActive.Tip() == 0 )
{
ret.push_back(Pair("error",(char *)"no active chain yet"));
return(ret);
}
height = chainActive.Tip()->nHeight;
}
//fprintf(stderr,"height_MoM height.%d\n",height);
depth = komodo_MoM(&notarized_height,&MoM,&kmdtxid,height,&MoMoM,&MoMoMoffset,&MoMoMdepth,&kmdstarti,&kmdendi);
ret.push_back(Pair("coin",(char *)(ASSETCHAINS_SYMBOL[0] == 0 ? "KMD" : ASSETCHAINS_SYMBOL)));
ret.push_back(Pair("height",height));
ret.push_back(Pair("timestamp",(uint64_t)timestamp));
if ( depth > 0 )
{
ret.push_back(Pair("depth",depth));
ret.push_back(Pair("notarized_height",notarized_height));
ret.push_back(Pair("MoM",MoM.GetHex()));
ret.push_back(Pair("kmdtxid",kmdtxid.GetHex()));
if ( ASSETCHAINS_SYMBOL[0] != 0 )
{
ret.push_back(Pair("MoMoM",MoMoM.GetHex()));
ret.push_back(Pair("MoMoMoffset",MoMoMoffset));
ret.push_back(Pair("MoMoMdepth",MoMoMdepth));
ret.push_back(Pair("kmdstarti",kmdstarti));
ret.push_back(Pair("kmdendi",kmdendi));
}
} else ret.push_back(Pair("error",(char *)"no MoM for height"));
return ret;
}
UniValue MoMoMdata(const UniValue& params, bool fHelp)
{
if ( fHelp || params.size() != 3 )
throw runtime_error("MoMoMdata symbol kmdheight ccid\n");
UniValue ret(UniValue::VOBJ);
char* symbol = (char *)params[0].get_str().c_str();
int kmdheight = atoi(params[1].get_str().c_str());
uint32_t ccid = atoi(params[2].get_str().c_str());
ret.push_back(Pair("coin",symbol));
ret.push_back(Pair("kmdheight",kmdheight));
ret.push_back(Pair("ccid", (int) ccid));
uint256 destNotarisationTxid;
std::vector<uint256> moms;
uint256 MoMoM = CalculateProofRoot(symbol, ccid, kmdheight, moms, destNotarisationTxid);
UniValue valMoms(UniValue::VARR);
for (int i=0; i<moms.size(); i++) valMoms.push_back(moms[i].GetHex());
ret.push_back(Pair("MoMs", valMoms));
ret.push_back(Pair("notarization_hash", destNotarisationTxid.GetHex()));
ret.push_back(Pair("MoMoM", MoMoM.GetHex()));
auto vmomomdata = E_MARSHAL(ss << MoMoM; ss << ((uint32_t)0));
ret.push_back(Pair("data", HexStr(vmomomdata)));
return ret;
}
UniValue calc_MoM(const UniValue& params, bool fHelp)
{
int32_t height,MoMdepth; uint256 MoM; UniValue ret(UniValue::VOBJ); UniValue a(UniValue::VARR);
if ( fHelp || params.size() != 2 )
throw runtime_error("calc_MoM height MoMdepth\n");
LOCK(cs_main);
height = atoi(params[0].get_str().c_str());
MoMdepth = atoi(params[1].get_str().c_str());
if ( height <= 0 || MoMdepth <= 0 || MoMdepth >= height )
throw runtime_error("calc_MoM illegal height or MoMdepth\n");
//fprintf(stderr,"height_MoM height.%d\n",height);
MoM = komodo_calcMoM(height,MoMdepth);
ret.push_back(Pair("coin",(char *)(ASSETCHAINS_SYMBOL[0] == 0 ? "KMD" : ASSETCHAINS_SYMBOL)));
ret.push_back(Pair("height",height));
ret.push_back(Pair("MoMdepth",MoMdepth));
ret.push_back(Pair("MoM",MoM.GetHex()));
return ret;
}
UniValue migrate_converttoexport(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 3)
throw runtime_error(
"migrate_converttoexport rawTx dest_symbol export_amount\n"
"\nConvert a raw transaction to a cross-chain export.\n"
"If neccesary, the transaction should be funded using fundrawtransaction.\n"
"Finally, the transaction should be signed using signrawtransaction\n"
"The finished export transaction, plus the payouts, should be passed to "
"the \"migrate_createimporttransaction\" method on a KMD node to get the corresponding "
"import transaction.\n"
);
if (ASSETCHAINS_CC < KOMODO_FIRSTFUNGIBLEID)
throw runtime_error("-ac_cc < KOMODO_FIRSTFUNGIBLEID");
if (ASSETCHAINS_SYMBOL[0] == 0)
throw runtime_error("Must be called on assetchain");
vector<uint8_t> txData(ParseHexV(params[0], "argument 1"));
CMutableTransaction tx;
if (!E_UNMARSHAL(txData, ss >> tx))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
string targetSymbol = params[1].get_str();
if (targetSymbol.size() == 0 || targetSymbol.size() > 32)
throw runtime_error("targetSymbol length must be >0 and <=32");
CAmount burnAmount = AmountFromValue(params[2]);
if (burnAmount <= 0)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for export");
{
CAmount needed = 0;
for (int i=0; i<tx.vout.size(); i++) needed += tx.vout[i].nValue;
if (burnAmount < needed)
throw runtime_error("export_amount too small");
}
CTxOut burnOut = MakeBurnOutput(burnAmount, ASSETCHAINS_CC, targetSymbol, tx.vout);
UniValue ret(UniValue::VOBJ);
ret.push_back(Pair("payouts", HexStr(E_MARSHAL(ss << tx.vout))));
tx.vout.clear();
tx.vout.push_back(burnOut);
ret.push_back(Pair("exportTx", HexStr(E_MARSHAL(ss << tx))));
return ret;
}
/*
* The process to migrate funds
*
* Create a transaction on assetchain:
*
* generaterawtransaction
* migrate_converttoexport
* fundrawtransaction
* signrawtransaction
*
* migrate_createimportransaction
* migrate_completeimporttransaction
*/
UniValue migrate_createimporttransaction(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 2)
throw runtime_error("migrate_createimporttransaction burnTx payouts\n\n"
"Create an importTx given a burnTx and the corresponding payouts, hex encoded");
if (ASSETCHAINS_CC < KOMODO_FIRSTFUNGIBLEID)
throw runtime_error("-ac_cc < KOMODO_FIRSTFUNGIBLEID");
if (ASSETCHAINS_SYMBOL[0] == 0)
throw runtime_error("Must be called on assetchain");
vector<uint8_t> txData(ParseHexV(params[0], "argument 1"));
CTransaction burnTx;
if (!E_UNMARSHAL(txData, ss >> burnTx))
throw runtime_error("Couldn't parse burnTx");
vector<CTxOut> payouts;
if (!E_UNMARSHAL(ParseHexV(params[1], "argument 2"), ss >> payouts))
throw runtime_error("Couldn't parse payouts");
uint256 txid = burnTx.GetHash();
TxProof proof = GetAssetchainProof(burnTx.GetHash());
CTransaction importTx = MakeImportCoinTransaction(proof, burnTx, payouts);
return HexStr(E_MARSHAL(ss << importTx));
}
UniValue migrate_completeimporttransaction(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error("migrate_completeimporttransaction importTx\n\n"
"Takes a cross chain import tx with proof generated on assetchain "
"and extends proof to target chain proof root");
if (ASSETCHAINS_SYMBOL[0] != 0)
throw runtime_error("Must be called on KMD");
CTransaction importTx;
if (!E_UNMARSHAL(ParseHexV(params[0], "argument 1"), ss >> importTx))
throw runtime_error("Couldn't parse importTx");
CompleteImportTransaction(importTx);
return HexStr(E_MARSHAL(ss << importTx));
}

53
src/rpcmining.cpp

@ -33,6 +33,8 @@
using namespace std;
extern int32_t ASSETCHAINS_ALGO, ASSETCHAINS_EQUIHASH, ASSETCHAINS_LWMAPOS;
extern uint64_t ASSETCHAINS_STAKED;
arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t height,int32_t goalperc);
/**
* Return average network hashes per second based on the last 'lookup' blocks,
@ -40,7 +42,7 @@ extern int32_t ASSETCHAINS_ALGO, ASSETCHAINS_EQUIHASH, ASSETCHAINS_LWMAPOS;
* If 'height' is nonnegative, compute the estimate at the time when a given block was found.
*/
int64_t GetNetworkHashPS(int lookup, int height) {
CBlockIndex *pb = chainActive.Tip();
CBlockIndex *pb = chainActive.LastTip();
if (height >= 0 && height < chainActive.Height())
pb = chainActive[height];
@ -184,7 +186,7 @@ UniValue generate(const UniValue& params, bool fHelp)
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Wallet disabled and -mineraddress not set");
}
#else
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "zcashd compiled without wallet and -mineraddress not set");
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "komodod compiled without wallet and -mineraddress not set");
#endif
}
if (!Params().MineBlocksOnDemand())
@ -216,7 +218,7 @@ UniValue generate(const UniValue& params, bool fHelp)
lastTime = GetTime();
#ifdef ENABLE_WALLET
std::unique_ptr<CBlockTemplate> pblocktemplate(CreateNewBlockWithKey(reservekey));
std::unique_ptr<CBlockTemplate> pblocktemplate(CreateNewBlockWithKey(reservekey,nHeight,KOMODO_MAXGPUCOUNT));
#else
std::unique_ptr<CBlockTemplate> pblocktemplate(CreateNewBlockWithKey());
#endif
@ -225,7 +227,7 @@ UniValue generate(const UniValue& params, bool fHelp)
CBlock *pblock = &pblocktemplate->block;
{
LOCK(cs_main);
IncrementExtraNonce(pblock, chainActive.Tip(), nExtraNonce);
IncrementExtraNonce(pblock, chainActive.LastTip(), nExtraNonce);
}
// Hash state
@ -269,7 +271,7 @@ UniValue generate(const UniValue& params, bool fHelp)
}
endloop:
CValidationState state;
if (!ProcessNewBlock(1,chainActive.Tip()->nHeight+1,state, NULL, pblock, true, NULL))
if (!ProcessNewBlock(1,chainActive.LastTip()->nHeight+1,state, NULL, pblock, true, NULL))
throw JSONRPCError(RPC_INTERNAL_ERROR, "ProcessNewBlock, block not accepted");
++nHeight;
blockHashes.push_back(pblock->GetHash().GetHex());
@ -306,7 +308,7 @@ UniValue setgenerate(const UniValue& params, bool fHelp)
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Wallet disabled and -mineraddress not set");
}
#else
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "zcashd compiled without wallet and -mineraddress not set");
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "komodod compiled without wallet and -mineraddress not set");
#endif
}
if (Params().MineBlocksOnDemand())
@ -320,8 +322,8 @@ UniValue setgenerate(const UniValue& params, bool fHelp)
if (params.size() > 1)
{
nGenProcLimit = params[1].get_int();
if (ASSETCHAINS_LWMAPOS == 0 && nGenProcLimit == 0)
fGenerate = false;
//if (nGenProcLimit == 0)
// fGenerate = false;
}
mapArgs["-gen"] = (fGenerate ? "1" : "0");
@ -515,7 +517,7 @@ UniValue getblocktemplate(const UniValue& params, bool fHelp)
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Wallet disabled and -mineraddress not set");
}
#else
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "zcashd compiled without wallet and -mineraddress not set");
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "komodod compiled without wallet and -mineraddress not set");
#endif
}
@ -558,7 +560,7 @@ UniValue getblocktemplate(const UniValue& params, bool fHelp)
return "duplicate-inconclusive";
}
CBlockIndex* const pindexPrev = chainActive.Tip();
CBlockIndex* const pindexPrev = chainActive.LastTip();
// TestBlockValidity only supports blocks built on the current Tip
if (block.hashPrevBlock != pindexPrev->GetBlockHash())
return "inconclusive-not-best-prevblk";
@ -571,8 +573,8 @@ UniValue getblocktemplate(const UniValue& params, bool fHelp)
if (strMode != "template")
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
if (vNodes.empty())
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Zcash is not connected!");
if (Params().MiningRequiresPeers() && (!IsInSync() || vNodes.empty()))
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Cannot get a block template while no peers are connected or chain not in sync!");
//if (IsInitialBlockDownload())
// throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Zcash is downloading blocks...");
@ -597,7 +599,7 @@ UniValue getblocktemplate(const UniValue& params, bool fHelp)
else
{
// NOTE: Spec does not specify behaviour for non-string longpollid, but this makes testing easier
hashWatchedChain = chainActive.Tip()->GetBlockHash();
hashWatchedChain = chainActive.LastTip()->GetBlockHash();
nTransactionsUpdatedLastLP = nTransactionsUpdatedLast;
}
@ -607,7 +609,7 @@ UniValue getblocktemplate(const UniValue& params, bool fHelp)
checktxtime = boost::get_system_time() + boost::posix_time::minutes(1);
boost::unique_lock<boost::mutex> lock(csBestBlock);
while (chainActive.Tip()->GetBlockHash() == hashWatchedChain && IsRPCRunning())
while (chainActive.LastTip()->GetBlockHash() == hashWatchedChain && IsRPCRunning())
{
if (!cvBlockChange.timed_wait(lock, checktxtime))
{
@ -629,7 +631,7 @@ UniValue getblocktemplate(const UniValue& params, bool fHelp)
static CBlockIndex* pindexPrev;
static int64_t nStart;
static CBlockTemplate* pblocktemplate;
if (pindexPrev != chainActive.Tip() ||
if (pindexPrev != chainActive.LastTip() ||
(mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 5))
{
// Clear pindexPrev so future calls make a new block, despite any failures from here on
@ -637,7 +639,7 @@ UniValue getblocktemplate(const UniValue& params, bool fHelp)
// Store the pindexBest used before CreateNewBlockWithKey, to avoid races
nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
CBlockIndex* pindexPrevNew = chainActive.Tip();
CBlockIndex* pindexPrevNew = chainActive.LastTip();
nStart = GetTime();
// Create new block
@ -648,7 +650,7 @@ UniValue getblocktemplate(const UniValue& params, bool fHelp)
}
#ifdef ENABLE_WALLET
CReserveKey reservekey(pwalletMain);
pblocktemplate = CreateNewBlockWithKey(reservekey);
pblocktemplate = CreateNewBlockWithKey(reservekey,chainActive.LastTip()->nHeight+1,KOMODO_MAXGPUCOUNT);
#else
pblocktemplate = CreateNewBlockWithKey();
#endif
@ -701,7 +703,8 @@ UniValue getblocktemplate(const UniValue& params, bool fHelp)
// Correct this if GetBlockTemplate changes the order
// entry.push_back(Pair("foundersreward", (int64_t)tx.vout[1].nValue));
//}
entry.push_back(Pair("coinbasevalue", 3*COIN));
CAmount nReward = GetBlockSubsidy(chainActive.LastTip()->nHeight+1, Params().GetConsensus());
entry.push_back(Pair("coinbasevalue", nReward));
entry.push_back(Pair("required", true));
txCoinbase = entry;
} else
@ -733,8 +736,16 @@ UniValue getblocktemplate(const UniValue& params, bool fHelp)
result.push_back(Pair("coinbaseaux", aux));
result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
}
result.push_back(Pair("longpollid", chainActive.Tip()->GetBlockHash().GetHex() + i64tostr(nTransactionsUpdatedLast)));
result.push_back(Pair("target", hashTarget.GetHex()));
result.push_back(Pair("longpollid", chainActive.LastTip()->GetBlockHash().GetHex() + i64tostr(nTransactionsUpdatedLast)));
if ( ASSETCHAINS_STAKED != 0 )
{
arith_uint256 POWtarget; int32_t PoSperc;
POWtarget = komodo_PoWtarget(&PoSperc,hashTarget,(int32_t)(pindexPrev->nHeight+1),ASSETCHAINS_STAKED);
result.push_back(Pair("target", POWtarget.GetHex()));
result.push_back(Pair("PoSperc", (int64_t)PoSperc));
result.push_back(Pair("ac_staked", (int64_t)ASSETCHAINS_STAKED));
result.push_back(Pair("origtarget", hashTarget.GetHex()));
} else result.push_back(Pair("target", hashTarget.GetHex()));
result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
result.push_back(Pair("mutable", aMutable));
result.push_back(Pair("noncerange", "00000000ffffffff"));
@ -816,7 +827,7 @@ UniValue submitblock(const UniValue& params, bool fHelp)
CValidationState state;
submitblock_StateCatcher sc(block.GetHash());
RegisterValidationInterface(&sc);
bool fAccepted = ProcessNewBlock(1,chainActive.Tip()->nHeight+1,state, NULL, &block, true, NULL);
bool fAccepted = ProcessNewBlock(1,chainActive.LastTip()->nHeight+1,state, NULL, &block, true, NULL);
UnregisterValidationInterface(&sc);
if (fBlockPresent)
{

169
src/rpcmisc.cpp

@ -52,8 +52,11 @@ int32_t komodo_whoami(char *pubkeystr,int32_t height,uint32_t timestamp);
extern uint64_t KOMODO_INTERESTSUM,KOMODO_WALLETBALANCE;
extern int32_t KOMODO_LASTMINED,JUMBLR_PAUSE,KOMODO_LONGESTCHAIN;
extern char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN];
uint32_t komodo_segid32(char *coinaddr);
int64_t komodo_coinsupply(int64_t *zfundsp,int32_t height);
int32_t notarizedtxid_height(char *dest,char *txidstr,int32_t *kmdnotarized_heightp);
#define KOMODO_VERSION "0.1.1"
#define VERUS_VERSION "0.3.12"
extern uint16_t ASSETCHAINS_P2PPORT,ASSETCHAINS_RPCPORT;
extern uint32_t ASSETCHAINS_CC;
extern uint32_t ASSETCHAINS_MAGIC;
@ -73,7 +76,7 @@ UniValue getinfo(const UniValue& params, bool fHelp)
" \"version\": xxxxx, (numeric) the server version\n"
" \"protocolversion\": xxxxx, (numeric) the protocol version\n"
" \"walletversion\": xxxxx, (numeric) the wallet version\n"
" \"balance\": xxxxxxx, (numeric) the total Zcash balance of the wallet\n"
" \"balance\": xxxxxxx, (numeric) the total Komodo balance of the wallet\n"
" \"blocks\": xxxxxx, (numeric) the current number of blocks processed in the server\n"
" \"timeoffset\": xxxxx, (numeric) the time offset\n"
" \"connections\": xxxxx, (numeric) the number of connections\n"
@ -106,6 +109,7 @@ UniValue getinfo(const UniValue& params, bool fHelp)
obj.push_back(Pair("version", CLIENT_VERSION));
obj.push_back(Pair("protocolversion", PROTOCOL_VERSION));
obj.push_back(Pair("KMDversion", KOMODO_VERSION));
obj.push_back(Pair("VRSCversion", VERUS_VERSION));
obj.push_back(Pair("notarized", notarized_height));
obj.push_back(Pair("prevMoMheight", prevMoMheight));
obj.push_back(Pair("notarizedhash", notarized_hash.ToString()));
@ -133,8 +137,8 @@ UniValue getinfo(const UniValue& params, bool fHelp)
//fprintf(stderr,"after longestchain %u\n",(uint32_t)time(NULL));
obj.push_back(Pair("longestchain", longestchain));
obj.push_back(Pair("timeoffset", GetTimeOffset()));
if ( chainActive.Tip() != 0 )
obj.push_back(Pair("tiptime", (int)chainActive.Tip()->nTime));
if ( chainActive.LastTip() != 0 )
obj.push_back(Pair("tiptime", (int)chainActive.LastTip()->nTime));
obj.push_back(Pair("connections", (int)vNodes.size()));
obj.push_back(Pair("proxy", (proxy.IsValid() ? proxy.proxy.ToStringIPPort() : string())));
obj.push_back(Pair("difficulty", (double)GetDifficulty()));
@ -152,7 +156,7 @@ UniValue getinfo(const UniValue& params, bool fHelp)
obj.push_back(Pair("errors", GetWarnings("statusbar")));
{
char pubkeystr[65]; int32_t notaryid;
if ( (notaryid= komodo_whoami(pubkeystr,(int32_t)chainActive.Tip()->nHeight,komodo_chainactive_timestamp())) >= 0 )
if ( (notaryid= komodo_whoami(pubkeystr,(int32_t)chainActive.LastTip()->nHeight,komodo_chainactive_timestamp())) >= 0 )
{
obj.push_back(Pair("notaryid", notaryid));
obj.push_back(Pair("pubkey", pubkeystr));
@ -249,6 +253,48 @@ public:
};
#endif
UniValue coinsupply(const UniValue& params, bool fHelp)
{
int32_t height = 0; int32_t currentHeight; int64_t zfunds,supply = 0; UniValue result(UniValue::VOBJ);
if (fHelp || params.size() > 1)
throw runtime_error("coinsupply <height>\n"
"\nReturn coin supply information at a given block height. If no height is given, the current height is used.\n"
"\nArguments:\n"
"1. \"height\" (integer, optional) Block height\n"
"\nResult:\n"
"{\n"
" \"result\" : \"success\", (string) If the request was successful.\n"
" \"coin\" : \"KMD\", (string) The currency symbol of the coin for asset chains, otherwise KMD.\n"
" \"height\" : 420, (integer) The height of this coin supply data\n"
" \"supply\" : \"777.0\", (float) The transparent coin supply\n"
" \"zfunds\" : \"0.777\", (float) The shielded coin supply (in zaddrs)\n"
" \"total\" : \"777.777\", (float) The total coin supply, i.e. sum of supply + zfunds\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("coinsupply", "420")
+ HelpExampleRpc("coinsupply", "420")
);
if ( params.size() == 0 )
height = chainActive.Height();
else height = atoi(params[0].get_str());
currentHeight = chainActive.Height();
if (height >= 0 && height <= currentHeight) {
if ( (supply= komodo_coinsupply(&zfunds,height)) > 0 )
{
result.push_back(Pair("result", "success"));
result.push_back(Pair("coin", ASSETCHAINS_SYMBOL[0] == 0 ? "KMD" : ASSETCHAINS_SYMBOL));
result.push_back(Pair("height", (int)height));
result.push_back(Pair("supply", ValueFromAmount(supply)));
result.push_back(Pair("zfunds", ValueFromAmount(zfunds)));
result.push_back(Pair("total", ValueFromAmount(zfunds + supply)));
} else result.push_back(Pair("error", "couldnt calculate supply"));
} else {
result.push_back(Pair("error", "invalid height"));
}
return(result);
}
UniValue jumblr_deposit(const UniValue& params, bool fHelp)
{
int32_t retval; UniValue result(UniValue::VOBJ);
@ -311,14 +357,14 @@ UniValue validateaddress(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"validateaddress \"zcashaddress\"\n"
"\nReturn information about the given Zcash address.\n"
"validateaddress \"komodoaddress\"\n"
"\nReturn information about the given Komodo address.\n"
"\nArguments:\n"
"1. \"zcashaddress\" (string, required) The Zcash address to validate\n"
"1. \"komodoaddress\" (string, required) The Komodo address to validate\n"
"\nResult:\n"
"{\n"
" \"isvalid\" : true|false, (boolean) If the address is valid or not. If not, this is the only property returned.\n"
" \"address\" : \"zcashaddress\", (string) The Zcash address validated\n"
" \"address\" : \"komodoaddress\", (string) The Komodo address validated\n"
" \"scriptPubKey\" : \"hex\", (string) The hex encoded scriptPubKey generated by the address\n"
" \"ismine\" : true|false, (boolean) If the address is yours or not\n"
" \"isscript\" : true|false, (boolean) If the key is a script\n"
@ -327,8 +373,8 @@ UniValue validateaddress(const UniValue& params, bool fHelp)
" \"account\" : \"account\" (string) DEPRECATED. The account associated with the address, \"\" is the default account\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("validateaddress", "\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\"")
+ HelpExampleRpc("validateaddress", "\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\"")
+ HelpExampleCli("validateaddress", "\"RTZMZHDFSTFQst8XmX2dR4DaH87cEUs3gC\"")
+ HelpExampleRpc("validateaddress", "\"RTZMZHDFSTFQst8XmX2dR4DaH87cEUs3gC\"")
);
#ifdef ENABLE_WALLET
@ -350,7 +396,7 @@ UniValue validateaddress(const UniValue& params, bool fHelp)
CScript scriptPubKey = GetScriptForDestination(dest);
ret.push_back(Pair("scriptPubKey", HexStr(scriptPubKey.begin(), scriptPubKey.end())));
ret.push_back(Pair("segid", (int32_t)komodo_segid32((char *)params[0].get_str().c_str()) & 0x3f));
#ifdef ENABLE_WALLET
isminetype mine = pwalletMain ? IsMine(*pwalletMain, dest) : ISMINE_NO;
ret.push_back(Pair("ismine", (mine & ISMINE_SPENDABLE) ? true : false));
@ -502,9 +548,9 @@ UniValue createmultisig(const UniValue& params, bool fHelp)
"\nArguments:\n"
"1. nrequired (numeric, required) The number of required signatures out of the n keys or addresses.\n"
"2. \"keys\" (string, required) A json array of keys which are Zcash addresses or hex-encoded public keys\n"
"2. \"keys\" (string, required) A json array of keys which are Komodo addresses or hex-encoded public keys\n"
" [\n"
" \"key\" (string) Zcash address or hex-encoded public key\n"
" \"key\" (string) Komodo address or hex-encoded public key\n"
" ,...\n"
" ]\n"
@ -516,9 +562,9 @@ UniValue createmultisig(const UniValue& params, bool fHelp)
"\nExamples:\n"
"\nCreate a multisig address from 2 addresses\n"
+ HelpExampleCli("createmultisig", "2 \"[\\\"t16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\",\\\"t171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\"") +
+ HelpExampleCli("createmultisig", "2 \"[\\\"RTZMZHDFSTFQst8XmX2dR4DaH87cEUs3gC\\\",\\\"RNKiEBduBru6Siv1cZRVhp4fkZNyPska6z\\\"]\"") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("createmultisig", "2, \"[\\\"t16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\",\\\"t171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\"")
+ HelpExampleRpc("createmultisig", "2, \"[\\\"RTZMZHDFSTFQst8XmX2dR4DaH87cEUs3gC\\\",\\\"RNKiEBduBru6Siv1cZRVhp4fkZNyPska6z\\\"]\"")
;
throw runtime_error(msg);
}
@ -539,10 +585,10 @@ UniValue verifymessage(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 3)
throw runtime_error(
"verifymessage \"zcashaddress\" \"signature\" \"message\"\n"
"verifymessage \"komodoaddress\" \"signature\" \"message\"\n"
"\nVerify a signed message\n"
"\nArguments:\n"
"1. \"zcashaddress\" (string, required) The Zcash address to use for the signature.\n"
"1. \"komodoaddress\" (string, required) The Komodo address to use for the signature.\n"
"2. \"signature\" (string, required) The signature provided by the signer in base 64 encoding (see signmessage).\n"
"3. \"message\" (string, required) The message that was signed.\n"
"\nResult:\n"
@ -551,11 +597,11 @@ UniValue verifymessage(const UniValue& params, bool fHelp)
"\nUnlock the wallet for 30 seconds\n"
+ HelpExampleCli("walletpassphrase", "\"mypassphrase\" 30") +
"\nCreate the signature\n"
+ HelpExampleCli("signmessage", "\"t14oHp2v54vfmdgQ3v3SNuQga8JKHTNi2a1\" \"my message\"") +
+ HelpExampleCli("signmessage", "\"RNKiEBduBru6Siv1cZRVhp4fkZNyPska6z\" \"my message\"") +
"\nVerify the signature\n"
+ HelpExampleCli("verifymessage", "\"t14oHp2v54vfmdgQ3v3SNuQga8JKHTNi2a1\" \"signature\" \"my message\"") +
+ HelpExampleCli("verifymessage", "\"RNKiEBduBru6Siv1cZRVhp4fkZNyPska6z\" \"signature\" \"my message\"") +
"\nAs json rpc\n"
+ HelpExampleRpc("verifymessage", "\"t14oHp2v54vfmdgQ3v3SNuQga8JKHTNi2a1\", \"signature\", \"my message\"")
+ HelpExampleRpc("verifymessage", "\"RNKiEBduBru6Siv1cZRVhp4fkZNyPska6z\", \"signature\", \"my message\"")
);
LOCK(cs_main);
@ -626,7 +672,8 @@ bool getAddressFromIndex(const int &type, const uint160 &hash, std::string &addr
address = CBitcoinAddress(CScriptID(hash)).ToString();
} else if (type == 1) {
address = CBitcoinAddress(CKeyID(hash)).ToString();
} else {
}
else {
return false;
}
return true;
@ -657,12 +704,12 @@ bool getAddressesFromParams(const UniValue& params, std::vector<std::pair<uint16
uint160 hashBytes;
int type = 0;
if (!address.GetIndexKey(hashBytes, type)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address");
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid addresses");
}
addresses.push_back(std::make_pair(hashBytes, type));
}
} else {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address");
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid addresse");
}
return true;
@ -705,8 +752,8 @@ UniValue getaddressmempool(const UniValue& params, bool fHelp)
" }\n"
"]\n"
"\nExamples:\n"
+ HelpExampleCli("getaddressmempool", "'{\"addresses\": [\"12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX\"]}'")
+ HelpExampleRpc("getaddressmempool", "{\"addresses\": [\"12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX\"]}")
+ HelpExampleCli("getaddressmempool", "'{\"addresses\": [\"RY5LccmGiX9bUHYGtSWQouNy1yFhc5rM87\"]}'")
+ HelpExampleRpc("getaddressmempool", "{\"addresses\": [\"RY5LccmGiX9bUHYGtSWQouNy1yFhc5rM87\"]}")
);
std::vector<std::pair<uint160, int> > addresses;
@ -776,8 +823,8 @@ UniValue getaddressutxos(const UniValue& params, bool fHelp)
" }\n"
"]\n"
"\nExamples:\n"
+ HelpExampleCli("getaddressutxos", "'{\"addresses\": [\"12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX\"]}'")
+ HelpExampleRpc("getaddressutxos", "{\"addresses\": [\"12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX\"]}")
+ HelpExampleCli("getaddressutxos", "'{\"addresses\": [\"RY5LccmGiX9bUHYGtSWQouNy1yFhc5rM87\"]}'")
+ HelpExampleRpc("getaddressutxos", "{\"addresses\": [\"RY5LccmGiX9bUHYGtSWQouNy1yFhc5rM87\"]}")
);
bool includeChainInfo = false;
@ -827,7 +874,7 @@ UniValue getaddressutxos(const UniValue& params, bool fHelp)
result.push_back(Pair("utxos", utxos));
LOCK(cs_main);
result.push_back(Pair("hash", chainActive.Tip()->GetBlockHash().GetHex()));
result.push_back(Pair("hash", chainActive.LastTip()->GetBlockHash().GetHex()));
result.push_back(Pair("height", (int)chainActive.Height()));
return result;
} else {
@ -863,8 +910,8 @@ UniValue getaddressdeltas(const UniValue& params, bool fHelp)
" }\n"
"]\n"
"\nExamples:\n"
+ HelpExampleCli("getaddressdeltas", "'{\"addresses\": [\"12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX\"]}'")
+ HelpExampleRpc("getaddressdeltas", "{\"addresses\": [\"12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX\"]}")
+ HelpExampleCli("getaddressdeltas", "'{\"addresses\": [\"RY5LccmGiX9bUHYGtSWQouNy1yFhc5rM87\"]}'")
+ HelpExampleRpc("getaddressdeltas", "{\"addresses\": [\"RY5LccmGiX9bUHYGtSWQouNy1yFhc5rM87\"]}")
);
@ -980,8 +1027,8 @@ UniValue getaddressbalance(const UniValue& params, bool fHelp)
" \"received\" (string) The total number of satoshis received (including change)\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getaddressbalance", "'{\"addresses\": [\"12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX\"]}'")
+ HelpExampleRpc("getaddressbalance", "{\"addresses\": [\"12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX\"]}")
+ HelpExampleCli("getaddressbalance", "'{\"addresses\": [\"RY5LccmGiX9bUHYGtSWQouNy1yFhc5rM87\"]}'")
+ HelpExampleRpc("getaddressbalance", "{\"addresses\": [\"RY5LccmGiX9bUHYGtSWQouNy1yFhc5rM87\"]}")
);
std::vector<std::pair<uint160, int> > addresses;
@ -1016,6 +1063,60 @@ UniValue getaddressbalance(const UniValue& params, bool fHelp)
}
UniValue komodo_snapshot(int top);
UniValue getsnapshot(const UniValue& params, bool fHelp)
{
UniValue result(UniValue::VOBJ); int64_t total; int32_t top = 0;
if (params.size() > 0 && !params[0].isNull()) {
top = atoi(params[0].get_str().c_str());
if (top <= 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, top must be a positive integer");
}
if ( fHelp || params.size() > 1)
{
throw runtime_error(
"getsnapshot\n"
"\nReturns a snapshot of (address,amount) pairs at current height (requires addressindex to be enabled).\n"
"\nArguments:\n"
" \"top\" (number, optional) Only return this many addresses, i.e. top N richlist\n"
"\nResult:\n"
"{\n"
" \"addresses\": [\n"
" {\n"
" \"addr\": \"RMEBhzvATA8mrfVK82E5TgPzzjtaggRGN3\",\n"
" \"amount\": \"100.0\"\n"
" },\n"
" {\n"
" \"addr\": \"RqEBhzvATAJmrfVL82E57gPzzjtaggR777\",\n"
" \"amount\": \"23.45\"\n"
" }\n"
" ],\n"
" \"total\": 123.45 (numeric) Total amount in snapshot\n"
" \"average\": 61.7, (numeric) Average amount in each address \n"
" \"utxos\": 14, (number) Total number of UTXOs in snapshot\n"
" \"total_addresses\": 2, (number) Total number of addresses in snapshot,\n"
" \"start_height\": 91, (number) Block height snapshot began\n"
" \"ending_height\": 91 (number) Block height snapsho finished,\n"
" \"start_time\": 1531982752, (number) Unix epoch time snapshot started\n"
" \"end_time\": 1531982752 (number) Unix epoch time snapshot finished\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getsnapshot","")
+ HelpExampleRpc("getsnapshot", "1000")
);
}
result = komodo_snapshot(top);
if ( result.size() > 0 ) {
result.push_back(Pair("end_time", (int) time(NULL)));
} else {
result.push_back(Pair("error", "no addressindex"));
}
return(result);
}
UniValue getaddresstxids(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
@ -1038,8 +1139,8 @@ UniValue getaddresstxids(const UniValue& params, bool fHelp)
" ,...\n"
"]\n"
"\nExamples:\n"
+ HelpExampleCli("getaddresstxids", "'{\"addresses\": [\"12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX\"]}'")
+ HelpExampleRpc("getaddresstxids", "{\"addresses\": [\"12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX\"]}")
+ HelpExampleCli("getaddresstxids", "'{\"addresses\": [\"RY5LccmGiX9bUHYGtSWQouNy1yFhc5rM87\"]}'")
+ HelpExampleRpc("getaddresstxids", "{\"addresses\": [\"RY5LccmGiX9bUHYGtSWQouNy1yFhc5rM87\"]}")
);
std::vector<std::pair<uint160, int> > addresses;

5
src/rpcnet.cpp

@ -196,6 +196,9 @@ int32_t komodo_longestchain()
}
if ( num > (n >> 1) )
{
extern char ASSETCHAINS_SYMBOL[];
if ( 0 && height != KOMODO_LONGESTCHAIN )
fprintf(stderr,"set %s KOMODO_LONGESTCHAIN <- %d\n",ASSETCHAINS_SYMBOL,height);
KOMODO_LONGESTCHAIN = height;
return(height);
}
@ -294,7 +297,7 @@ UniValue getaddednodeinfo(const UniValue& params, bool fHelp)
" \"connected\" : true|false, (boolean) If connected\n"
" \"addresses\" : [\n"
" {\n"
" \"address\" : \"192.168.0.201:8233\", (string) The Zcash server host and port\n"
" \"address\" : \"192.168.0.201:8233\", (string) The Komodo server host and port\n"
" \"connected\" : \"outbound\" (string) connection, inbound or outbound\n"
" }\n"
" ,...\n"

36
src/rpcrawtransaction.cpp

@ -33,6 +33,8 @@
using namespace std;
extern char ASSETCHAINS_SYMBOL[];
void ScriptPubKeyToJSON(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex)
{
txnouttype type;
@ -43,7 +45,8 @@ void ScriptPubKeyToJSON(const CScript& scriptPubKey, UniValue& out, bool fInclud
if (fIncludeHex)
out.push_back(Pair("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end())));
if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired)) {
if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired))
{
out.push_back(Pair("type", GetTxnOutputType(type)));
return;
}
@ -57,7 +60,6 @@ void ScriptPubKeyToJSON(const CScript& scriptPubKey, UniValue& out, bool fInclud
out.push_back(Pair("addresses", a));
}
UniValue TxJoinSplitToJSON(const CTransaction& tx) {
UniValue vjoinsplit(UniValue::VARR);
for (unsigned int i = 0; i < tx.vjoinsplit.size(); i++) {
@ -115,7 +117,7 @@ UniValue TxJoinSplitToJSON(const CTransaction& tx) {
return vjoinsplit;
}
uint64_t komodo_interest(int32_t txheight,uint64_t nValue,uint32_t nLockTime,uint32_t tiptime);
uint64_t komodo_accrued_interest(int32_t *txheightp,uint32_t *locktimep,uint256 hash,int32_t n,int32_t checkheight,uint64_t checkvalue,int32_t tipheight);
void TxToJSONExpanded(const CTransaction& tx, const uint256 hashBlock, UniValue& entry, int nHeight = 0, int nConfirmations = 0, int nBlockTime = 0)
{
@ -135,6 +137,9 @@ void TxToJSONExpanded(const CTransaction& tx, const uint256 hashBlock, UniValue&
UniValue in(UniValue::VOBJ);
if (tx.IsCoinBase())
in.push_back(Pair("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
else if (tx.IsCoinImport()) {
in.push_back(Pair("is_import", "1"));
}
else {
in.push_back(Pair("txid", txin.prevout.hash.GetHex()));
in.push_back(Pair("vout", (int64_t)txin.prevout.n));
@ -159,7 +164,8 @@ void TxToJSONExpanded(const CTransaction& tx, const uint256 hashBlock, UniValue&
in.push_back(Pair("valueSat", spentInfo.satoshis));
if (spentInfo.addressType == 1) {
in.push_back(Pair("address", CBitcoinAddress(CKeyID(spentInfo.addressHash)).ToString()));
} else if (spentInfo.addressType == 2) {
}
else if (spentInfo.addressType == 2) {
in.push_back(Pair("address", CBitcoinAddress(CScriptID(spentInfo.addressHash)).ToString()));
}
}
@ -172,13 +178,15 @@ void TxToJSONExpanded(const CTransaction& tx, const uint256 hashBlock, UniValue&
CBlockIndex *tipindex,*pindex = it->second;
uint64_t interest;
UniValue vout(UniValue::VARR);
for (unsigned int i = 0; i < tx.vout.size(); i++) {
for (unsigned int i = 0; i < tx.vout.size(); i++)
{
const CTxOut& txout = tx.vout[i];
UniValue out(UniValue::VOBJ);
out.push_back(Pair("value", ValueFromAmount(txout.nValue)));
if ( pindex != 0 && tx.nLockTime > 500000000 && (tipindex= chainActive.Tip()) != 0 )
if ( ASSETCHAINS_SYMBOL[0] == 0 && pindex != 0 && tx.nLockTime >= 500000000 && (tipindex= chainActive.LastTip()) != 0 )
{
interest = komodo_interest(pindex->nHeight,txout.nValue,tx.nLockTime,tipindex->nTime);
int64_t interest; int32_t txheight; uint32_t locktime;
interest = komodo_accrued_interest(&txheight,&locktime,tx.GetHash(),i,0,txout.nValue,(int32_t)tipindex->nHeight);
out.push_back(Pair("interest", ValueFromAmount(interest)));
}
out.push_back(Pair("valueZat", txout.nValue));
@ -326,7 +334,7 @@ UniValue getrawtransaction(const UniValue& params, bool fHelp)
" \"reqSigs\" : n, (numeric) The required sigs\n"
" \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
" \"addresses\" : [ (json array of string)\n"
" \"zcashaddress\" (string) Zcash address\n"
" \"komodoaddress\" (string) Komodo address\n"
" ,...\n"
" ]\n"
" }\n"
@ -452,7 +460,7 @@ int32_t gettxout_scriptPubKey(uint8_t *scriptPubKey,int32_t maxsize,uint256 txid
}*/
CTransaction tx;
uint256 hashBlock;
if ( GetTransaction(txid,tx,hashBlock,true) == 0 )
if ( GetTransaction(txid,tx,hashBlock,false) == 0 )
return(-1);
else if ( n <= tx.vout.size() ) // vout.size() seems off by 1
{
@ -601,7 +609,7 @@ UniValue createrawtransaction(const UniValue& params, bool fHelp)
" ]\n"
"2. \"addresses\" (string, required) a json object with addresses as keys and amounts as values\n"
" {\n"
" \"address\": x.xxx (numeric, required) The key is the Zcash address, the value is the " + CURRENCY_UNIT + " amount\n"
" \"address\": x.xxx (numeric, required) The key is the Komodo address, the value is the " + CURRENCY_UNIT + " amount\n"
" ,...\n"
" }\n"
@ -622,7 +630,7 @@ UniValue createrawtransaction(const UniValue& params, bool fHelp)
int nextBlockHeight = chainActive.Height() + 1;
CMutableTransaction rawTx = CreateNewContextualCMutableTransaction(
Params().GetConsensus(), nextBlockHeight);
if (NetworkUpgradeActive(nextBlockHeight, Params().GetConsensus(), Consensus::UPGRADE_OVERWINTER)) {
rawTx.nExpiryHeight = nextBlockHeight + expiryDelta;
if (rawTx.nExpiryHeight >= TX_EXPIRY_HEIGHT_THRESHOLD){
@ -652,7 +660,7 @@ UniValue createrawtransaction(const UniValue& params, bool fHelp)
BOOST_FOREACH(const string& name_, addrList) {
CBitcoinAddress address(name_);
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Zcash address: ")+name_);
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Komodo address: ")+name_);
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+name_);
@ -708,7 +716,7 @@ UniValue decoderawtransaction(const UniValue& params, bool fHelp)
" \"reqSigs\" : n, (numeric) The required sigs\n"
" \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
" \"addresses\" : [ (json array of string)\n"
" \"t12tvKAXCxZjSmdNbao16dKXC8tRWfcF5oc\" (string) zcash address\n"
" \"RTZMZHDFSTFQst8XmX2dR4DaH87cEUs3gC\" (string) komodo address\n"
" ,...\n"
" ]\n"
" }\n"
@ -778,7 +786,7 @@ UniValue decodescript(const UniValue& params, bool fHelp)
" \"type\":\"type\", (string) The output type\n"
" \"reqSigs\": n, (numeric) The required signatures\n"
" \"addresses\": [ (json array of string)\n"
" \"address\" (string) Zcash address\n"
" \"address\" (string) Komodo address\n"
" ,...\n"
" ],\n"
" \"p2sh\",\"address\" (string) script address\n"

72
src/rpcserver.cpp

@ -280,6 +280,7 @@ static const CRPCCommand vRPCCommands[] =
{ "network", "clearbanned", &clearbanned, true },
/* Block chain and UTXO */
{ "blockchain", "coinsupply", &coinsupply, true },
{ "blockchain", "getblockchaininfo", &getblockchaininfo, true },
{ "blockchain", "getbestblockhash", &getbestblockhash, true },
{ "blockchain", "getblockcount", &getblockcount, true },
@ -302,15 +303,20 @@ static const CRPCCommand vRPCCommands[] =
{ "blockchain", "paxpending", &paxpending, true },
{ "blockchain", "paxprices", &paxprices, true },
{ "blockchain", "notaries", &notaries, true },
{ "blockchain", "allMoMs", &allMoMs, true },
{ "blockchain", "MoMoMdata", &MoMoMdata, true },
{ "blockchain", "calc_MoM", &calc_MoM, true },
{ "blockchain", "height_MoM", &height_MoM, true },
{ "blockchain", "txMoMproof", &txMoMproof, true },
{ "blockchain", "minerids", &minerids, true },
{ "blockchain", "kvsearch", &kvsearch, true },
{ "blockchain", "kvupdate", &kvupdate, true },
/* Cross chain utilities */
{ "crosschain", "MoMoMdata", &MoMoMdata, true },
{ "crosschain", "calc_MoM", &calc_MoM, true },
{ "crosschain", "height_MoM", &height_MoM, true },
{ "crosschain", "assetchainproof", &assetchainproof, true },
{ "crosschain", "crosschainproof", &crosschainproof, true },
{ "crosschain", "migrate_converttoexport", &migrate_converttoexport, true },
{ "crosschain", "migrate_createimporttransaction", &migrate_createimporttransaction, true },
{ "crosschain", "migrate_completeimporttransaction", &migrate_completeimporttransaction, true },
/* Mining */
{ "mining", "getblocktemplate", &getblocktemplate, true },
{ "mining", "getmininginfo", &getmininginfo, true },
@ -338,6 +344,53 @@ static const CRPCCommand vRPCCommands[] =
#ifdef ENABLE_WALLET
{ "rawtransactions", "fundrawtransaction", &fundrawtransaction, false },
#endif
/* auction */
{ "auction", "auctionaddress", &auctionaddress, true },
/* lotto */
{ "lotto", "lottoaddress", &lottoaddress, true },
/* ponzi */
{ "ponzi", "ponziaddress", &ponziaddress, true },
/* rewards */
{ "rewards", "rewardslist", &rewardslist, true },
{ "rewards", "rewardsinfo", &rewardsinfo, true },
{ "rewards", "rewardscreatefunding", &rewardscreatefunding, true },
{ "rewards", "rewardsaddfunding", &rewardsaddfunding, true },
{ "rewards", "rewardslock", &rewardslock, true },
{ "rewards", "rewardsunlock", &rewardsunlock, true },
{ "rewards", "rewardsaddress", &rewardsaddress, true },
/* faucet */
{ "faucet", "faucetfund", &faucetfund, true },
{ "faucet", "faucetget", &faucetget, true },
{ "faucet", "faucetaddress", &faucetaddress, true },
/* dice */
{ "dice", "dicelist", &dicelist, true },
{ "dice", "diceinfo", &diceinfo, true },
{ "dice", "dicefund", &dicefund, true },
{ "dice", "diceaddfunds", &diceaddfunds, true },
{ "dice", "dicebet", &dicebet, true },
{ "dice", "diceaddress", &diceaddress, true },
/* tokens */
{ "tokens", "tokeninfo", &tokeninfo, true },
{ "tokens", "tokenlist", &tokenlist, true },
{ "tokens", "tokenorders", &tokenorders, true },
{ "tokens", "tokenaddress", &tokenaddress, true },
{ "tokens", "tokenbalance", &tokenbalance, true },
{ "tokens", "tokencreate", &tokencreate, true },
{ "tokens", "tokentransfer", &tokentransfer, true },
{ "tokens", "tokenbid", &tokenbid, true },
{ "tokens", "tokencancelbid", &tokencancelbid, true },
{ "tokens", "tokenfillbid", &tokenfillbid, true },
{ "tokens", "tokenask", &tokenask, true },
{ "tokens", "tokenswapask", &tokenswapask, true },
{ "tokens", "tokencancelask", &tokencancelask, true },
{ "tokens", "tokenfillask", &tokenfillask, true },
{ "tokens", "tokenfillswap", &tokenfillswap, true },
/* Address index */
{ "addressindex", "getaddressmempool", &getaddressmempool, true },
@ -345,6 +398,7 @@ static const CRPCCommand vRPCCommands[] =
{ "addressindex", "getaddressdeltas", &getaddressdeltas, false },
{ "addressindex", "getaddresstxids", &getaddresstxids, false },
{ "addressindex", "getaddressbalance", &getaddressbalance, false },
{ "addressindex", "getsnapshot", &getsnapshot, false },
/* Utility functions */
{ "util", "createmultisig", &createmultisig, true },
@ -358,12 +412,12 @@ static const CRPCCommand vRPCCommands[] =
{ "util", "jumblr_pause", &jumblr_pause, true },
{ "util", "jumblr_resume", &jumblr_resume, true },
{ "util", "invalidateblock", &invalidateblock, true },
{ "util", "reconsiderblock", &reconsiderblock, true },
/* Not shown in help */
{ "hidden", "invalidateblock", &invalidateblock, true },
{ "hidden", "reconsiderblock", &reconsiderblock, true },
{ "hidden", "setmocktime", &setmocktime, true },
#ifdef ENABLE_WALLET
{ "hidden", "resendwallettransactions", &resendwallettransactions, true},
{ "wallet", "resendwallettransactions", &resendwallettransactions, true},
#endif
#ifdef ENABLE_WALLET
@ -377,7 +431,9 @@ static const CRPCCommand vRPCCommands[] =
{ "wallet", "getaccount", &getaccount, true },
{ "wallet", "getaddressesbyaccount", &getaddressesbyaccount, true },
{ "wallet", "getbalance", &getbalance, false },
{ "wallet", "getbalance64", &getbalance64, false },
{ "wallet", "getnewaddress", &getnewaddress, true },
// { "wallet", "getnewaddress64", &getnewaddress64, true },
{ "wallet", "getrawchangeaddress", &getrawchangeaddress, true },
{ "wallet", "getreceivedbyaccount", &getreceivedbyaccount, false },
{ "wallet", "getreceivedbyaddress", &getreceivedbyaddress, false },

46
src/rpcserver.h

@ -177,6 +177,7 @@ extern UniValue getaddressmempool(const UniValue& params, bool fHelp);
extern UniValue getaddressutxos(const UniValue& params, bool fHelp);
extern UniValue getaddressdeltas(const UniValue& params, bool fHelp);
extern UniValue getaddresstxids(const UniValue& params, bool fHelp);
extern UniValue getsnapshot(const UniValue& params, bool fHelp);
extern UniValue getaddressbalance(const UniValue& params, bool fHelp);
extern UniValue getpeerinfo(const UniValue& params, bool fHelp);
extern UniValue ping(const UniValue& params, bool fHelp);
@ -206,8 +207,44 @@ extern UniValue getblocktemplate(const UniValue& params, bool fHelp);
extern UniValue submitblock(const UniValue& params, bool fHelp);
extern UniValue estimatefee(const UniValue& params, bool fHelp);
extern UniValue estimatepriority(const UniValue& params, bool fHelp);
extern UniValue coinsupply(const UniValue& params, bool fHelp);
extern UniValue tokeninfo(const UniValue& params, bool fHelp);
extern UniValue tokenlist(const UniValue& params, bool fHelp);
extern UniValue tokenorders(const UniValue& params, bool fHelp);
extern UniValue tokenbalance(const UniValue& params, bool fHelp);
extern UniValue tokenaddress(const UniValue& params, bool fHelp);
extern UniValue tokencreate(const UniValue& params, bool fHelp);
extern UniValue tokentransfer(const UniValue& params, bool fHelp);
extern UniValue tokenbid(const UniValue& params, bool fHelp);
extern UniValue tokencancelbid(const UniValue& params, bool fHelp);
extern UniValue tokenfillbid(const UniValue& params, bool fHelp);
extern UniValue tokenask(const UniValue& params, bool fHelp);
extern UniValue tokencancelask(const UniValue& params, bool fHelp);
extern UniValue tokenfillask(const UniValue& params, bool fHelp);
extern UniValue tokenswapask(const UniValue& params, bool fHelp);
extern UniValue tokenfillswap(const UniValue& params, bool fHelp);
extern UniValue faucetfund(const UniValue& params, bool fHelp);
extern UniValue faucetget(const UniValue& params, bool fHelp);
extern UniValue faucetaddress(const UniValue& params, bool fHelp);
extern UniValue rewardsinfo(const UniValue& params, bool fHelp);
extern UniValue rewardslist(const UniValue& params, bool fHelp);
extern UniValue rewardsaddress(const UniValue& params, bool fHelp);
extern UniValue rewardscreatefunding(const UniValue& params, bool fHelp);
extern UniValue rewardsaddfunding(const UniValue& params, bool fHelp);
extern UniValue rewardslock(const UniValue& params, bool fHelp);
extern UniValue rewardsunlock(const UniValue& params, bool fHelp);
extern UniValue diceaddress(const UniValue& params, bool fHelp);
extern UniValue dicefund(const UniValue& params, bool fHelp);
extern UniValue dicelist(const UniValue& params, bool fHelp);
extern UniValue diceinfo(const UniValue& params, bool fHelp);
extern UniValue diceaddfunds(const UniValue& params, bool fHelp);
extern UniValue dicebet(const UniValue& params, bool fHelp);
extern UniValue lottoaddress(const UniValue& params, bool fHelp);
extern UniValue ponziaddress(const UniValue& params, bool fHelp);
extern UniValue auctionaddress(const UniValue& params, bool fHelp);
extern UniValue getnewaddress(const UniValue& params, bool fHelp); // in rpcwallet.cpp
//extern UniValue getnewaddress64(const UniValue& params, bool fHelp); // in rpcwallet.cpp
extern UniValue getaccountaddress(const UniValue& params, bool fHelp);
extern UniValue getrawchangeaddress(const UniValue& params, bool fHelp);
extern UniValue setaccount(const UniValue& params, bool fHelp);
@ -219,6 +256,7 @@ extern UniValue verifymessage(const UniValue& params, bool fHelp);
extern UniValue getreceivedbyaddress(const UniValue& params, bool fHelp);
extern UniValue getreceivedbyaccount(const UniValue& params, bool fHelp);
extern UniValue getbalance(const UniValue& params, bool fHelp);
extern UniValue getbalance64(const UniValue& params, bool fHelp);
extern UniValue getunconfirmedbalance(const UniValue& params, bool fHelp);
extern UniValue movecmd(const UniValue& params, bool fHelp);
extern UniValue sendfrom(const UniValue& params, bool fHelp);
@ -312,11 +350,15 @@ extern UniValue z_validateaddress(const UniValue& params, bool fHelp); // in rpc
extern UniValue z_getpaymentdisclosure(const UniValue& params, bool fHelp); // in rpcdisclosure.cpp
extern UniValue z_validatepaymentdisclosure(const UniValue &params, bool fHelp); // in rpcdisclosure.cpp
extern UniValue allMoMs(const UniValue& params, bool fHelp);
extern UniValue MoMoMdata(const UniValue& params, bool fHelp);
extern UniValue calc_MoM(const UniValue& params, bool fHelp);
extern UniValue height_MoM(const UniValue& params, bool fHelp);
extern UniValue txMoMproof(const UniValue& params, bool fHelp);
extern UniValue assetchainproof(const UniValue& params, bool fHelp);
extern UniValue crosschainproof(const UniValue& params, bool fHelp);
extern UniValue migrate_converttoexport(const UniValue& params, bool fHelp);
extern UniValue migrate_createimporttransaction(const UniValue& params, bool fHelp);
extern UniValue migrate_completeimporttransaction(const UniValue& params, bool fHelp);
extern UniValue notaries(const UniValue& params, bool fHelp);
extern UniValue minerids(const UniValue& params, bool fHelp);
extern UniValue kvsearch(const UniValue& params, bool fHelp);

3
src/script/cc.h

@ -1,6 +1,8 @@
#ifndef SCRIPT_CC_H
#define SCRIPT_CC_H
#include <memory>
#include "pubkey.h"
#include "script/script.h"
#include "cryptoconditions/include/cryptoconditions.h"
@ -79,5 +81,4 @@ bool GetPushData(const CScript &sig, std::vector<unsigned char> &data);
*/
bool GetOpReturnData(const CScript &sig, std::vector<unsigned char> &data);
#endif /* SCRIPT_CC_H */

14
src/script/interpreter.cpp

@ -3,17 +3,20 @@
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <cryptoconditions.h>
#include "interpreter.h"
#include "consensus/upgrades.h"
#include "primitives/transaction.h"
#include "cc/eval.h"
#include "crypto/ripemd160.h"
#include "crypto/sha1.h"
#include "crypto/sha256.h"
#include "pubkey.h"
#include "script/script.h"
#include "uint256.h"
#include "cryptoconditions/include/cryptoconditions.h"
using namespace std;
@ -1310,6 +1313,14 @@ int TransactionSignatureChecker::CheckCryptoCondition(
} catch (logic_error ex) {
return 0;
}
//int32_t z; uint8_t *ptr;
//ptr = (uint8_t *)scriptCode.data();
//for (z=0; z<scriptCode.size(); z++)
// fprintf(stderr,"%02x",ptr[z]);
//fprintf(stderr," <- CScript\n");
//for (z=0; z<32; z++)
// fprintf(stderr,"%02x",((uint8_t *)&sighash)[z]);
//fprintf(stderr," sighash nIn.%d nHashType.%d %.8f id.%d\n",(int32_t)nIn,(int32_t)nHashType,(double)amount/COIN,(int32_t)consensusBranchId);
VerifyEval eval = [] (CC *cond, void *checker) {
return ((TransactionSignatureChecker*)checker)->CheckEvalCondition(cond);
@ -1317,6 +1328,7 @@ int TransactionSignatureChecker::CheckCryptoCondition(
int out = cc_verify(cond, (const unsigned char*)&sighash, 32, 0,
condBin.data(), condBin.size(), eval, (void*)this);
//fprintf(stderr,"out.%d from cc_verify\n",(int32_t)out);
cc_free(cond);
return out;
}

1
src/script/interpreter.h

@ -186,5 +186,4 @@ bool VerifyScript(
const BaseSignatureChecker& checker,
uint32_t consensusBranchId,
ScriptError* serror = NULL);
#endif // BITCOIN_SCRIPT_INTERPRETER_H

21
src/script/script.cpp

@ -8,8 +8,10 @@
#include "tinyformat.h"
#include "utilstrencodings.h"
#include "script/cc.h"
#include "cc/eval.h"
#include "cryptoconditions/include/cryptoconditions.h"
namespace {
inline std::string ValueString(const std::vector<unsigned char>& vch)
{
@ -227,6 +229,14 @@ bool CScript::IsPayToPublicKeyHash() const
(*this)[24] == OP_CHECKSIG);
}
bool CScript::IsPayToPublicKey() const
{
// Extra-fast test for pay-to-pubkey CScripts:
return (this->size() == 35 &&
(*this)[0] == 33 &&
(*this)[34] == OP_CHECKSIG);
}
bool CScript::IsPayToScriptHash() const
{
// Extra-fast test for pay-to-script-hash CScripts:
@ -266,6 +276,17 @@ bool CScript::MayAcceptCryptoCondition() const
return out;
}
bool CScript::IsCoinImport() const
{
const_iterator pc = this->begin();
vector<unsigned char> data;
opcodetype opcode;
if (this->GetOp(pc, opcode, data))
if (opcode > OP_0 && opcode <= OP_PUSHDATA4)
return data.begin()[0] == EVAL_IMPORTCOIN;
return false;
}
bool CScript::IsPushOnly() const
{
const_iterator pc = begin();

2
src/script/script.h

@ -569,9 +569,11 @@ public:
unsigned int GetSigOpCount(const CScript& scriptSig) const;
bool IsPayToPublicKeyHash() const;
bool IsPayToPublicKey() const;
bool IsPayToScriptHash() const;
bool IsPayToCryptoCondition() const;
bool IsCoinImport() const;
bool MayAcceptCryptoCondition() const;
/** Called by IsStandardTx and P2SH/BIP62 VerifyScript (which makes it consensus-critical). */

18
src/script/standard.cpp

@ -31,6 +31,8 @@ const char* GetTxnOutputType(txnouttype t)
case TX_SCRIPTHASH: return "scripthash";
case TX_MULTISIG: return "multisig";
case TX_NULL_DATA: return "nulldata";
case TX_CRYPTOCONDITION: return "cryptocondition";
default: return "invalid";
}
return NULL;
}
@ -74,6 +76,14 @@ bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, vector<vector<unsi
if (scriptPubKey.IsPayToCryptoCondition()) {
if (scriptPubKey.MayAcceptCryptoCondition()) {
typeRet = TX_CRYPTOCONDITION;
vector<unsigned char> hashBytes; uint160 x; int32_t i; uint8_t hash20[20],*ptr;;
x = Hash160(scriptPubKey);
memcpy(hash20,&x,20);
hashBytes.resize(20);
ptr = hashBytes.data();
for (i=0; i<20; i++)
ptr[i] = hash20[i];
vSolutionsRet.push_back(hashBytes);
return true;
}
return false;
@ -263,6 +273,12 @@ bool ExtractDestination(const CScript& _scriptPubKey, CTxDestination& addressRet
addressRet = CScriptID(uint160(vSolutions[0]));
return true;
}
else if (IsCryptoConditionsEnabled() != 0 && whichType == TX_CRYPTOCONDITION)
{
addressRet = CKeyID(uint160(vSolutions[0]));
return true;
}
// Multisig txns have more than one address...
return false;
}
@ -314,7 +330,9 @@ bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, vecto
nRequiredRet = 1;
CTxDestination address;
if (!ExtractDestination(scriptPubKey, address))
{
return false;
}
addressRet.push_back(address);
}

8
src/test-komodo/main.cpp

@ -1,14 +1,22 @@
#include "key.h"
#include "base58.h"
#include "chainparams.h"
#include "gtest/gtest.h"
#include "crypto/common.h"
#include "testutils.h"
int main(int argc, char **argv) {
assert(init_and_check_sodium() != -1);
ECC_Start();
ECCVerifyHandle handle; // Inits secp256k1 verify context
SelectParams(CBaseChainParams::REGTEST);
CBitcoinSecret vchSecret;
// this returns false due to network prefix mismatch but works anyway
vchSecret.SetString(notarySecret);
notaryKey = vchSecret.GetKey();
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

257
src/test-komodo/test_coinimport.cpp

@ -0,0 +1,257 @@
#include <cryptoconditions.h>
#include <gtest/gtest.h>
#include "cc/eval.h"
#include "importcoin.h"
#include "base58.h"
#include "core_io.h"
#include "key.h"
#include "main.h"
#include "primitives/transaction.h"
#include "script/cc.h"
#include "script/interpreter.h"
#include "script/serverchecker.h"
#include "txmempool.h"
#include "testutils.h"
extern Eval* EVAL_TEST;
namespace TestCoinImport {
static uint8_t testNum = 0;
class TestCoinImport : public ::testing::Test, public Eval {
public:
CMutableTransaction burnTx;
std::vector<CTxOut> payouts;
TxProof proof;
uint256 MoMoM;
CMutableTransaction importTx;
uint32_t testCcid = 2;
std::string testSymbol = "PIZZA";
CAmount amount = 100;
void SetImportTx() {
burnTx.vout.resize(0);
burnTx.vout.push_back(MakeBurnOutput(amount, testCcid, testSymbol, payouts));
importTx = CMutableTransaction(MakeImportCoinTransaction(proof, CTransaction(burnTx), payouts));
MoMoM = burnTx.GetHash(); // TODO: an actual branch
}
uint32_t GetAssetchainsCC() const { return testCcid; }
std::string GetAssetchainsSymbol() const { return testSymbol; }
bool GetProofRoot(uint256 hash, uint256 &momom) const
{
if (MoMoM.IsNull()) return false;
momom = MoMoM;
return true;
}
protected:
static void SetUpTestCase() { setupChain(); }
virtual void SetUp() {
ASSETCHAINS_CC = 1;
EVAL_TEST = this;
std::vector<uint8_t> fakepk;
fakepk.resize(33);
fakepk.begin()[0] = testNum++;
payouts.push_back(CTxOut(amount, CScript() << fakepk << OP_CHECKSIG));
SetImportTx();
}
void TestRunCCEval(CMutableTransaction mtx)
{
CTransaction importTx(mtx);
PrecomputedTransactionData txdata(importTx);
ServerTransactionSignatureChecker checker(&importTx, 0, 0, false, txdata);
CValidationState verifystate;
if (!VerifyCoinImport(importTx.vin[0].scriptSig, checker, verifystate))
printf("TestRunCCEval: %s\n", verifystate.GetRejectReason().data());
}
};
TEST_F(TestCoinImport, testProcessImportThroughPipeline)
{
CValidationState mainstate;
CTransaction tx(importTx);
// first should work
acceptTxFail(tx);
// should fail in mempool
ASSERT_FALSE(acceptTx(tx, mainstate));
EXPECT_EQ("already in mempool", mainstate.GetRejectReason());
// should be in persisted UTXO set
generateBlock();
ASSERT_FALSE(acceptTx(tx, mainstate));
EXPECT_EQ("already have coins", mainstate.GetRejectReason());
ASSERT_TRUE(pcoinsTip->HaveCoins(tx.GetHash()));
// Now disconnect the block
CValidationState invalstate;
if (!InvalidateBlock(invalstate, chainActive.Tip())) {
FAIL() << invalstate.GetRejectReason();
}
ASSERT_FALSE(pcoinsTip->HaveCoins(tx.GetHash()));
// should be back in mempool
ASSERT_FALSE(acceptTx(tx, mainstate));
EXPECT_EQ("already in mempool", mainstate.GetRejectReason());
}
TEST_F(TestCoinImport, testImportTombstone)
{
CValidationState mainstate;
// By setting an unspendable output, there will be no addition to UTXO
// Nonetheless, we dont want to be able to import twice
payouts[0].scriptPubKey = CScript() << OP_RETURN;
SetImportTx();
MoMoM = burnTx.GetHash(); // TODO: an actual branch
CTransaction tx(importTx);
// first should work
acceptTxFail(tx);
// should be in persisted UTXO set
generateBlock();
ASSERT_FALSE(acceptTx(tx, mainstate));
EXPECT_EQ("import tombstone exists", mainstate.GetRejectReason());
ASSERT_TRUE(pcoinsTip->HaveCoins(burnTx.GetHash()));
// Now disconnect the block
CValidationState invalstate;
if (!InvalidateBlock(invalstate, chainActive.Tip())) {
FAIL() << invalstate.GetRejectReason();
}
// Tombstone should be gone from utxo set
ASSERT_FALSE(pcoinsTip->HaveCoins(burnTx.GetHash()));
// should be back in mempool
ASSERT_FALSE(acceptTx(tx, mainstate));
EXPECT_EQ("already in mempool", mainstate.GetRejectReason());
}
TEST_F(TestCoinImport, testNoVouts)
{
importTx.vout.resize(0);
TestRunCCEval(importTx);
EXPECT_EQ("too-few-vouts", state.GetRejectReason());
}
TEST_F(TestCoinImport, testInvalidParams)
{
std::vector<uint8_t> payload = E_MARSHAL(ss << EVAL_IMPORTCOIN; ss << 'a');
importTx.vin[0].scriptSig = CScript() << payload;
TestRunCCEval(importTx);
EXPECT_EQ("invalid-params", state.GetRejectReason());
}
TEST_F(TestCoinImport, testNonCanonical)
{
importTx.nLockTime = 10;
TestRunCCEval(importTx);
EXPECT_EQ("non-canonical", state.GetRejectReason());
}
TEST_F(TestCoinImport, testInvalidBurnOutputs)
{
burnTx.vout.resize(0);
MoMoM = burnTx.GetHash(); // TODO: an actual branch
CTransaction tx = MakeImportCoinTransaction(proof, CTransaction(burnTx), payouts);
TestRunCCEval(tx);
EXPECT_EQ("invalid-burn-tx", state.GetRejectReason());
}
TEST_F(TestCoinImport, testInvalidBurnParams)
{
burnTx.vout[0].scriptPubKey = CScript() << OP_RETURN << E_MARSHAL(ss << VARINT(testCcid));
MoMoM = burnTx.GetHash(); // TODO: an actual branch
CTransaction tx = MakeImportCoinTransaction(proof, CTransaction(burnTx), payouts);
TestRunCCEval(tx);
EXPECT_EQ("invalid-burn-tx", state.GetRejectReason());
}
TEST_F(TestCoinImport, testWrongChainId)
{
testCcid = 0;
TestRunCCEval(importTx);
EXPECT_EQ("importcoin-wrong-chain", state.GetRejectReason());
}
TEST_F(TestCoinImport, testInvalidBurnAmount)
{
burnTx.vout[0].nValue = 0;
MoMoM = burnTx.GetHash(); // TODO: an actual branch
CTransaction tx = MakeImportCoinTransaction(proof, CTransaction(burnTx), payouts);
TestRunCCEval(tx);
EXPECT_EQ("invalid-burn-amount", state.GetRejectReason());
}
TEST_F(TestCoinImport, testPayoutTooHigh)
{
importTx.vout[1].nValue = 101;
TestRunCCEval(importTx);
EXPECT_EQ("payout-too-high", state.GetRejectReason());
}
TEST_F(TestCoinImport, testAmountInOpret)
{
importTx.vout[0].nValue = 1;
TestRunCCEval(importTx);
EXPECT_EQ("non-canonical", state.GetRejectReason());
}
TEST_F(TestCoinImport, testInvalidPayouts)
{
importTx.vout[1].nValue = 40;
importTx.vout.push_back(importTx.vout[0]);
TestRunCCEval(importTx);
EXPECT_EQ("wrong-payouts", state.GetRejectReason());
}
TEST_F(TestCoinImport, testCouldntLoadMomom)
{
MoMoM.SetNull();
TestRunCCEval(importTx);
EXPECT_EQ("coudnt-load-momom", state.GetRejectReason());
}
TEST_F(TestCoinImport, testMomomCheckFail)
{
MoMoM.SetNull();
MoMoM.begin()[0] = 1;
TestRunCCEval(importTx);
EXPECT_EQ("momom-check-fail", state.GetRejectReason());
}
TEST_F(TestCoinImport, testGetCoinImportValue)
{
ASSERT_EQ(100, GetCoinImportValue(importTx));
}
} /* namespace TestCoinImport */

213
src/test-komodo/test_crosschain.cpp

@ -0,0 +1,213 @@
#include <zmq.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>
#include <cryptoconditions.h>
#include <gtest/gtest.h>
#include "cc/eval.h"
#include "importcoin.h"
#include "base58.h"
#include "core_io.h"
#include "crosschain.h"
#include "key.h"
#include "komodo_structs.h"
#include "main.h"
#include "notarisationdb.h"
#include "primitives/block.h"
#include "primitives/transaction.h"
#include "script/cc.h"
#include "script/interpreter.h"
#include "script/serverchecker.h"
#include "txmempool.h"
#include "crosschain.h"
#include "testutils.h"
extern uint256 komodo_calcMoM(int32_t height,int32_t MoMdepth);
extern bool KOMODO_TEST_ASSETCHAIN_SKIP_POW;
/*
* Tests for the whole process of creating and validating notary proofs
* using proof roots (MoMoMs). This is to support coin imports.
*/
namespace TestCrossChainProof {
class TestCrossChain : public ::testing::Test, public Eval {
public:
bool CheckNotaryInputs(const CTransaction &tx, uint32_t height, uint32_t timestamp) const
{
NotarisationData data(2);
return ParseNotarisationOpReturn(tx, data); // If it parses it's valid
}
protected:
static void SetUpTestCase() { }
virtual void SetUp() {
KOMODO_TEST_ASSETCHAIN_SKIP_POW = 1;
ASSETCHAINS_CC = 1;
EVAL_TEST = this;
}
};
uint256 endianHash(uint256 h)
{
uint256 out;
for (int i=0; i<32; i++) {
out.begin()[31-i] = h.begin()[i];
}
return out;
}
TEST_F(TestCrossChain, testCreateAndValidateImportProof)
{
/*
* This tests the full process of creation of a cross chain proof.
* For the purposes of the test we will use one assetchain and a KMD chain.
*
* In order to do this test, we need 2 blockchains, so we'll fork and make a socket
* for IPC.
*/
int childPid = fork();
void *ctx = zmq_ctx_new();
void *socket = zmq_socket(ctx, ZMQ_PAIR);
if (!childPid)
strcpy(ASSETCHAINS_SYMBOL, "PIZZA");
setupChain();
std::vector<CBlock> blocks;
blocks.resize(1000);
NotarisationData a2kmd(0), kmd2a(1);
int numTestNotarisations = 10;
auto SendIPC = [&] (std::vector<uint8_t> v) {
assert(v.size() == zmq_send(socket, v.data(), v.size(), 0));
};
auto RecvIPC = [&] () {
std::vector<uint8_t> out;
out.resize(100000);
int len = zmq_recv(socket, out.data(), out.size(), 0);
assert(len != -1);
out.resize(len);
return out;
};
auto RecordNotarisation = [&] (CTransaction inputTx, NotarisationData data) {
CMutableTransaction mtx = spendTx(inputTx);
mtx.vout.resize(2);
mtx.vout[0].scriptPubKey << VCH(notaryKey.GetPubKey().begin(), 33) << OP_CHECKSIG;
mtx.vout[1].scriptPubKey << OP_RETURN << E_MARSHAL(ss << data);
mtx.vout[1].nValue = 0;
mtx.vin[0].scriptSig << getSig(mtx, inputTx.vout[0].scriptPubKey);
acceptTxFail(CTransaction(mtx));
return mtx.GetHash();
};
auto RunTestAssetchain = [&] ()
{
NotarisationData n(0), back(1);
strcpy(n.symbol, "PIZZA");
n.ccId = 2;
int height = 0;
/*
* Send notarisations and write backnotarisations
*/
for (int ni=0; ni<numTestNotarisations; ni++)
{
generateBlock(&blocks[++height]);
generateBlock(&blocks[++height]);
n.blockHash = blocks[height].GetHash();
n.MoM = endianHash(komodo_calcMoM(n.height=height, n.MoMDepth=2));
SendIPC(E_MARSHAL(ss << n));
assert(E_UNMARSHAL(RecvIPC(), ss >> back));
RecordNotarisation(blocks[height].vtx[0], back);
}
/*
* Test a proof
*/
uint256 txid = blocks[7].vtx[0].GetHash();
TxProof proof = GetAssetchainProof(txid);
SendIPC(E_MARSHAL(ss << txid; ss << proof));
E_UNMARSHAL(RecvIPC(), ss >> proof);
std::pair<uint256,NotarisationData> bn;
if (!GetNextBacknotarisation(proof.first, bn)) {
printf("GetNextBackNotarisation failed\n");
return 1;
}
if (proof.second.Exec(txid) != bn.second.MoMoM) {
printf("MoMom incorrect\n");
return 1;
}
return 0;
};
auto RunTestKmd = [&] ()
{
NotarisationData n(0);
int height = 0;
/*
* Write notarisations and send backnotarisations
*/
for (int ni=0; ni<numTestNotarisations; ni++)
{
n.IsBackNotarisation = 0;
E_UNMARSHAL(RecvIPC(), ss >> n);
// Grab a coinbase input to fund notarisation
generateBlock(&blocks[++height]);
n.txHash = RecordNotarisation(blocks[height].vtx[0], n);
{
std::vector<uint256> moms;
uint256 destNotarisationTxid;
n.MoMoM = CalculateProofRoot(n.symbol, 2, height, moms, destNotarisationTxid);
}
n.IsBackNotarisation = 1;
SendIPC(E_MARSHAL(ss << n));
}
/*
* Extend proof
*/
TxProof proof;
uint256 txid;
// Extend proof to MoMoM
assert(E_UNMARSHAL(RecvIPC(), ss >> txid; ss >> proof));
proof = GetCrossChainProof(txid, (char*)"PIZZA", 2, proof);
SendIPC(E_MARSHAL(ss << proof));
};
const char endpoint[] = "ipc://tmpKomodoTestCrossChainSock";
if (!childPid) {
assert(0 == zmq_connect(socket, endpoint));
usleep(20000);
int out = RunTestAssetchain();
if (!out) printf("Assetchain success\n");
exit(out);
}
else {
assert(0 == zmq_bind(socket, endpoint));
RunTestKmd();
int returnStatus;
waitpid(childPid, &returnStatus, 0);
unlink("tmpKomodoTestCrossChainSock");
ASSERT_EQ(0, returnStatus);
}
}
} /* namespace TestCrossChainProof */

10
src/test-komodo/test_cryptoconditions.cpp

@ -12,11 +12,6 @@
#include "testutils.h"
CKey notaryKey;
std::string pubkey = "0205a8ad0c1dbc515f149af377981aab58b836af008d4d7ab21bd76faf80550b47";
std::string secret = "UxFWWxsf1d7w7K5TvAWSkeX4H95XQKwdwGv49DXwWUTzPTTjHBbU";
class CCTest : public ::testing::Test {
public:
@ -32,11 +27,6 @@ protected:
virtual void SetUp() {
// enable CC
ASSETCHAINS_CC = 1;
// Notary key
CBitcoinSecret vchSecret;
// this returns false due to network prefix mismatch but works anyway
vchSecret.SetString(secret);
notaryKey = vchSecret.GetKey();
}
};

6
src/test-komodo/test_eval_bet.cpp

@ -208,7 +208,7 @@ public:
int nIndex = 5;
std::vector<uint256> vBranch;
vBranch.resize(3);
return MoMProof(nIndex, vBranch, EvalMock::NotarisationHash());
return {MerkleBranch(nIndex, vBranch), EvalMock::NotarisationHash()};
}
CMutableTransaction ImportPayoutTx()
@ -237,7 +237,7 @@ public:
eval.currentHeight = currentHeight;
MoMProof proof = GetMoMProof();
eval.MoM = proof.Exec(DisputeTx(Player2).GetHash());
eval.MoM = proof.branch.Exec(DisputeTx(Player2).GetHash());
EVAL_TEST = &eval;
return eval;
@ -585,7 +585,7 @@ TEST_F(TestBet, testImportPayoutMomFail)
EvalMock eval = ebet.SetEvalMock(12);
MoMProof proof = ebet.GetMoMProof();
proof.nIndex ^= 1;
proof.branch.nIndex ^= 1;
CMutableTransaction importTx = ebet.bet.MakeImportPayoutTx(
ebet.Payouts(Player2), ebet.DisputeTx(Player2), uint256(), proof);

170
src/test-komodo/test_eval_notarisation.cpp

@ -15,93 +15,90 @@
#include "testutils.h"
extern Eval* EVAL_TEST;
extern int32_t komodo_notaries(uint8_t pubkeys[64][33],int32_t height,uint32_t timestamp);
namespace TestEvalNotarisation {
class EvalMock : public Eval
{
public:
uint32_t nNotaries;
uint8_t notaries[64][33];
std::map<uint256, CTransaction> txs;
std::map<uint256, CBlockIndex> blocks;
int32_t GetNotaries(uint8_t pubkeys[64][33], int32_t height, uint32_t timestamp) const
{
memcpy(pubkeys, notaries, sizeof(notaries));
return nNotaries;
}
bool GetTxUnconfirmed(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock) const
class EvalMock : public Eval
{
auto r = txs.find(hash);
if (r != txs.end()) {
txOut = r->second;
if (blocks.count(hash) > 0)
hashBlock = hash;
return true;
public:
uint32_t nNotaries;
uint8_t notaries[64][33];
std::map<uint256, CTransaction> txs;
std::map<uint256, CBlockIndex> blocks;
int32_t GetNotaries(uint8_t pubkeys[64][33], int32_t height, uint32_t timestamp) const
{
memcpy(pubkeys, notaries, sizeof(notaries));
return nNotaries;
}
bool GetTxUnconfirmed(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock) const
{
auto r = txs.find(hash);
if (r != txs.end()) {
txOut = r->second;
if (blocks.count(hash) > 0)
hashBlock = hash;
return true;
}
return false;
}
bool GetBlock(uint256 hash, CBlockIndex& blockIdx) const
{
auto r = blocks.find(hash);
if (r == blocks.end()) return false;
blockIdx = r->second;
return true;
}
};
static auto noop = [&](CMutableTransaction &mtx){};
template<typename Modifier>
void SetupEval(EvalMock &eval, CMutableTransaction &notary, Modifier modify)
{
eval.nNotaries = komodo_notaries(eval.notaries, 780060, 1522946781);
// make fake notary inputs
notary.vin.resize(11);
for (int i=0; i<notary.vin.size(); i++) {
CMutableTransaction txIn;
txIn.vout.resize(1);
txIn.vout[0].scriptPubKey << VCH(eval.notaries[i*2], 33) << OP_CHECKSIG;
notary.vin[i].prevout = COutPoint(txIn.GetHash(), 0);
eval.txs[txIn.GetHash()] = CTransaction(txIn);
}
modify(notary);
eval.txs[notary.GetHash()] = CTransaction(notary);
eval.blocks[notary.GetHash()].nHeight = 780060;
eval.blocks[notary.GetHash()].nTime = 1522946781;
}
return false;
}
bool GetBlock(uint256 hash, CBlockIndex& blockIdx) const
{
auto r = blocks.find(hash);
if (r == blocks.end()) return false;
blockIdx = r->second;
return true;
}
};
static auto noop = [&](CMutableTransaction &mtx){};
template<typename Modifier>
void SetEval(EvalMock &eval, CMutableTransaction &notary, Modifier modify)
{
eval.nNotaries = komodo_notaries(eval.notaries, 780060, 1522946781);
// make fake notary inputs
notary.vin.resize(11);
for (int i=0; i<notary.vin.size(); i++) {
CMutableTransaction txIn;
txIn.vout.resize(1);
txIn.vout[0].scriptPubKey << VCH(eval.notaries[i*2], 33) << OP_CHECKSIG;
notary.vin[i].prevout = COutPoint(txIn.GetHash(), 0);
eval.txs[txIn.GetHash()] = CTransaction(txIn);
}
modify(notary);
eval.txs[notary.GetHash()] = CTransaction(notary);
eval.blocks[notary.GetHash()].nHeight = 780060;
eval.blocks[notary.GetHash()].nTime = 1522946781;
// https://kmd.explorer.supernet.org/tx/5b8055d37cff745a404d1ae45e21ffdba62da7b28ed6533c67468d7379b20bae
// inputs have been dropped
static auto rawNotaryTx = "01000000000290460100000000002321020e46e79a2a8d12b9b5d12c7a91adb4e454edfae43c0a0cb805427d2ac7613fd9ac0000000000000000506a4c4dae8e0f3e6e5de498a072f5967f3c418c4faba5d56ac8ce17f472d029ef3000008f2e0100424f545300050ba773f0bc31da5839fc7cb9bd7b87f3b765ca608e5cf66785a466659b28880500000000000000";
CTransaction notaryTx;
static bool init = DecodeHexTx(notaryTx, rawNotaryTx);
EVAL_TEST = &eval;
}
// https://kmd.explorer.supernet.org/tx/5b8055d37cff745a404d1ae45e21ffdba62da7b28ed6533c67468d7379b20bae
// inputs have been dropped
static auto rawNotaryTx = "01000000000290460100000000002321020e46e79a2a8d12b9b5d12c7a91adb4e454edfae43c0a0cb805427d2ac7613fd9ac0000000000000000506a4c4dae8e0f3e6e5de498a072f5967f3c418c4faba5d56ac8ce17f472d029ef3000008f2e0100424f545300050ba773f0bc31da5839fc7cb9bd7b87f3b765ca608e5cf66785a466659b28880500000000000000";
CTransaction notaryTx;
static bool init = DecodeHexTx(notaryTx, rawNotaryTx);
static uint256 proofTxHash = uint256S("37f76551a16093fbb0a92ee635bbd45b3460da8fd00cf7d5a6b20d93e727fe4c");
static auto vMomProof = ParseHex("0303faecbdd4b3da128c2cd2701bb143820a967069375b2ec5b612f39bbfe78a8611978871c193457ab1e21b9520f4139f113b8d75892eb93ee247c18bccfd067efed7eacbfcdc8946cf22de45ad536ec0719034fb9bc825048fe6ab61fee5bd6e9aae0bb279738d46673c53d68eb2a72da6dbff215ee41a4d405a74ff7cd355805b"); // $ fiat/bots txMoMproof $proofTxHash
static uint256 proofTxHash = uint256S("37f76551a16093fbb0a92ee635bbd45b3460da8fd00cf7d5a6b20d93e727fe4c");
static auto vMomProof = ParseHex("0303faecbdd4b3da128c2cd2701bb143820a967069375b2ec5b612f39bbfe78a8611978871c193457ab1e21b9520f4139f113b8d75892eb93ee247c18bccfd067efed7eacbfcdc8946cf22de45ad536ec0719034fb9bc825048fe6ab61fee5bd6e9aae0bb279738d46673c53d68eb2a72da6dbff215ee41a4d405a74ff7cd355805b"); // $ fiat/bots txMoMproof $proofTxHash
/*
TEST(TestEvalNotarisation, testGetNotarisation)
{
EvalMock eval;
CMutableTransaction notary(notaryTx);
SetupEval(eval, notary, noop);
TEST(TestEvalNotarisation, testGetNotarisation)
{
EvalMock eval;
CMutableTransaction notary(notaryTx);
SetEval(eval, notary, noop);
NotarisationData data;
NotarisationData data;
ASSERT_TRUE(eval.GetNotarisationData(notary.GetHash(), data));
EXPECT_EQ(data.height, 77455);
EXPECT_EQ(data.blockHash.GetHex(), "000030ef29d072f417cec86ad5a5ab4f8c413c7f96f572a098e45d6e3e0f8eae");
@ -111,7 +108,7 @@ TEST(TestEvalNotarisation, testGetNotarisation)
MoMProof proof;
E_UNMARSHAL(vMomProof, ss >> proof);
EXPECT_EQ(data.MoM, proof.Exec(proofTxHash));
EXPECT_EQ(data.MoM, proof.branch.Exec(proofTxHash));
}
@ -119,13 +116,14 @@ TEST(TestEvalNotarisation, testInvalidNotaryPubkey)
{
EvalMock eval;
CMutableTransaction notary(notaryTx);
SetEval(eval, notary, noop);
SetupEval(eval, notary, noop);
memset(eval.notaries[10], 0, 33);
NotarisationData data;
ASSERT_FALSE(eval.GetNotarisationData(notary.GetHash(), data));
}
*/
TEST(TestEvalNotarisation, testInvalidNotarisationBadOpReturn)
@ -134,9 +132,9 @@ TEST(TestEvalNotarisation, testInvalidNotarisationBadOpReturn)
CMutableTransaction notary(notaryTx);
notary.vout[1].scriptPubKey = CScript() << OP_RETURN << 0;
SetEval(eval, notary, noop);
SetupEval(eval, notary, noop);
NotarisationData data;
NotarisationData data(0);
ASSERT_FALSE(eval.GetNotarisationData(notary.GetHash(), data));
}
@ -146,11 +144,11 @@ TEST(TestEvalNotarisation, testInvalidNotarisationTxNotEnoughSigs)
EvalMock eval;
CMutableTransaction notary(notaryTx);
SetEval(eval, notary, [](CMutableTransaction &tx) {
SetupEval(eval, notary, [](CMutableTransaction &tx) {
tx.vin.resize(10);
});
NotarisationData data;
NotarisationData data(0);
ASSERT_FALSE(eval.GetNotarisationData(notary.GetHash(), data));
}
@ -160,9 +158,9 @@ TEST(TestEvalNotarisation, testInvalidNotarisationTxDoesntExist)
EvalMock eval;
CMutableTransaction notary(notaryTx);
SetEval(eval, notary, noop);
SetupEval(eval, notary, noop);
NotarisationData data;
NotarisationData data(0);
ASSERT_FALSE(eval.GetNotarisationData(uint256(), data));
}
@ -172,11 +170,11 @@ TEST(TestEvalNotarisation, testInvalidNotarisationDupeNotary)
EvalMock eval;
CMutableTransaction notary(notaryTx);
SetEval(eval, notary, [](CMutableTransaction &tx) {
SetupEval(eval, notary, [](CMutableTransaction &tx) {
tx.vin[1] = tx.vin[3];
});
NotarisationData data;
NotarisationData data(0);
ASSERT_FALSE(eval.GetNotarisationData(notary.GetHash(), data));
}
@ -186,7 +184,7 @@ TEST(TestEvalNotarisation, testInvalidNotarisationInputNotCheckSig)
EvalMock eval;
CMutableTransaction notary(notaryTx);
SetEval(eval, notary, [&](CMutableTransaction &tx) {
SetupEval(eval, notary, [&](CMutableTransaction &tx) {
int i = 1;
CMutableTransaction txIn;
txIn.vout.resize(1);
@ -195,7 +193,7 @@ TEST(TestEvalNotarisation, testInvalidNotarisationInputNotCheckSig)
eval.txs[txIn.GetHash()] = CTransaction(txIn);
});
NotarisationData data;
NotarisationData data(0);
ASSERT_FALSE(eval.GetNotarisationData(notary.GetHash(), data));
}

54
src/test-komodo/test_parse_notarisation.cpp

@ -0,0 +1,54 @@
#include <gtest/gtest.h>
#include "cc/eval.h"
#include "core_io.h"
#include "key.h"
#include "testutils.h"
namespace TestParseNotarisation {
class TestParseNotarisation : public ::testing::Test, public Eval {};
TEST(TestParseNotarisation, test_ee2fa)
{
// ee2fa47820a31a979f9f21cb3fedbc484bf9a8957cb6c9acd0af28ced29bdfe1
std::vector<uint8_t> opret = ParseHex("c349ff90f3bce62c1b7b49d1da0423b1a3d9b733130cce825b95b9e047c729066e020d00743a06fdb95ad5775d032b30bbb3680dac2091a0f800cf54c79fd3461ce9b31d4b4d4400");
NotarisationData nd;
ASSERT_TRUE(E_UNMARSHAL(opret, ss >> nd));
}
TEST(TestParseNotarisation, test__)
{
// 576e910a1f704207bcbcf724124ff9adc5237f45cb6919589cd0aa152caec424
std::vector<uint8_t> opret = ParseHex("b3ed7fbbfbc027caeeeec81e65489ec5d9cd47cda675a5cbb75b4a845e67cf0ef6330300b5a6bd8385feb833f3be961c9d8a46fcecd36dcdfa42ad81a20a892433722f0b4b4d44004125a06024eae24c11f36ea110acd707b041d5355b6e1b42de5e2614357999c6aa02000d26ad0300000000404b4c000000000005130300500d000061f22ba7d19fe29ac3baebd839af8b7127d1f90755534400");
NotarisationData nd;
// We can't parse this one
ASSERT_FALSE(E_UNMARSHAL(opret, ss >> nd));
}
TEST(TestParseNotarisation, test__a)
{
// be55101e6c5a93fb3611a44bd66217ad8714d204275ea4e691cfff9d65dff85c TXSCL
std::vector<uint8_t> opret = ParseHex("fb9ea2818eec8b07f8811bab49d64379db074db478997f8114666f239bd79803cc460000d0fac4e715b7e2b917a5d79f85ece0c423d27bd3648fd39ac1dc7db8e1bd4b16545853434c00a69eab9f23d7fb63c4624973e7a9079d6ada2f327040936356d7af5e849f6d670a0003001caf7b7b9e1c9bc59d0c7a619c9683ab1dd0794b6f3ea184a19f8fda031150e700000000");
NotarisationData nd(1);
bool res = E_UNMARSHAL(opret, ss >> nd);
ASSERT_TRUE(res);
}
TEST(TestParseNotarisation, test__b)
{
// 03085dafed656aaebfda25bf43ffe9d1fb72565bb1fc8b2a12a631659f28f877 TXSCL
std::vector<uint8_t> opret = ParseHex("48c71a10aa060eab1a43f52acefac3b81fb2a2ce310186b06141884c0501d403c246000052e6d49afd82d9ab3d97c996dd9b6a78a554ffa1625e8dadf0494bd1f8442e3e545853434c007cc5c07e3b67520fd14e23cd5b49f2aa022f411500fd3326ff91e6dc0544a1c90c0003008b69117bb1376ac8df960f785d8c208c599d3a36248c98728256bb6d4737e59600000000");
NotarisationData nd(1);
bool res = E_UNMARSHAL(opret, ss >> nd);
ASSERT_TRUE(res);
}
// for l in `g 'parse notarisation' ~/.komodo/debug.log | pyline 'l.split()[8]'`; do hoek decodeTx '{"hex":"'`src/komodo-cli getrawtransaction "$l"`'"}' | jq '.outputs[1].script.op_return' | pyline 'import base64; print base64.b64decode(l).encode("hex")'; done
}

147
src/test-komodo/testutils.cpp

@ -0,0 +1,147 @@
#include <cryptoconditions.h>
#include <gtest/gtest.h>
#include <boost/filesystem.hpp>
#include "core_io.h"
#include "key.h"
#include "main.h"
#include "miner.h"
#include "notarisationdb.h"
#include "random.h"
#include "rpcserver.h"
#include "rpcprotocol.h"
#include "txdb.h"
#include "util.h"
#include "utilstrencodings.h"
#include "utiltime.h"
#include "consensus/validation.h"
#include "primitives/transaction.h"
#include "script/cc.h"
#include "script/interpreter.h"
#include "testutils.h"
std::string notaryPubkey = "0205a8ad0c1dbc515f149af377981aab58b836af008d4d7ab21bd76faf80550b47";
std::string notarySecret = "UxFWWxsf1d7w7K5TvAWSkeX4H95XQKwdwGv49DXwWUTzPTTjHBbU";
CKey notaryKey;
/*
* We need to have control of clock,
* otherwise block production can fail.
*/
int64_t nMockTime;
extern uint32_t USE_EXTERNAL_PUBKEY;
extern std::string NOTARY_PUBKEY;
void setupChain()
{
SelectParams(CBaseChainParams::REGTEST);
// Settings to get block reward
NOTARY_PUBKEY = notaryPubkey;
USE_EXTERNAL_PUBKEY = 1;
mapArgs["-mineraddress"] = "bogus";
COINBASE_MATURITY = 1;
// Global mock time
nMockTime = GetTime();
// Unload
UnloadBlockIndex();
// Init blockchain
ClearDatadirCache();
auto pathTemp = GetTempPath() / strprintf("test_komodo_%li_%i", GetTime(), GetRand(100000));
if (ASSETCHAINS_SYMBOL[0])
pathTemp = pathTemp / strprintf("_%s", ASSETCHAINS_SYMBOL);
boost::filesystem::create_directories(pathTemp);
mapArgs["-datadir"] = pathTemp.string();
pblocktree = new CBlockTreeDB(1 << 20, true);
CCoinsViewDB *pcoinsdbview = new CCoinsViewDB(1 << 23, true);
pcoinsTip = new CCoinsViewCache(pcoinsdbview);
pnotarisations = new NotarisationDB(1 << 20, true);
InitBlockIndex();
}
void generateBlock(CBlock *block)
{
UniValue params;
params.setArray();
params.push_back(1);
uint256 blockId;
SetMockTime(nMockTime+=100); // CreateNewBlock can fail if not enough time passes
try {
UniValue out = generate(params, false);
blockId.SetHex(out[0].getValStr());
if (block) ASSERT_TRUE(ReadBlockFromDisk(*block, mapBlockIndex[blockId], false));
} catch (const UniValue& e) {
FAIL() << "failed to create block: " << e.write().data();
}
}
void acceptTxFail(const CTransaction tx)
{
CValidationState state;
if (!acceptTx(tx, state)) FAIL() << state.GetRejectReason();
}
bool acceptTx(const CTransaction tx, CValidationState &state)
{
LOCK(cs_main);
return AcceptToMemoryPool(mempool, state, tx, false, NULL);
}
CMutableTransaction spendTx(const CTransaction &txIn, int nOut)
{
CMutableTransaction mtx;
mtx.vin.resize(1);
mtx.vin[0].prevout.hash = txIn.GetHash();
mtx.vin[0].prevout.n = nOut;
mtx.vout.resize(1);
mtx.vout[0].nValue = txIn.vout[nOut].nValue - 1000;
return mtx;
}
std::vector<uint8_t> getSig(const CMutableTransaction mtx, CScript inputPubKey, int nIn)
{
uint256 hash = SignatureHash(inputPubKey, mtx, nIn, SIGHASH_ALL, 0, 0);
std::vector<uint8_t> vchSig;
notaryKey.Sign(hash, vchSig);
vchSig.push_back((unsigned char)SIGHASH_ALL);
return vchSig;
}
/*
* In order to do tests there needs to be inputs to spend.
* This method creates a block and returns a transaction that spends the coinbase.
*/
void getInputTx(CScript scriptPubKey, CTransaction &txIn)
{
// Get coinbase
CBlock block;
generateBlock(&block);
CTransaction coinbase = block.vtx[0];
// Create tx
auto mtx = spendTx(coinbase);
mtx.vout[0].scriptPubKey = scriptPubKey;
uint256 hash = SignatureHash(coinbase.vout[0].scriptPubKey, mtx, 0, SIGHASH_ALL, 0, 0);
std::vector<unsigned char> vchSig;
notaryKey.Sign(hash, vchSig);
vchSig.push_back((unsigned char)SIGHASH_ALL);
mtx.vin[0].scriptSig << vchSig;
// Accept
acceptTxFail(mtx);
txIn = CTransaction(mtx);
}

16
src/test-komodo/testutils.h

@ -1,7 +1,7 @@
#ifndef TESTUTILS_H
#define TESTUTILS_H
#include "script/cc.h"
#include "main.h"
#define VCH(a,b) std::vector<unsigned char>(a, a + b)
@ -12,4 +12,18 @@ static char ccjsonerr[1000] = "\0";
if (!o) FAIL() << "bad json: " << ccjsonerr;
extern std::string notaryPubkey;
extern std::string notarySecret;
extern CKey notaryKey;
void setupChain();
void generateBlock(CBlock *block=NULL);
bool acceptTx(const CTransaction tx, CValidationState &state);
void acceptTxFail(const CTransaction tx);
void getInputTx(CScript scriptPubKey, CTransaction &txIn);
CMutableTransaction spendTx(const CTransaction &txIn, int nOut=0);
std::vector<uint8_t> getSig(const CMutableTransaction mtx, CScript inputPubKey, int nIn=0);
#endif /* TESTUTILS_H */

447
src/test/alert_tests.cpp

@ -1,447 +0,0 @@
// Copyright (c) 2013 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
//
// Unit tests for alert system
//
#include "alert.h"
#include "chain.h"
#include "chainparams.h"
#include "clientversion.h"
#include "data/alertTests.raw.h"
#include "main.h"
#include "rpcprotocol.h"
#include "rpcserver.h"
#include "serialize.h"
#include "streams.h"
#include "util.h"
#include "utilstrencodings.h"
#include "test/test_bitcoin.h"
#include <fstream>
#include <boost/filesystem/operations.hpp>
#include <boost/foreach.hpp>
#include <boost/test/unit_test.hpp>
#include "key.h"
#include "alertkeys.h"
#include <iostream>
/*
* If the alert key pairs have changed, the test suite will fail as the
* test data is now invalid. To create valid test data, signed with a
* new alert private key, follow these steps:
*
* 1. Copy your private key into alertkeys.h. Don't commit this file!
* See sendalert.cpp for more info.
*
* 2. Set the GENERATE_ALERTS_FLAG to true.
*
* 3. Build and run:
* test_bitcoin -t Generate_Alert_Test_Data
*
* 4. Test data is saved in your current directory as alertTests.raw.NEW
* Copy this file to: src/test/data/alertTests.raw
*
* For debugging purposes, terminal output can be copied into:
* src/test/data/alertTests.raw.h
*
* 5. Clean up...
* - Set GENERATE_ALERTS_FLAG back to false.
* - Remove your private key from alertkeys.h
*
* 6. Build and verify the new test data:
* test_bitcoin -t Alert_tests
*
*/
#define GENERATE_ALERTS_FLAG false
#if GENERATE_ALERTS_FLAG
// NOTE:
// A function SignAndSave() was used by Bitcoin Core to create alert test data
// but it has not been made publicly available. So instead, we have adapted
// some publicly available code which achieves the intended result:
// https://gist.github.com/lukem512/9b272bd35e2cdefbf386
// Code to output a C-style array of values
template<typename T>
std::string HexStrArray(const T itbegin, const T itend, int lineLength)
{
std::string rv;
static const char hexmap[16] = { '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
rv.reserve((itend-itbegin)*3);
int i = 0;
for(T it = itbegin; it < itend; ++it)
{
unsigned char val = (unsigned char)(*it);
if(it != itbegin)
{
if (i % lineLength == 0)
rv.push_back('\n');
else
rv.push_back(' ');
}
rv.push_back('0');
rv.push_back('x');
rv.push_back(hexmap[val>>4]);
rv.push_back(hexmap[val&15]);
rv.push_back(',');
i++;
}
return rv;
}
template<typename T>
inline std::string HexStrArray(const T& vch, int lineLength)
{
return HexStrArray(vch.begin(), vch.end(), lineLength);
}
// Sign CAlert with alert private key
bool SignAlert(CAlert &alert)
{
// serialize alert data
CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
sMsg << *(CUnsignedAlert*)&alert;
alert.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
// sign alert
std::vector<unsigned char> vchTmp(ParseHex(pszPrivKey));
CPrivKey vchPrivKey(vchTmp.begin(), vchTmp.end());
CKey key;
if (!key.SetPrivKey(vchPrivKey, false))
{
printf("key.SetPrivKey failed\n");
return false;
}
if (!key.Sign(Hash(alert.vchMsg.begin(), alert.vchMsg.end()), alert.vchSig))
{
printf("SignAlert() : key.Sign failed\n");
return false;
}
return true;
}
// Sign a CAlert and serialize it
bool SignAndSerialize(CAlert &alert, CDataStream &buffer)
{
// Sign
if(!SignAlert(alert))
{
printf("SignAndSerialize() : could not sign alert\n");
return false;
}
// ...and save!
buffer << alert;
return true;
}
void GenerateAlertTests()
{
CDataStream sBuffer(SER_DISK, CLIENT_VERSION);
CAlert alert;
alert.nRelayUntil = 60;
alert.nExpiration = 24 * 60 * 60;
alert.nID = 1;
alert.nCancel = 0; // cancels previous messages up to this ID number
alert.nMinVer = 0; // These versions are protocol versions
alert.nMaxVer = 999001;
alert.nPriority = 1;
alert.strComment = "Alert comment";
alert.strStatusBar = "Alert 1";
// Replace SignAndSave with SignAndSerialize
SignAndSerialize(alert, sBuffer);
// More tests go here ...
alert.setSubVer.insert(std::string("/MagicBean:0.1.0/"));
alert.strStatusBar = "Alert 1 for MagicBean 0.1.0";
SignAndSerialize(alert, sBuffer);
alert.setSubVer.insert(std::string("/MagicBean:0.2.0/"));
alert.strStatusBar = "Alert 1 for MagicBean 0.1.0, 0.2.0";
SignAndSerialize(alert, sBuffer);
alert.setSubVer.clear();
++alert.nID;
alert.nCancel = 1;
alert.nPriority = 100;
alert.strStatusBar = "Alert 2, cancels 1";
SignAndSerialize(alert, sBuffer);
alert.nExpiration += 60;
++alert.nID;
SignAndSerialize(alert, sBuffer);
++alert.nID;
alert.nPriority = 5000;
alert.strStatusBar = "Alert 3, disables RPC";
alert.strRPCError = "RPC disabled";
SignAndSerialize(alert, sBuffer);
++alert.nID;
alert.nPriority = 5000;
alert.strStatusBar = "Alert 4, re-enables RPC";
alert.strRPCError = "";
SignAndSerialize(alert, sBuffer);
++alert.nID;
alert.nMinVer = 11;
alert.nMaxVer = 22;
alert.nPriority = 100;
SignAndSerialize(alert, sBuffer);
++alert.nID;
alert.strStatusBar = "Alert 2 for MagicBean 0.1.0";
alert.setSubVer.insert(std::string("/MagicBean:0.1.0/"));
SignAndSerialize(alert, sBuffer);
++alert.nID;
alert.nMinVer = 0;
alert.nMaxVer = 999999;
alert.strStatusBar = "Evil Alert'; /bin/ls; echo '";
alert.setSubVer.clear();
bool b = SignAndSerialize(alert, sBuffer);
if (b) {
// Print the hex array, which will become the contents of alertTest.raw.h
std::vector<unsigned char> vch = std::vector<unsigned char>(sBuffer.begin(), sBuffer.end());
printf("%s\n", HexStrArray(vch, 8).c_str());
// Write the data to alertTests.raw.NEW, to be copied to src/test/data/alertTests.raw
std::ofstream outfile("alertTests.raw.NEW", std::ios::out | std::ios::binary);
outfile.write((const char*)&vch[0], vch.size());
outfile.close();
}
}
struct GenerateAlertTestsFixture : public TestingSetup {
GenerateAlertTestsFixture() {}
~GenerateAlertTestsFixture() {}
};
BOOST_FIXTURE_TEST_SUITE(Generate_Alert_Test_Data, GenerateAlertTestsFixture);
BOOST_AUTO_TEST_CASE(GenerateTheAlertTests)
{
GenerateAlertTests();
}
BOOST_AUTO_TEST_SUITE_END()
#else
struct ReadAlerts : public TestingSetup
{
ReadAlerts()
{
std::vector<unsigned char> vch(alert_tests::alertTests, alert_tests::alertTests + sizeof(alert_tests::alertTests));
CDataStream stream(vch, SER_DISK, CLIENT_VERSION);
try {
while (!stream.eof())
{
CAlert alert;
stream >> alert;
alerts.push_back(alert);
}
}
catch (const std::exception&) { }
}
~ReadAlerts() { }
static std::vector<std::string> read_lines(boost::filesystem::path filepath)
{
std::vector<std::string> result;
std::ifstream f(filepath.string().c_str());
std::string line;
while (std::getline(f,line))
result.push_back(line);
return result;
}
std::vector<CAlert> alerts;
};
BOOST_FIXTURE_TEST_SUITE(Alert_tests, ReadAlerts)
BOOST_AUTO_TEST_CASE(AlertApplies)
{
SetMockTime(11);
const std::vector<unsigned char>& alertKey = Params(CBaseChainParams::MAIN).AlertKey();
BOOST_FOREACH(const CAlert& alert, alerts)
{
BOOST_CHECK(alert.CheckSignature(alertKey));
}
BOOST_CHECK(alerts.size() >= 3);
// Matches:
BOOST_CHECK(alerts[0].AppliesTo(1, ""));
BOOST_CHECK(alerts[0].AppliesTo(999001, ""));
BOOST_CHECK(alerts[0].AppliesTo(1, "/MagicBean:11.11.11/"));
BOOST_CHECK(alerts[1].AppliesTo(1, "/MagicBean:0.1.0/"));
BOOST_CHECK(alerts[1].AppliesTo(999001, "/MagicBean:0.1.0/"));
BOOST_CHECK(alerts[2].AppliesTo(1, "/MagicBean:0.1.0/"));
BOOST_CHECK(alerts[2].AppliesTo(1, "/MagicBean:0.2.0/"));
// Don't match:
BOOST_CHECK(!alerts[0].AppliesTo(-1, ""));
BOOST_CHECK(!alerts[0].AppliesTo(999002, ""));
BOOST_CHECK(!alerts[1].AppliesTo(1, ""));
BOOST_CHECK(!alerts[1].AppliesTo(1, "MagicBean:0.1.0"));
BOOST_CHECK(!alerts[1].AppliesTo(1, "/MagicBean:0.1.0"));
BOOST_CHECK(!alerts[1].AppliesTo(1, "MagicBean:0.1.0/"));
BOOST_CHECK(!alerts[1].AppliesTo(-1, "/MagicBean:0.1.0/"));
BOOST_CHECK(!alerts[1].AppliesTo(999002, "/MagicBean:0.1.0/"));
BOOST_CHECK(!alerts[1].AppliesTo(1, "/MagicBean:0.2.0/"));
BOOST_CHECK(!alerts[2].AppliesTo(1, "/MagicBean:0.3.0/"));
SetMockTime(0);
}
BOOST_AUTO_TEST_CASE(AlertNotify)
{
SetMockTime(11);
const std::vector<unsigned char>& alertKey = Params(CBaseChainParams::MAIN).AlertKey();
boost::filesystem::path temp = GetTempPath() /
boost::filesystem::unique_path("alertnotify-%%%%.txt");
mapArgs["-alertnotify"] = std::string("echo %s >> ") + temp.string();
BOOST_FOREACH(CAlert alert, alerts)
alert.ProcessAlert(alertKey, false);
std::vector<std::string> r = read_lines(temp);
BOOST_CHECK_EQUAL(r.size(), 6u);
// Windows built-in echo semantics are different than posixy shells. Quotes and
// whitespace are printed literally.
#ifndef _WIN32
BOOST_CHECK_EQUAL(r[0], "Alert 1");
BOOST_CHECK_EQUAL(r[1], "Alert 2, cancels 1");
BOOST_CHECK_EQUAL(r[2], "Alert 2, cancels 1");
BOOST_CHECK_EQUAL(r[3], "Alert 3, disables RPC");
BOOST_CHECK_EQUAL(r[4], "Alert 4, reenables RPC"); // dashes should be removed
BOOST_CHECK_EQUAL(r[5], "Evil Alert; /bin/ls; echo "); // single-quotes should be removed
#else
BOOST_CHECK_EQUAL(r[0], "'Alert 1' ");
BOOST_CHECK_EQUAL(r[1], "'Alert 2, cancels 1' ");
BOOST_CHECK_EQUAL(r[2], "'Alert 2, cancels 1' ");
BOOST_CHECK_EQUAL(r[3], "'Alert 3, disables RPC' ");
BOOST_CHECK_EQUAL(r[4], "'Alert 4, reenables RPC' "); // dashes should be removed
BOOST_CHECK_EQUAL(r[5], "'Evil Alert; /bin/ls; echo ' ");
#endif
boost::filesystem::remove(temp);
SetMockTime(0);
mapAlerts.clear();
}
BOOST_AUTO_TEST_CASE(AlertDisablesRPC)
{
SetMockTime(11);
const std::vector<unsigned char>& alertKey = Params(CBaseChainParams::MAIN).AlertKey();
// Command should work before alerts
BOOST_CHECK_EQUAL(GetWarnings("rpc"), "");
// First alert should disable RPC
alerts[5].ProcessAlert(alertKey, false);
BOOST_CHECK_EQUAL(alerts[5].strRPCError, "RPC disabled");
BOOST_CHECK_EQUAL(GetWarnings("rpc"), "RPC disabled");
// Second alert should re-enable RPC
alerts[6].ProcessAlert(alertKey, false);
BOOST_CHECK_EQUAL(alerts[6].strRPCError, "");
BOOST_CHECK_EQUAL(GetWarnings("rpc"), "");
SetMockTime(0);
mapAlerts.clear();
}
static bool falseFunc() { return false; }
BOOST_AUTO_TEST_CASE(PartitionAlert)
{
// Test PartitionCheck
CCriticalSection csDummy;
CBlockIndex indexDummy[400];
CChainParams& params = Params(CBaseChainParams::MAIN);
int64_t nPowTargetSpacing = params.GetConsensus().nPowTargetSpacing;
// Generate fake blockchain timestamps relative to
// an arbitrary time:
int64_t now = 1427379054;
SetMockTime(now);
for (int i = 0; i < 400; i++)
{
indexDummy[i].phashBlock = NULL;
if (i == 0) indexDummy[i].pprev = NULL;
else indexDummy[i].pprev = &indexDummy[i-1];
indexDummy[i].nHeight = i;
indexDummy[i].nTime = now - (400-i)*nPowTargetSpacing;
// Other members don't matter, the partition check code doesn't
// use them
}
// Test 1: chain with blocks every nPowTargetSpacing seconds,
// as normal, no worries:
PartitionCheck(falseFunc, csDummy, &indexDummy[399], nPowTargetSpacing);
BOOST_CHECK(strMiscWarning.empty());
// Test 2: go 3.5 hours without a block, expect a warning:
now += 3*60*60+30*60;
SetMockTime(now);
PartitionCheck(falseFunc, csDummy, &indexDummy[399], nPowTargetSpacing);
BOOST_CHECK(!strMiscWarning.empty());
BOOST_TEST_MESSAGE(std::string("Got alert text: ")+strMiscWarning);
strMiscWarning = "";
// Test 3: test the "partition alerts only go off once per day"
// code:
now += 60*10;
SetMockTime(now);
PartitionCheck(falseFunc, csDummy, &indexDummy[399], nPowTargetSpacing);
BOOST_CHECK(strMiscWarning.empty());
// Test 4: get 2.5 times as many blocks as expected:
now += 60*60*24; // Pretend it is a day later
SetMockTime(now);
int64_t quickSpacing = nPowTargetSpacing*2/5;
for (int i = 0; i < 400; i++) // Tweak chain timestamps:
indexDummy[i].nTime = now - (400-i)*quickSpacing;
PartitionCheck(falseFunc, csDummy, &indexDummy[399], nPowTargetSpacing);
BOOST_CHECK(!strMiscWarning.empty());
BOOST_TEST_MESSAGE(std::string("Got alert text: ")+strMiscWarning);
strMiscWarning = "";
SetMockTime(0);
}
BOOST_AUTO_TEST_SUITE_END()
#endif

30
src/test/miner_tests.cpp

@ -158,7 +158,7 @@ BOOST_AUTO_TEST_CASE(CreateNewBlock_validity)
for (unsigned int i = 0; i < sizeof(blockinfo)/sizeof(*blockinfo); ++i)
{
// Simple block creation, nothing special yet:
BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey));
BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey,-1));
CBlock *pblock = &pblocktemplate->block; // pointer for convenience
pblock->nVersion = 4;
@ -242,7 +242,7 @@ BOOST_AUTO_TEST_CASE(CreateNewBlock_validity)
CValidationState state;
if (ProcessNewBlock(1,state, NULL, pblock, true, NULL) && state.IsValid()) {
if (ProcessNewBlock(1,0,state, NULL, pblock, true, NULL) && state.IsValid()) {
goto foundit;
}
@ -261,7 +261,7 @@ BOOST_AUTO_TEST_CASE(CreateNewBlock_validity)
*/
CValidationState state;
BOOST_CHECK(ProcessNewBlock(1,state, NULL, pblock, true, NULL));
BOOST_CHECK(ProcessNewBlock(1,0,state, NULL, pblock, true, NULL));
BOOST_CHECK_MESSAGE(state.IsValid(), state.GetRejectReason());
pblock->hashPrevBlock = pblock->GetHash();
@ -270,7 +270,7 @@ BOOST_AUTO_TEST_CASE(CreateNewBlock_validity)
}
// Just to make sure we can still make simple blocks
BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey));
BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey,-1));
delete pblocktemplate;
// block sigops > limit: 1000 CHECKMULTISIG + 1
@ -289,7 +289,7 @@ BOOST_AUTO_TEST_CASE(CreateNewBlock_validity)
mempool.addUnchecked(hash, entry.Time(GetTime()).SpendsCoinbase(spendsCoinbase).FromTx(tx));
tx.vin[0].prevout.hash = hash;
}
BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey));
BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey,-1));
delete pblocktemplate;
mempool.clear();
@ -310,14 +310,14 @@ BOOST_AUTO_TEST_CASE(CreateNewBlock_validity)
mempool.addUnchecked(hash, entry.Time(GetTime()).SpendsCoinbase(spendsCoinbase).FromTx(tx));
tx.vin[0].prevout.hash = hash;
}
BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey));
BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey,-1));
delete pblocktemplate;
mempool.clear();
// orphan in mempool
hash = tx.GetHash();
mempool.addUnchecked(hash, entry.Time(GetTime()).FromTx(tx));
BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey));
BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey,-1));
delete pblocktemplate;
mempool.clear();
@ -335,7 +335,7 @@ BOOST_AUTO_TEST_CASE(CreateNewBlock_validity)
tx.vout[0].nValue = 49000LL;
hash = tx.GetHash();
mempool.addUnchecked(hash, entry.Time(GetTime()).SpendsCoinbase(true).FromTx(tx));
BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey));
BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey,-1));
delete pblocktemplate;
mempool.clear();
@ -346,7 +346,7 @@ BOOST_AUTO_TEST_CASE(CreateNewBlock_validity)
tx.vout[0].nValue = 0;
hash = tx.GetHash();
mempool.addUnchecked(hash, entry.Time(GetTime()).SpendsCoinbase(false).FromTx(tx));
BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey));
BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey,-1));
delete pblocktemplate;
mempool.clear();
@ -364,7 +364,7 @@ BOOST_AUTO_TEST_CASE(CreateNewBlock_validity)
tx.vout[0].nValue -= 10000;
hash = tx.GetHash();
mempool.addUnchecked(hash, entry.Time(GetTime()).SpendsCoinbase(false).FromTx(tx));
BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey));
BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey,-1));
delete pblocktemplate;
mempool.clear();
@ -378,17 +378,17 @@ BOOST_AUTO_TEST_CASE(CreateNewBlock_validity)
tx.vout[0].scriptPubKey = CScript() << OP_2;
hash = tx.GetHash();
mempool.addUnchecked(hash, entry.Time(GetTime()).SpendsCoinbase(true).FromTx(tx));
BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey));
BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey,-1));
delete pblocktemplate;
mempool.clear();
// subsidy changing
int nHeight = chainActive.Height();
chainActive.Tip()->nHeight = 209999;
BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey));
BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey,-1));
delete pblocktemplate;
chainActive.Tip()->nHeight = 210000;
BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey));
BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey,-1));
delete pblocktemplate;
chainActive.Tip()->nHeight = nHeight;
@ -420,7 +420,7 @@ BOOST_AUTO_TEST_CASE(CreateNewBlock_validity)
mempool.addUnchecked(hash, entry.Time(GetTime()).SpendsCoinbase(true).FromTx(tx2));
BOOST_CHECK(!CheckFinalTx(tx2, LOCKTIME_MEDIAN_TIME_PAST));
BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey));
BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey,-1));
// Neither tx should have made it into the template.
BOOST_CHECK_EQUAL(pblocktemplate->block.vtx.size(), 1);
@ -435,7 +435,7 @@ BOOST_AUTO_TEST_CASE(CreateNewBlock_validity)
//BOOST_CHECK(CheckFinalTx(tx));
//BOOST_CHECK(CheckFinalTx(tx2));
BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey));
BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey,-1));
BOOST_CHECK_EQUAL(pblocktemplate->block.vtx.size(), 2);
delete pblocktemplate;

139
src/txdb.cpp

@ -10,6 +10,7 @@
#include "main.h"
#include "pow.h"
#include "uint256.h"
#include "core_io.h"
#include <stdint.h>
@ -396,6 +397,144 @@ bool CBlockTreeDB::ReadAddressIndex(uint160 addressHash, int type,
return true;
}
bool getAddressFromIndex(const int &type, const uint160 &hash, std::string &address);
extern UniValue CBlockTreeDB::Snapshot(int top)
{
char chType; int64_t total = 0; int64_t totalAddresses = 0; std::string address;
int64_t utxos = 0; int64_t ignoredAddresses;
boost::scoped_ptr<leveldb::Iterator> iter(NewIterator());
std::map <std::string, CAmount> addressAmounts;
std::vector <std::pair<CAmount, std::string>> vaddr;
UniValue result(UniValue::VOBJ);
result.push_back(Pair("start_time", (int) time(NULL)));
std::map <std::string,int> ignoredMap = {
{"RReUxSs5hGE39ELU23DfydX8riUuzdrHAE", 1},
{"RMUF3UDmzWFLSKV82iFbMaqzJpUnrWjcT4", 1},
{"RA5imhVyJa7yHhggmBytWuDr923j2P1bxx", 1},
{"RBM5LofZFodMeewUzoMWcxedm3L3hYRaWg", 1},
{"RAdcko2d94TQUcJhtFHZZjMyWBKEVfgn4J", 1},
{"RLzUaZ934k2EFCsAiVjrJqM8uU1vmMRFzk", 1},
{"RMSZMWZXv4FhUgWhEo4R3AQXmRDJ6rsGyt", 1},
{"RUDrX1v5toCsJMUgtvBmScKjwCB5NaR8py", 1},
{"RMSZMWZXv4FhUgWhEo4R3AQXmRDJ6rsGyt", 1},
{"RRvwmbkxR5YRzPGL5kMFHMe1AH33MeD8rN", 1},
{"RQLQvSgpPAJNPgnpc8MrYsbBhep95nCS8L", 1},
{"RK8JtBV78HdvEPvtV5ckeMPSTojZPzHUTe", 1},
{"RHVs2KaCTGUMNv3cyWiG1jkEvZjigbCnD2", 1},
{"RE3SVaDgdjkRPYA6TRobbthsfCmxQedVgF", 1},
{"RW6S5Lw5ZCCvDyq4QV9vVy7jDHfnynr5mn", 1},
{"RTkJwAYtdXXhVsS3JXBAJPnKaBfMDEswF8", 1},
{"RD6GgnrMpPaTSMn8vai6yiGA7mN4QGPVMY", 1} //Burnaddress for null privkey
};
int64_t startingHeight = chainActive.Height();
fprintf(stderr, "Starting snapshot at height %li\n", startingHeight);
for (iter->SeekToLast(); iter->Valid(); iter->Prev())
{
boost::this_thread::interruption_point();
try
{
leveldb::Slice slKey = iter->key();
CDataStream ssKey(slKey.data(), slKey.data()+slKey.size(), SER_DISK, CLIENT_VERSION);
CAddressIndexIteratorKey indexKey;
ssKey >> chType;
ssKey >> indexKey;
//fprintf(stderr, "chType=%d\n", chType);
if (chType == DB_ADDRESSUNSPENTINDEX)
{
try {
leveldb::Slice slValue = iter->value();
CDataStream ssValue(slValue.data(), slValue.data()+slValue.size(), SER_DISK, CLIENT_VERSION);
CAmount nValue;
ssValue >> nValue;
getAddressFromIndex(indexKey.type, indexKey.hashBytes, address);
std::map <std::string, int>::iterator ignored = ignoredMap.find(address);
if (ignored != ignoredMap.end()) {
fprintf(stderr,"ignoring %s\n", address.c_str());
ignoredAddresses++;
continue;
}
std::map <std::string, CAmount>::iterator pos = addressAmounts.find(address);
if (pos == addressAmounts.end()) {
// insert new address + utxo amount
//fprintf(stderr, "inserting new address %s with amount %li\n", address.c_str(), nValue);
addressAmounts[address] = nValue;
totalAddresses++;
} else {
// update unspent tally for this address
//fprintf(stderr, "updating address %s with new utxo amount %li\n", address.c_str(), nValue);
addressAmounts[address] += nValue;
}
//fprintf(stderr,"{\"%s\", %.8f},\n",address.c_str(),(double)nValue/COIN);
// total += nValue;
utxos++;
} catch (const std::exception& e) {
fprintf(stderr, "DONE %s: LevelDB addressindex exception! - %s\n", __func__, e.what());
break;
}
}
} catch (const std::exception& e) {
fprintf(stderr, "DONE reading index entries\n");
break;
}
}
UniValue addresses(UniValue::VARR);
fprintf(stderr, "total=%f, totalAddresses=%li, utxos=%li, ignored=%li\n", (double) total / COIN, totalAddresses, utxos, ignoredAddresses);
for (std::pair<std::string, CAmount> element : addressAmounts) {
vaddr.push_back( make_pair(element.second, element.first) );
}
std::sort(vaddr.rbegin(), vaddr.rend());
UniValue obj(UniValue::VOBJ);
UniValue addressesSorted(UniValue::VARR);
int topN = 0;
for (std::vector<std::pair<CAmount, std::string>>::iterator it = vaddr.begin(); it!=vaddr.end(); ++it) {
UniValue obj(UniValue::VOBJ);
obj.push_back( make_pair("addr", it->second.c_str() ) );
char amount[32];
sprintf(amount, "%.8f", (double) it->first / COIN);
obj.push_back( make_pair("amount", amount) );
total += it->first;
addressesSorted.push_back(obj);
topN++;
// If requested, only show top N addresses in output JSON
if (top == topN)
break;
}
if (top)
totalAddresses = top;
if (totalAddresses > 0) {
// Array of all addreses with balances
result.push_back(make_pair("addresses", addressesSorted));
// Total amount in this snapshot, which is less than circulating supply if top parameter is used
result.push_back(make_pair("total", (double) total / COIN ));
// Average amount in each address of this snapshot
result.push_back(make_pair("average",(double) (total/COIN) / totalAddresses ));
}
// Total number of utxos processed in this snaphot
result.push_back(make_pair("utxos", utxos));
// Total number of addresses in this snaphot
result.push_back(make_pair("total_addresses", totalAddresses));
// Total number of ignored addresses in this snaphot
result.push_back(make_pair("ignored_addresses", ignoredAddresses));
// The snapshot began at this block height
result.push_back(make_pair("start_height", startingHeight));
// The snapshot finished at this block height
result.push_back(make_pair("ending_height", chainActive.Height()));
return(result);
}
bool CBlockTreeDB::WriteTimestampIndex(const CTimestampIndexKey &timestampIndex) {
CLevelDBBatch batch;
batch.Write(make_pair(DB_TIMESTAMPINDEX, timestampIndex), 0);

2
src/txdb.h

@ -13,6 +13,7 @@
#include <string>
#include <utility>
#include <vector>
#include <univalue.h>
class CBlockFileInfo;
class CBlockIndex;
@ -94,6 +95,7 @@ public:
bool ReadFlag(const std::string &name, bool &fValue);
bool LoadBlockIndexGuts();
bool blockOnchainActive(const uint256 &hash);
UniValue Snapshot(int top);
};
#endif // BITCOIN_TXDB_H

57
src/txmempool.cpp

@ -104,8 +104,10 @@ bool CTxMemPool::addUnchecked(const uint256& hash, const CTxMemPoolEntry &entry,
LOCK(cs);
mapTx.insert(entry);
const CTransaction& tx = mapTx.find(hash)->GetTx();
for (unsigned int i = 0; i < tx.vin.size(); i++)
mapNextTx[tx.vin[i].prevout] = CInPoint(&tx, i);
if (!tx.IsCoinImport()) {
for (unsigned int i = 0; i < tx.vin.size(); i++)
mapNextTx[tx.vin[i].prevout] = CInPoint(&tx, i);
}
BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
mapNullifiers[nf] = &tx;
@ -135,14 +137,28 @@ void CTxMemPool::addAddressIndex(const CTxMemPoolEntry &entry, const CCoinsViewC
CMempoolAddressDelta delta(entry.GetTime(), prevout.nValue * -1, input.prevout.hash, input.prevout.n);
mapAddress.insert(make_pair(key, delta));
inserted.push_back(key);
} else if (prevout.scriptPubKey.IsPayToPublicKeyHash()) {
}
else if (prevout.scriptPubKey.IsPayToPublicKeyHash()) {
vector<unsigned char> hashBytes(prevout.scriptPubKey.begin()+3, prevout.scriptPubKey.begin()+23);
CMempoolAddressDeltaKey key(1, uint160(hashBytes), txhash, j, 1);
CMempoolAddressDelta delta(entry.GetTime(), prevout.nValue * -1, input.prevout.hash, input.prevout.n);
mapAddress.insert(make_pair(key, delta));
inserted.push_back(key);
}
}
else if (prevout.scriptPubKey.IsPayToPublicKey()) {
vector<unsigned char> hashBytes(prevout.scriptPubKey.begin()+1, prevout.scriptPubKey.begin()+34);
CMempoolAddressDeltaKey key(1, Hash160(hashBytes), txhash, j, 1);
CMempoolAddressDelta delta(entry.GetTime(), prevout.nValue * -1, input.prevout.hash, input.prevout.n);
mapAddress.insert(make_pair(key, delta));
inserted.push_back(key);
}
else if (prevout.scriptPubKey.IsPayToCryptoCondition()) {
vector<unsigned char> hashBytes(prevout.scriptPubKey.begin(), prevout.scriptPubKey.end());
CMempoolAddressDeltaKey key(1, Hash160(hashBytes), txhash, j, 1);
CMempoolAddressDelta delta(entry.GetTime(), prevout.nValue * -1, input.prevout.hash, input.prevout.n);
mapAddress.insert(make_pair(key, delta));
inserted.push_back(key);
} }
for (unsigned int k = 0; k < tx.vout.size(); k++) {
const CTxOut &out = tx.vout[k];
@ -151,13 +167,28 @@ void CTxMemPool::addAddressIndex(const CTxMemPoolEntry &entry, const CCoinsViewC
CMempoolAddressDeltaKey key(2, uint160(hashBytes), txhash, k, 0);
mapAddress.insert(make_pair(key, CMempoolAddressDelta(entry.GetTime(), out.nValue)));
inserted.push_back(key);
} else if (out.scriptPubKey.IsPayToPublicKeyHash()) {
}
else if (out.scriptPubKey.IsPayToPublicKeyHash()) {
vector<unsigned char> hashBytes(out.scriptPubKey.begin()+3, out.scriptPubKey.begin()+23);
std::pair<addressDeltaMap::iterator,bool> ret;
CMempoolAddressDeltaKey key(1, uint160(hashBytes), txhash, k, 0);
mapAddress.insert(make_pair(key, CMempoolAddressDelta(entry.GetTime(), out.nValue)));
inserted.push_back(key);
}
else if (out.scriptPubKey.IsPayToPublicKey()) {
vector<unsigned char> hashBytes(out.scriptPubKey.begin()+1, out.scriptPubKey.begin()+34);
std::pair<addressDeltaMap::iterator,bool> ret;
CMempoolAddressDeltaKey key(1, Hash160(hashBytes), txhash, k, 0);
mapAddress.insert(make_pair(key, CMempoolAddressDelta(entry.GetTime(), out.nValue)));
inserted.push_back(key);
}
else if (out.scriptPubKey.IsPayToCryptoCondition()) {
vector<unsigned char> hashBytes(out.scriptPubKey.begin(), out.scriptPubKey.end());
std::pair<addressDeltaMap::iterator,bool> ret;
CMempoolAddressDeltaKey key(1, Hash160(hashBytes), txhash, k, 0);
mapAddress.insert(make_pair(key, CMempoolAddressDelta(entry.GetTime(), out.nValue)));
inserted.push_back(key);
}
}
mapAddressInserted.insert(make_pair(txhash, inserted));
@ -210,10 +241,20 @@ void CTxMemPool::addSpentIndex(const CTxMemPoolEntry &entry, const CCoinsViewCac
if (prevout.scriptPubKey.IsPayToScriptHash()) {
addressHash = uint160(vector<unsigned char> (prevout.scriptPubKey.begin()+2, prevout.scriptPubKey.begin()+22));
addressType = 2;
} else if (prevout.scriptPubKey.IsPayToPublicKeyHash()) {
}
else if (prevout.scriptPubKey.IsPayToPublicKeyHash()) {
addressHash = uint160(vector<unsigned char> (prevout.scriptPubKey.begin()+3, prevout.scriptPubKey.begin()+23));
addressType = 1;
} else {
}
else if (prevout.scriptPubKey.IsPayToPublicKey()) {
addressHash = Hash160(vector<unsigned char> (prevout.scriptPubKey.begin()+1, prevout.scriptPubKey.begin()+34));
addressType = 1;
}
else if (prevout.scriptPubKey.IsPayToCryptoCondition()) {
addressHash = Hash160(vector<unsigned char> (prevout.scriptPubKey.begin(), prevout.scriptPubKey.end()));
addressType = 1;
}
else {
addressHash.SetNull();
addressType = 0;
}
@ -418,7 +459,7 @@ void CTxMemPool::removeExpired(unsigned int nBlockHeight)
for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++)
{
const CTransaction& tx = it->GetTx();
tipindex = chainActive.Tip();
tipindex = chainActive.LastTip();
if (IsExpiredTx(tx, nBlockHeight) || (ASSETCHAINS_SYMBOL[0] == 0 && tipindex != 0 && komodo_validate_interest(tx,tipindex->nHeight+1,tipindex->GetMedianTimePast() + 777,0)) < 0)
{
transactionsToRemove.push_back(tx);

2
src/verusd

@ -2,4 +2,4 @@
#set working directory to the location of this script
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd $DIR
./komodod -ac_name=VRSC -ac_algo=verushash -ac_cc=1 -ac_supply=0 -ac_eras=3 -ac_reward=0,38400000000,2400000000 -ac_halving=1,43200,1051920 -ac_decay=100000000,0,0 -ac_end=10080,226080,0 -addnode=185.25.48.72 -addnode=185.25.48.236 -addnode=185.64.105.111 -ac_timelockgte=19200000000 -ac_timeunlockfrom=129600 -ac_timeunlockto=1180800 -ac_veruspos=50 -gen -genproclimit=0 "$@"
./komodod -ac_name=VRSC -ac_algo=verushash -ac_cc=1 -ac_supply=0 -ac_eras=3 -ac_reward=0,38400000000,2400000000 -ac_halving=1,43200,1051920 -ac_decay=100000000,0,0 -ac_end=10080,226080,0 -ac_timelockgte=19200000000 -ac_timeunlockfrom=129600 -ac_timeunlockto=1180800 -ac_veruspos=50 -gen -genproclimit=0 "$@"

4
src/wallet/asyncrpcoperation_mergetoaddress.cpp

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

4
src/wallet/asyncrpcoperation_sendmany.cpp

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

4
src/wallet/asyncrpcoperation_shieldcoinbase.cpp

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

36
src/wallet/rpcdump.cpp

@ -64,7 +64,7 @@ std::string DecodeDumpString(const std::string &str) {
for (unsigned int pos = 0; pos < str.length(); pos++) {
unsigned char c = str[pos];
if (c == '%' && pos+2 < str.length()) {
c = (((str[pos+1]>>6)*9+((str[pos+1]-'0')&15)) << 4) |
c = (((str[pos+1]>>6)*9+((str[pos+1]-'0')&15)) << 4) |
((str[pos+2]>>6)*9+((str[pos+2]-'0')&15));
pos += 2;
}
@ -77,13 +77,13 @@ UniValue importprivkey(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 1 || params.size() > 3)
throw runtime_error(
"importprivkey \"zcashprivkey\" ( \"label\" rescan )\n"
"importprivkey \"komodoprivkey\" ( \"label\" rescan )\n"
"\nAdds a private key (as returned by dumpprivkey) to your wallet.\n"
"\nArguments:\n"
"1. \"zcashprivkey\" (string, required) The private key (see dumpprivkey)\n"
"1. \"komodoprivkey\" (string, required) The private key (see dumpprivkey)\n"
"2. \"label\" (string, optional, default=\"\") An optional label\n"
"3. rescan (boolean, optional, default=true) Rescan the wallet for transactions\n"
"\nNote: This call can take minutes to complete if rescan is true.\n"
@ -152,7 +152,7 @@ UniValue importaddress(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 1 || params.size() > 3)
throw runtime_error(
"importaddress \"address\" ( \"label\" rescan )\n"
@ -248,7 +248,7 @@ UniValue importwallet(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() != 1)
throw runtime_error(
"importwallet \"filename\"\n"
@ -278,7 +278,7 @@ UniValue importwallet_impl(const UniValue& params, bool fHelp, bool fImportZKeys
if (!file.is_open())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file");
int64_t nTimeBegin = chainActive.Tip()->GetBlockTime();
int64_t nTimeBegin = chainActive.LastTip()->GetBlockTime();
bool fGood = true;
@ -364,7 +364,7 @@ UniValue importwallet_impl(const UniValue& params, bool fHelp, bool fImportZKeys
file.close();
pwalletMain->ShowProgress("", 100); // hide progress dialog in GUI
CBlockIndex *pindex = chainActive.Tip();
CBlockIndex *pindex = chainActive.LastTip();
while (pindex && pindex->pprev && pindex->GetBlockTime() > nTimeBegin - 7200)
pindex = pindex->pprev;
@ -385,14 +385,14 @@ UniValue dumpprivkey(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() != 1)
throw runtime_error(
"dumpprivkey \"zcashaddress\"\n"
"\nReveals the private key corresponding to 'zcashaddress'.\n"
"dumpprivkey \"komodoaddress\"\n"
"\nReveals the private key corresponding to 'komodoaddress'.\n"
"Then the importprivkey can be used with this output\n"
"\nArguments:\n"
"1. \"zcashaddress\" (string, required) The zcash address for the private key\n"
"1. \"komodoaddress\" (string, required) The komodo address for the private key\n"
"\nResult:\n"
"\"key\" (string) The private key\n"
"\nExamples:\n"
@ -424,13 +424,13 @@ UniValue z_exportwallet(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() != 1)
throw runtime_error(
"z_exportwallet \"filename\"\n"
"\nExports all wallet keys, for taddr and zaddr, in a human-readable format. Overwriting an existing file is not permitted.\n"
"\nArguments:\n"
"1. \"filename\" (string, required) The filename, saved in folder set by zcashd -exportdir option\n"
"1. \"filename\" (string, required) The filename, saved in folder set by komodod -exportdir option\n"
"\nResult:\n"
"\"path\" (string) The full path of the destination file\n"
"\nExamples:\n"
@ -451,7 +451,7 @@ UniValue dumpwallet(const UniValue& params, bool fHelp)
"dumpwallet \"filename\"\n"
"\nDumps taddr wallet keys in a human-readable format. Overwriting an existing file is not permitted.\n"
"\nArguments:\n"
"1. \"filename\" (string, required) The filename, saved in folder set by zcashd -exportdir option\n"
"1. \"filename\" (string, required) The filename, saved in folder set by komodod -exportdir option\n"
"\nResult:\n"
"\"path\" (string) The full path of the destination file\n"
"\nExamples:\n"
@ -475,7 +475,7 @@ UniValue dumpwallet_impl(const UniValue& params, bool fHelp, bool fDumpZKeys)
throw JSONRPCError(RPC_INTERNAL_ERROR, e.what());
}
if (exportdir.empty()) {
throw JSONRPCError(RPC_WALLET_ERROR, "Cannot export wallet until the zcashd -exportdir option has been set");
throw JSONRPCError(RPC_WALLET_ERROR, "Cannot export wallet until the komodod -exportdir option has been set");
}
std::string unclean = params[0].get_str();
std::string clean = SanitizeFilename(unclean);
@ -509,8 +509,8 @@ UniValue dumpwallet_impl(const UniValue& params, bool fHelp, bool fDumpZKeys)
// produce output
file << strprintf("# Wallet dump created by Komodo %s (%s)\n", CLIENT_BUILD, CLIENT_DATE);
file << strprintf("# * Created on %s\n", EncodeDumpTime(GetTime()));
file << strprintf("# * Best block at time of backup was %i (%s),\n", chainActive.Height(), chainActive.Tip()->GetBlockHash().ToString());
file << strprintf("# mined on %s\n", EncodeDumpTime(chainActive.Tip()->GetBlockTime()));
file << strprintf("# * Best block at time of backup was %i (%s),\n", chainActive.Height(), chainActive.LastTip()->GetBlockHash().ToString());
file << strprintf("# mined on %s\n", EncodeDumpTime(chainActive.LastTip()->GetBlockTime()));
file << "\n";
for (std::vector<std::pair<int64_t, CKeyID> >::const_iterator it = vKeyBirth.begin(); it != vKeyBirth.end(); it++) {
const CKeyID &keyid = it->second;

1216
src/wallet/rpcwallet.cpp

File diff suppressed because it is too large

49
src/wallet/wallet.cpp

@ -46,6 +46,7 @@ extern int32_t KOMODO_EXCHANGEWALLET;
extern char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN];
extern int32_t VERUS_MIN_STAKEAGE;
CBlockIndex *komodo_chainactive(int32_t height);
extern std::string DONATION_PUBKEY;
/**
* Fees smaller than this (in satoshi) are considered zero fee (for transaction creation)
@ -2044,7 +2045,7 @@ int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
double dProgressStart = Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex, false);
double dProgressTip = Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), chainActive.Tip(), false);
double dProgressTip = Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), chainActive.LastTip(), false);
while (pindex)
{
if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0)
@ -2110,10 +2111,17 @@ void CWallet::ReacceptWalletTransactions()
bool CWalletTx::RelayWalletTransaction()
{
if ( pwallet == 0 )
{
fprintf(stderr,"unexpected null pwallet in RelayWalletTransaction\n");
return(false);
}
assert(pwallet->GetBroadcastTransactions());
if (!IsCoinBase())
{
if (GetDepthInMainChain() == 0) {
if (GetDepthInMainChain() == 0)
{
// if tx is expired, dont relay
LogPrintf("Relaying wtx %s\n", GetHash().ToString());
RelayTransaction((CTransaction)*this);
return true;
@ -2326,19 +2334,31 @@ std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime)
LOCK(cs_wallet);
// Sort them in chronological order
multimap<unsigned int, CWalletTx*> mapSorted;
uint32_t now = (uint32_t)time(NULL);
BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
{
CWalletTx& wtx = item.second;
// Don't rebroadcast if newer than nTime:
if (wtx.nTimeReceived > nTime)
continue;
//if ( ASSETCHAINS_SYMBOL[0] == 0 )
{
if ( wtx.nLockTime >= LOCKTIME_THRESHOLD && wtx.nLockTime < now-KOMODO_MAXMEMPOOLTIME )
{
LogPrintf("skip Relaying wtx %s nLockTime %u vs now.%u\n", wtx.GetHash().ToString(),(uint32_t)wtx.nLockTime,now);
continue;
}
}
mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
}
BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
{
CWalletTx& wtx = *item.second;
if (wtx.RelayWalletTransaction())
result.push_back(wtx.GetHash());
if ( item.second != 0 )
{
CWalletTx &wtx = *item.second;
if (wtx.RelayWalletTransaction())
result.push_back(wtx.GetHash());
}
}
return result;
}
@ -2511,20 +2531,20 @@ void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const
if ( KOMODO_EXCHANGEWALLET == 0 )
{
uint32_t locktime; int32_t txheight; CBlockIndex *tipindex;
if ( ASSETCHAINS_SYMBOL[0] == 0 && chainActive.Tip() != 0 && chainActive.Tip()->nHeight >= 60000 )
if ( ASSETCHAINS_SYMBOL[0] == 0 && chainActive.LastTip() != 0 && chainActive.LastTip()->nHeight >= 60000 )
{
if ( pcoin->vout[i].nValue >= 10*COIN )
{
if ( (tipindex= chainActive.Tip()) != 0 )
if ( (tipindex= chainActive.LastTip()) != 0 )
{
komodo_accrued_interest(&txheight,&locktime,wtxid,i,0,pcoin->vout[i].nValue,(int32_t)tipindex->nHeight);
interest = komodo_interestnew(txheight,pcoin->vout[i].nValue,locktime,tipindex->nTime);
} else interest = 0;
//interest = komodo_interestnew(chainActive.Tip()->nHeight+1,pcoin->vout[i].nValue,pcoin->nLockTime,chainActive.Tip()->nTime);
//interest = komodo_interestnew(chainActive.LastTip()->nHeight+1,pcoin->vout[i].nValue,pcoin->nLockTime,chainActive.LastTip()->nTime);
if ( interest != 0 )
{
//printf("wallet nValueRet %.8f += interest %.8f ht.%d lock.%u/%u tip.%u\n",(double)pcoin->vout[i].nValue/COIN,(double)interest/COIN,txheight,locktime,pcoin->nLockTime,tipindex->nTime);
//fprintf(stderr,"wallet nValueRet %.8f += interest %.8f ht.%d lock.%u tip.%u\n",(double)pcoin->vout[i].nValue/COIN,(double)interest/COIN,chainActive.Tip()->nHeight+1,pcoin->nLockTime,chainActive.Tip()->nTime);
//fprintf(stderr,"wallet nValueRet %.8f += interest %.8f ht.%d lock.%u tip.%u\n",(double)pcoin->vout[i].nValue/COIN,(double)interest/COIN,chainActive.LastTip()->nHeight+1,pcoin->nLockTime,chainActive.LastTip()->nTime);
//ptr = (uint64_t *)&pcoin->vout[i].nValue;
//(*ptr) += interest;
ptr = (uint64_t *)&pcoin->vout[i].interest;
@ -2899,7 +2919,7 @@ bool CWallet::CreateTransaction(const vector<CRecipient>& vecSend, CWalletTx& wt
int nextBlockHeight = chainActive.Height() + 1;
CMutableTransaction txNew = CreateNewContextualCMutableTransaction(
Params().GetConsensus(), nextBlockHeight);
txNew.nLockTime = (uint32_t)chainActive.Tip()->nTime + 1; // set to a time close to now
txNew.nLockTime = (uint32_t)chainActive.LastTip()->nTime + 1; // set to a time close to now
// Activates after Overwinter network upgrade
// Set nExpiryHeight to expiryDelta (default 20) blocks past current block height
@ -3002,6 +3022,15 @@ bool CWallet::CreateTransaction(const vector<CRecipient>& vecSend, CWalletTx& wt
//fprintf(stderr,"KOMODO_EXCHANGEWALLET disable interest sum %.8f, interest2 %.8f\n",(double)interest/COIN,(double)interest2/COIN);
//interest = 0; // interest2 also
//}
if ( ASSETCHAINS_SYMBOL[0] == 0 && DONATION_PUBKEY.size() == 66 && interest2 > 5000 )
{
CScript scriptDonation = CScript() << ParseHex(DONATION_PUBKEY) << OP_CHECKSIG;
CTxOut newTxOut(interest2,scriptDonation);
int32_t nDonationPosRet = txNew.vout.size() - 1; // dont change first or last
vector<CTxOut>::iterator position = txNew.vout.begin()+nDonationPosRet;
txNew.vout.insert(position, newTxOut);
interest2 = 0;
}
CAmount nChange = (nValueIn - nValue + interest2);
//fprintf(stderr,"wallet change %.8f (%.8f - %.8f) interest2 %.8f total %.8f\n",(double)nChange/COIN,(double)nValueIn/COIN,(double)nValue/COIN,(double)interest2/COIN,(double)nTotalValue/COIN);
if (nSubtractFeeFromAmount == 0)

2
src/wallet/wallet.h

@ -992,9 +992,9 @@ public:
bool UpdateNullifierNoteMap();
void UpdateNullifierNoteMapWithTx(const CWalletTx& wtx);
bool AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet, CWalletDB* pwalletdb);
void EraseFromWallet(const uint256 &hash);
void SyncTransaction(const CTransaction& tx, const CBlock* pblock);
bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate);
void EraseFromWallet(const uint256 &hash);
void WitnessNoteCommitment(
std::vector<uint256> commitments,
std::vector<boost::optional<ZCIncrementalWitness>>& witnesses,

2
src/zcbenchmarks.cpp

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

2
toolchain-info.sh

@ -1,6 +1,6 @@
#!/bin/bash
tools=("gcc-5" "g++-5" "otool" "nm")
tools=("gcc-6" "g++-6" "otool" "nm")
echo "Platform: `uname -a`"
echo "-------------------------------------"

6
zcutil/build-mac.sh

@ -1,6 +1,6 @@
#!/bin/bash
export CC=gcc-5
export CXX=g++-5
export CC=gcc-6
export CXX=g++-6
export LIBTOOL=libtool
export AR=ar
export RANLIB=ranlib
@ -44,7 +44,7 @@ make "$@" -C ./depends/ V=1 NO_QT=1 NO_PROTON=1
./autogen.sh
CPPFLAGS="-I$PREFIX/include -arch x86_64" LDFLAGS="-L$PREFIX/lib -arch x86_64 -Wl,-no_pie" \
CXXFLAGS='-arch x86_64 -I/usr/local/Cellar/gcc5/5.4.0/include/c++/5.4.0 -I$PREFIX/include -fwrapv -fno-strict-aliasing -Werror -g -Wl,-undefined -Wl,dynamic_lookup' \
CXXFLAGS='-arch x86_64 -I/usr/local/Cellar/gcc\@6/6.4.0_2/include/c++/6.4.0/ -I$PREFIX/include -fwrapv -fno-strict-aliasing -Werror -g -Wl,-undefined -Wl,dynamic_lookup' \
./configure --prefix="${PREFIX}" --with-gui=no "$HARDENING_ARG" "$LCOV_ARG"
make "$@" V=1 NO_GTEST=1 STATIC=1

Loading…
Cancel
Save