Skip to content

Commit

Permalink
Spark integration (#1246)
Browse files Browse the repository at this point in the history
* Squash

* Replace coin cover sets with Merkle roots for transcript purposes

* Support multiple output coins in mint transactions

* Use aggregate Schnorr proofs for multiple-output mint transactions

* Add versioning to proving system transcript labels

* Refactoring mobile api for Lelantus

* Typo fixed

* Updating getanonymityset rpc to get part of the set

* Adding getfeerate rpc

* Parsing issue fixed

* Fixing typo in getfeerate rpc

* Adding getcoinsforrecovery rpc

* Including block hash into recovery rpc

* Fixed json creation in getcoinsforrecovery rpc

* Putting tx hash instead of block hash into coin list for recovery

* Pushing sets as vector of json files

* Fixed json creation

* Returning sets separately during restoration

* getanonymityset and getusedcoinserials rpc calls refactored

* Compilation fixed

* Fixed getusedcoinserials argument number bug

* Spark address/key serialization functions implemented

* CSparkWallet and mint db functions added

* Spark mint tx creation, GetAvailableSparkCoins() implemented

* Bind serial commitments to chain context

* Use default curve generator for spend component

* Completed merge

* Use default address when auto minting

* Adding domain separators when doing hashes

* Adding version and checksum in address serialization

* Saving serial_context into CSparkMintMeta

* Moving Spark related code into separate directory

* Spark state implemented

* More state functionality implemented

* Adding Spark state into mempool

* More spark state functionality implemented

* Embed KDF derived key size into hash instantiation

* Generalize range proofs to arbitrary set sizes

* WIP: spend verification batching

* Use a key-committing AEAD construction

* Use base64 to make transferred data smaller

* Spark balance proof fixed

* Index for mobile api optimized

* Adds an encoding method for address scrambling

* Fix a typo

* Switch from hex to `bech32m` encoding

* Add tests

* SpendTransaction refactored and added serialization for it

* Review comment applied and fixed a bug in mint generation

* Spark spend creation

* Spark spend verification

* More state functionality implemented and bug fixes

* Some bug fixes and cleanup

* Bug fixes and review comments resolved

* More review comments resolved

* Adding several rpc calls for spark

* Adding more rpc calls

* Failing unittests fixed

* Devnet Spark HF block

* Version bump

* LelantusToSpark function implemented

* Refactoring of file paths

* lelantustospark rpc name refactored

* Adding check to stop lelantus on consensus level

* Fixing bug resulting batch verification fail

* Minor fixes on lelantustospark rpc

* Use new thread to recognize spark mints/spends

* Recognizing spark mints and spends during wallet scan

* Wallet spark tx scanning

* Spark limits

* Version bump

* Review fixes (#1218)

Addresses issues FLS-01, FLS-02, FLS-03, FLS-07 from the HashCloak review.

* Fix minor corner case issue

* Review fixes

* Add spark fee into gettransaction rpc

* Fixing crashes on some platforms

* Rpc tests fixed

* Rpc tests fixed

* Adding RPC tests for Spark

* Crashing issue and failing tests fixed

* Fixing unstable unittest

* Fixed remining conflict

* Adding several more unitests

* Adding one more rpc test

* Keeping some additional data in block index for mobile/light wallet

* Memo encryption fixed and test added

* Keep additional mint data for Lelantus only when -mobile passed

* Spark mobile api

* Minor inprovements

* Adding more unitests

* Minor fixes

* Add one more unittest

* Detect zero challenges

* isAddressMine implemented

* Typo fix

* Script tests fixed

* Spark state reset in  tests

* isMine() fixed

* Spark tx index

* Rpc test fix and more

* Add mint limit in tx creation

* Devnet graceful period extended

* Remove mint limit

* Version bump

* Spend limits fixed

* Using json object instead of array

* A little cleanup

* Add subtractFeeFromAmount in spark mint creation

* Spend input number limit removed

* Offloaded signing (#1237)

* Use `SHA-512` for broader hash function support

* Use pre-hashed auxiliary data for binding hash

* Simplify binding hash

* Version bump

* Spark address prefix changed

* Compile error fixed

* GetChange for spark spend

* Rpc tests fixed

* Failing unitests fixed

* Rpc test failing

* Improve GetAvailableCredit performance

* Fixed undefined behavior and compilation for macOS

* Rebase finished

* Spend conflict issue fixed

* devnet restart

* Smarter change recognition scheme implemented

* Typo fixed

* LelantusToSpark fixed

* Added anonymize all rpc for spark

* fix spendspark corner case crash

* Fix one more minor bug in spark spend verification

* Add getMintAmount function

* Fix typo in automintspark RPC call (#1253)

* Possible fix for crash on windows

* Update Spark addresses in RPC help with new format (#1256)

* Wallet refactoring

* Abandon spark transactions

* Version bump

* Recognize incoming spark mint

* Batch verification fixed

* Recognize transparent output fixed

* Anonymity set size changed

* Testnet HF blocks set

* Typo fixed

* Lelantus graceful period check in rpc calls

* spendspark rpc refactored

* Help string updated

* Include spark balance into gettotalbalance rpc result

* Fix crash for Apple's recent compiler on ARM64

* Fix for compilation with recent Apple compiler

* rpc tests fixed

* getusedcoinserials fixed

* getusedcoinstags fixed

* Add spark mempool clear

* fix RPC syntax in help (#1289)

* Locked Wallet case covered

* french typo issue fixed (#1295)

* lelantus manual-anonymize page fixed (#1293)

* spark available balance included in getprivatebalance (#1296)

* Subtract fee issue fix

* Reverting commit ddb04d8

* Add a method to request wallet unlock.

* Drop buggy TableViewLastColumnResizingFixer class. bitcoin/bitcoin@fd725c2

* fix Transaction tab resize issue

* Fixing tx not mined issue

* switcher fix

* Making conditions look better

* Fix receive detail tab size issue (#1306)

* Fix receive detail tab size issue

* Fix receive detail tab size issue

* Spark IS fixed

* ZapSparkMints

* Test for Spark IS

* Fixed broken spark state (#1307)

* Fixed broken spark state when a block with more than one spark spend fails lTag check

* Stop CSparkState::AddSpend from throwing an exception

* Adding cover set  existance check

* Failing test fixed

---------

Co-authored-by: levonpetrosyan93 <[email protected]>

* Bumped spark start block numbers for mainnet

* Don't throw an exception in CSparkState::RemoveBlock

* QT: Transaction tab columns size fix (#1335)

* QT: Amount column size fix

* QT: Status column size fix

* Fixed crash when -mobile passed

* Unlock screen for spark first run

* Temporarily bypass check for walletpassphrase rpc

* Depends NO_WALLET=1 setting fix (#1321)

* Spend remaining sigma coins in lelantustospark rpc

* Fix removetxmempool rpc

* Fix help strings for mint/spendspark rpc calls

* Fix for #1328

* Integrate Spark into QT (#1263)

* integrate spark

* update default of Requested payments history, combine mintspark trans, update nTxFee

* update spark address book

* fix bug for spark address book

* add default spark address into spark address book

* update migrateLelantusToSpark

* fix spendspark crash

* update typo

* integrate Anonymize All

* merge remote branch firo

* fix migrateLelantusToSpark

* remove close X of the migrate dialog

* remove close X of the private dialog

* fix the migration issues

* fix the migration issues

* update for verifying migration

* update for verifying migration

* update calculating estimated fee of spendspark

* fix mintspark/spendspark from an another wallet

* fix crash if using the existing wallet

* fix bug 1282 & 1288

* Add output spark address & amount

* Merge remote-tracking branch 'firo/spark' into spark

* remove i

* remove addresstype

* fix edit spark label, size of address col in transaction history

* Version bump

* Fix Spark address view on recieverequestdialog

* Merge conflict fixed

* Review commit resolved

* Remove sensitive data from Coin

---------

Co-authored-by: levonpetrosyan93 <[email protected]>
Co-authored-by: levonpetrosyan93 <[email protected]>

* Build fixed

* RPC tests and more fixed

* Fix Github Actions (#1355)

* Disable building libconsensus for Windows in CI

* setuptools workaround for macOS

* Fixed QT crash on startup (#1312)

* Libspark fuzzing harness (#1340)

* Spark address/key serialization functions implemented

* CSparkWallet and mint db functions added

* Spark mint tx creation, GetAvailableSparkCoins() implemented

* Bind serial commitments to chain context

* Use default curve generator for spend component

* Completed merge

* Use default address when auto minting

* Adding domain separators when doing hashes

* Adding version and checksum in address serialization

* Saving serial_context into CSparkMintMeta

* Moving Spark related code into separate directory

* Embed KDF derived key size into hash instantiation

* Generalize range proofs to arbitrary set sizes

* Spark state implemented

* More state functionality implemented

* WIP: spend verification batching

* Adding Spark state into mempool

* Use a key-committing AEAD construction

* More spark state functionality implemented

* Spark balance proof fixed

* Adds an encoding method for address scrambling

* Switch from hex to `bech32m` encoding

* Add tests

* SpendTransaction refactored and added serialization for it

* Review comment applied and fixed a bug in mint generation

* Spark spend creation

* Spark spend verification

* More state functionality implemented and bug fixes

* Some bug fixes and cleanup

* Bug fixes and review comments resolved

* More review comments resolved

* Adding several rpc calls for spark

* Adding more rpc calls

* Failing unittests fixed

* Version bump

* Devnet Spark HF block

* Added fuzz folder for persistent fuzzing libspark fuzzing

* bech32 fuzzing harness for honggfuzz added

* fix bech32_fuzz.cpp

* Added f4grumble fuzzing harness

* Forgot to add return statement to f4grumble_fuzz.cpp

* Moved libspark related fuzzing to its own folder

* Added FuzzedDataProvider.h

* Integrated FuzzedDataProvider.h in bech32_fuzz.cpp

* Fixed fuzzing enum in bech32_fuzz.cpp

* missing semicolon

* Added fuzz folder for persistent fuzzing libspark fuzzing

bech32 fuzzing harness for honggfuzz added

Added f4grumble fuzzing harness

Revert "missing semicolon"

This reverts commit 330cff6.

Fuzzing directory cleanup

Added FuzzedDataProvider.h

* Added fuzzing utilities for group elements and scalars

* Added fuzzing for aead.cpp

* Added vector versions of GetGroupElement and GetScalar in fuzzing_utilities.cpp

* Added single proof fuzz test for bpplus_fuzz

* LelantusToSpark function implemented

* Refactoring of file paths

* lelantustospark rpc name refactored

* Adding check to stop lelantus on consensus level

* Added fuzz folder for persistent fuzzing libspark fuzzing

bech32 fuzzing harness for honggfuzz added

Added f4grumble fuzzing harness

Revert "missing semicolon"

This reverts commit 330cff6.

Fuzzing directory cleanup

Added FuzzedDataProvider.h

* Added fuzzing utilities for group elements and scalars

* Added fuzzing for aead.cpp

* Added vector versions of GetGroupElement and GetScalar in fuzzing_utilities.cpp

* Added single proof fuzz test for bpplus_fuzz

* Changed relative paths of dependencies in secp256k1/src/cpp

* More relative path changes in src/secp256k1

* Changed relative paths in crypto/common.h

* Removed FuzzedSecp256k1Object deconstructor

* Addedd aead_fuzz.cpp and other utilities

Adding check to stop lelantus on consensus level

Added fuzz folder for persistent fuzzing libspark fuzzing

bech32 fuzzing harness for honggfuzz added

Added f4grumble fuzzing harness

Revert "missing semicolon"

This reverts commit 330cff6.

Fuzzing directory cleanup

Added FuzzedDataProvider.h

Added fuzzing utilities for group elements and scalars

Added fuzzing for aead.cpp

* Added vector versions of GetGroupElement and GetScalar in fuzzing_utilities.cpp

* Added single proof fuzz test for bpplus_fuzz

* Changed relative paths of dependencies in secp256k1/src/cpp

* More relative path changes in src/secp256k1

* Changed relative paths in crypto/common.h

* Removed FuzzedSecp256k1Object deconstructor

* Added batch bpplus proofs fuzzing tests

* Changed relative paths in libspark/params.h

* Fixed errors in bpplus_fuzz.cpp

* Fixed more errors

* More fixes in bpplus.cpp

* Completed bpplus_fuzz tests

Added batch bpplus proofs fuzzing tests

Changed relative paths in libspark/params.h

Fixed errors in bpplus_fuzz.cpp

Fixed more errors

More fixes in bpplus.cpp

Changed type of sizes in bpplus_fuzz.cpp

* Added chaum_fuzz.cpp

* Changed relative paths in src/wallet/crypter.h

* Changed relative path in arith_uint256.h

exit

* Completed chaum fuzz tests

Added chaum_fuzz.cpp

Changed relative paths in src/wallet/crypter.h

Changed relative path in arith_uint256.h

exit

* Added schnorr_fuzz.cpp

* Addedd grootle_fuzz.cpp

* Added length to ConsumeBytes call

* Initialized sizes vector via a loop in grootle_fuzz.cpp

* Changed relative paths in support/allocator/secure.h

* Changed relative paths in support/allocator/secure.h again

* Added mint_transaction_fuzz.cpp

* Changed type of parameter in MintTransaction in mint_transaction_fuzz.cpp

* Changed relative path in params.cpp

* Changed relative paths in consensus/params.h

* Changed relative paths in primitives/block.h

* Changed relative paths in primitives/transaction.h

* Changed relative paths in src/script/script.h

* Changed more relative paths in src/script/script.h

* Changed relative paths in crypto/MerkleTreeProof/mtp.h

* Changed relative paths in crypto/MerkleTreeProof/mtp.h. Actually this time.

* Changed relative paths in crypto/progpow.h

* Completed mint_transaction_fuzz.cpp

Added mint_transaction_fuzz.cpp

Changed type of parameter in MintTransaction in mint_transaction_fuzz.cpp

Changed relative path in params.cpp

Changed relative paths in consensus/params.h

Changed relative paths in primitives/block.h

Changed relative paths in primitives/transaction.h

Changed relative paths in src/script/script.h

Changed more relative paths in src/script/script.h

Changed relative paths in crypto/MerkleTreeProof/mtp.h

Changed relative paths in crypto/MerkleTreeProof/mtp.h. Actually this time.

Changed relative paths in crypto/progpow.h

* Added spend_transaction_fuzz.cpp

* Fixed errors in spend_transaction_fuzz.cpp

* Completed spend_transaction_fuzz.cpp

Added spend_transaction_fuzz.cpp

Fixed errors in spend_transaction_fuzz.cpp

* Updated relative paths in MultiExponent.cpp

* fuzzing and coverage of different libspark files

* makefile and code-coverage for libspark

* spend transaction modified

* coverage, input, results removed

* empty and temporary files deleted

* empty files removed

* readme for fuzzing modified

* original paths restored and conflict resolved, flags added in fuzz makefile

* path fixed and merged latest spark

* path fixed

* instructions for installing dependencies added in fuzz readme

* binary removed and loop length resized

* readme modified & vetor size reserved in fuzzing_utilities

---------

Co-authored-by: levonpetrosyan93 <[email protected]>
Co-authored-by: Aaron Feickert <[email protected]>
Co-authored-by: Mikerah <[email protected]>
Co-authored-by: Onur İnanç <[email protected]>
Co-authored-by: HashCloak <[email protected]>

* Fix getsparkanonymityset

* Fix second anonymity set bug

* Detect zero challenges in schnorr

* Verion bump

* Fix rpc help strings

* Spark mainnet HF blocks set

* Extended spork support for 1 more year

* Set lelantus graceful period 2 years

---------

Co-authored-by: Aaron Feickert <[email protected]>
Co-authored-by: Peter Shugalev <[email protected]>
Co-authored-by: justanwar <[email protected]>
Co-authored-by: levoncrypto <[email protected]>
Co-authored-by: sproxet <[email protected]>
Co-authored-by: [email protected] <[email protected]>
Co-authored-by: giangnamnabka <[email protected]>
Co-authored-by: Manish Kumar <[email protected]>
Co-authored-by: Mikerah <[email protected]>
Co-authored-by: Onur İnanç <[email protected]>
Co-authored-by: HashCloak <[email protected]>
  • Loading branch information
12 people authored Nov 21, 2023
1 parent 2467c94 commit 0579884
Show file tree
Hide file tree
Showing 222 changed files with 20,599 additions and 991 deletions.
30 changes: 25 additions & 5 deletions configure.ac
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ AC_PREREQ([2.60])
define(_CLIENT_VERSION_MAJOR, 0)
define(_CLIENT_VERSION_MINOR, 14)
define(_CLIENT_VERSION_REVISION, 12)
define(_CLIENT_VERSION_BUILD, 1)
define(_CLIENT_VERSION_BUILD, 6)
define(_CLIENT_VERSION_IS_RELEASE, true)
define(_COPYRIGHT_YEAR, 2023)
define(_COPYRIGHT_HOLDERS,[The %s developers])
Expand Down Expand Up @@ -92,7 +92,18 @@ AC_PATH_TOOL(OBJCOPY, objcopy)
AC_ARG_VAR(PYTHONPATH, Augments the default search path for python module files)

# Enable wallet
enable_wallet=yes
AC_ARG_ENABLE([wallet],
[AS_HELP_STRING([--disable-wallet],
[disable wallet (enabled by default)])],
[enable_wallet=$enableval],
[enable_wallet=yes])

AC_ARG_WITH([bdb],
[AS_HELP_STRING([--without-bdb],
[disable bdb wallet support (default is enabled if wallet is enabled)])],
[use_bdb=$withval],
[use_bdb=auto])


AC_ARG_ENABLE([elysium],
[AS_HELP_STRING([--enable-elysium],[enable elysium (disabled by default)])],
Expand Down Expand Up @@ -651,9 +662,11 @@ AC_SUBST(LEVELDB_CPPFLAGS)
AC_SUBST(LIBLEVELDB)
AC_SUBST(LIBMEMENV)

if test x$enable_wallet != xno; then
dnl Check for libdb_cxx only if wallet enabled
BITCOIN_FIND_BDB48
if test "$enable_wallet" != "no"; then
dnl Check for libdb_cxx only if wallet enabled
if test "$use_bdb" != "no"; then
BITCOIN_FIND_BDB48
fi
fi

dnl Check for libminiupnpc (optional)
Expand Down Expand Up @@ -1168,6 +1181,7 @@ AM_CONDITIONAL([USE_LCOV],[test x$use_lcov = xyes])
AM_CONDITIONAL([GLIBC_BACK_COMPAT],[test x$use_glibc_compat = xyes])
AM_CONDITIONAL([HARDEN],[test x$use_hardening = xyes])
AM_CONDITIONAL([ENABLE_SSE42],[test x$enable_sse42 = xyes])
AM_CONDITIONAL([USE_BDB], [test "$use_bdb" = "yes"])

AC_DEFINE(CLIENT_VERSION_MAJOR, _CLIENT_VERSION_MAJOR, [Major version])
AC_DEFINE(CLIENT_VERSION_MINOR, _CLIENT_VERSION_MINOR, [Minor version])
Expand Down Expand Up @@ -1222,6 +1236,7 @@ AC_SUBST(ZMQ_LIBS)
AC_SUBST(PROTOBUF_LIBS)
AC_SUBST(QR_LIBS)
AC_SUBST(DSYMUTIL_FLAT)
AC_SUBST(USE_BDB)
AC_CONFIG_FILES([Makefile src/Makefile share/setup.nsi share/qt/Info.plist src/test/buildenv.py])
AC_CONFIG_FILES([qa/pull-tester/tests_config.py],[chmod +x qa/pull-tester/tests_config.py])
AC_CONFIG_FILES([contrib/devtools/split-debug.sh],[chmod +x contrib/devtools/split-debug.sh])
Expand Down Expand Up @@ -1291,6 +1306,11 @@ if test x$bitcoin_enable_qt != xno; then
echo " qt version = $bitcoin_qt_got_major_vers"
echo " with qr = $use_qr"
fi

if test "$enable_wallet" != "no"; then
echo " with bdb = $use_bdb"
fi

echo " with zmq = $use_zmq"
echo " with test = $use_tests"
echo " with bench = $use_bench"
Expand Down
3 changes: 3 additions & 0 deletions qa/pull-tester/rpc-tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,9 @@
raise

testScripts = [
'spark_mint.py',
'spark_spend_gettransaction.py',
'spark_setmintstatus_validation.py',
'lelantus_mint.py',
'lelantus_setmintstatus_validation.py',
'lelantus_mintspend.py',
Expand Down
2 changes: 1 addition & 1 deletion qa/rpc-tests/bip47-sendreceive.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def setup_network(self, split=False):

def run_test(self):

self.nodes[1].generate(1010)
self.nodes[1].generate(410)
node0_pcode = self.nodes[0].createrapaddress("node0-pcode0")

try:
Expand Down
2 changes: 1 addition & 1 deletion qa/rpc-tests/lelantus_mint.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ def run_test(self):

assert_raises_message(
JSONRPCException,
"Lelantus is not activated yet",
"Lelantus is not active",
self.nodes[0].mintlelantus, 1)

self.nodes[0].generate(activation_block - self.nodes[0].getblockcount())
Expand Down
2 changes: 1 addition & 1 deletion qa/rpc-tests/lelantus_mintspend.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ def __init__(self):
def run_test(self):
# Decimal formating: 6 digits for balance will be enought 000.000
getcontext().prec = 6
self.nodes[0].generate(401)
self.nodes[0].generate(201)
self.sync_all()

start_bal = self.nodes[0].getbalance()
Expand Down
2 changes: 1 addition & 1 deletion qa/rpc-tests/llmq-cl-evospork.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def run_test(self):
self.nodes[0].sendtoaddress(self.payment_address, 1)

# mine many blocks, wait for chainlock
while self.nodes[0].getblockcount() < 1000:
while self.nodes[0].getblockcount() < 800:
self.nodes[0].generate(20)
self.wait_for_chainlock_tip_all_nodes()

Expand Down
2 changes: 1 addition & 1 deletion qa/rpc-tests/llmq-is-lelantus.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def run_test(self):
self.mine_quorum()
self.wait_for_chainlocked_block_all_nodes(self.nodes[0].getbestblockhash())

self.nodes[0].generate(1000 - self.nodes[0].getblockcount())
self.nodes[0].generate(401 - self.nodes[0].getblockcount())
for i in range(0, 3):
mintTxids = self.nodes[0].mintlelantus(1)

Expand Down
58 changes: 58 additions & 0 deletions qa/rpc-tests/llmq-is-spark.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
#!/usr/bin/env python3
# Copyright (c) 2015-2018 The Dash Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.

from test_framework.mininode import *
from test_framework.test_framework import EvoZnodeTestFramework
from test_framework.util import sync_blocks, set_node_times, \
isolate_node, reconnect_isolated_node, set_mocktime, get_mocktime
from test_framework.util import assert_equal, assert_raises_jsonrpc, \
bitcoind_processes, start_nodes, start_node, connect_nodes_bi

from decimal import Decimal

'''
llmq-is-spark.py
Testing Instantsend for Spark transactions
'''

class LLMQ_IS_Lelantus(EvoZnodeTestFramework):
def __init__(self):
super().__init__(6, 5, extra_args=[['-debug=instantsend']] * 6 )
self.sporkprivkey = "cW2YM2xaeCaebfpKguBahUAgEzLXgSserWRuD29kSyKHq1TTgwRQ"

def run_test(self):
self.sporkAddress = self.nodes[0].getaccountaddress("")
self.mine_quorum()
self.wait_for_chainlocked_block_all_nodes(self.nodes[0].getbestblockhash())

self.nodes[0].generate(1001 - self.nodes[0].getblockcount())

sparkaddress = self.nodes[0].getnewsparkaddress()[0]
for i in range(0, 3):
mintTxids = self.nodes[0].mintspark({sparkaddress: {"amount": 1, "memo":"Test memo"}})

for mintTxid in mintTxids:
mintTx = self.nodes[0].getrawtransaction(mintTxid, 1)
val = 0
for vi in mintTx['vin']:
val += vi['valueSat']
if val > 10000:
break;
val = Decimal((val - 10000) / 1e+8).quantize(Decimal('1e-7'))

assert(self.wait_for_instantlock(mintTxid, self.nodes[0]))

mintDspend = self.nodes[0].createrawtransaction(mintTx['vin'], {self.nodes[0].getnewaddress(): str(val)})
assert_raises_jsonrpc(-26, 'tx-txlock-conflict', self.nodes[0].sendrawtransaction, mintDspend)

self.nodes[0].generate(3)
assert (self.nodes[0].getrawtransaction(mintTxid, True)['confirmations'] > 0)

spendTxid = self.nodes[0].spendspark({self.sporkAddress: {"amount": 0.1, "subtractFee": False}})
assert(self.wait_for_instantlock(spendTxid, self.nodes[0]))

if __name__ == '__main__':
LLMQ_IS_Lelantus().main()
83 changes: 83 additions & 0 deletions qa/rpc-tests/spark_mint.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
#!/usr/bin/env python3
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import assert_equal, assert_raises_message, JSONRPCException

class SparkMintTest(BitcoinTestFramework):
def __init__(self):
super().__init__()
self.num_nodes = 1
self.setup_clean_chain = False

def run_test(self):
assert_raises_message(
JSONRPCException,
"Spark is not activated yet",
self.nodes[0].mintspark, 1)

self.nodes[0].generate(1001)

# generate coins
amounts = [1, 1.1, 2, 10]

# 10 confirmations
address = self.nodes[0].getnewsparkaddress()[0]
self.nodes[0].mintspark({address: {"amount": amounts[0], "memo":"Test memo"}})
self.nodes[0].mintspark({address: {"amount": amounts[1], "memo": "Test memo"}})
self.nodes[0].generate(5)

# 5 confirmations
self.nodes[0].mintspark({address: {"amount": amounts[2], "memo": "Test memo"}})
self.nodes[0].mintspark({address: {"amount": amounts[3], "memo": "Test memo"}})
self.nodes[0].generate(5)

# get all mints and utxos
mints = self.verify_listsparkmints(amounts)
self.verify_listunspentsparkmints(amounts)
assert_equal([False, False, False, False], list(map(lambda m : m["isUsed"], mints)))

# state modification test
# mark two coins as used
self.nodes[0].setsparkmintstatus(mints[2]["lTagHash"], True)
self.nodes[0].setsparkmintstatus(mints[3]["lTagHash"], True)

mints = self.verify_listsparkmints(amounts)
self.verify_listunspentsparkmints([1, 1.1])
assert_equal([False, False, True, True], list(map(lambda m : m["isUsed"], mints)))

# set a coin as unused
self.nodes[0].setsparkmintstatus(mints[3]["lTagHash"], False)
mints = self.verify_listsparkmints(amounts)
self.verify_listunspentsparkmints([1, 1.1, 10])
assert_equal([False, False, True, False], list(map(lambda m : m["isUsed"], mints)))

self.nodes[0].setsparkmintstatus(mints[0]["lTagHash"], False)
self.nodes[0].setsparkmintstatus(mints[1]["lTagHash"], False)
self.nodes[0].setsparkmintstatus(mints[2]["lTagHash"], False)
self.nodes[0].setsparkmintstatus(mints[3]["lTagHash"], False)

mints = self.verify_listsparkmints(amounts)
self.verify_listunspentsparkmints(amounts)
assert_equal([False, False, False, False], list(map(lambda m : m["isUsed"], mints)))

def verify_listsparkmints(self, expected_amounts):
mints = self.nodes[0].listsparkmints()
mints = sorted(mints, key = lambda u: u['amount'])

assert_equal(
sorted(expected_amounts),
list(map(lambda u: float(u['amount']), mints)))

return mints

def verify_listunspentsparkmints(self, expected_amounts):
mints = self.nodes[0].listunspentsparkmints()
mints = sorted(mints, key = lambda u: float(u['amount']))

assert_equal(
sorted(expected_amounts),
list(map(lambda u: float(u['amount']), mints)))

return mints

if __name__ == '__main__':
SparkMintTest().main()
123 changes: 123 additions & 0 deletions qa/rpc-tests/spark_mintspend.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
#!/usr/bin/env python3
from decimal import *

from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
from time import *

class SparkMintSpendTest(BitcoinTestFramework):
def __init__(self):
super().__init__()
self.num_nodes = 4
self.setup_clean_chain = False

def run_test(self):
# Decimal formating: 6 digits for balance will be enought 000.000
getcontext().prec = 6
self.nodes[0].generate(801)
self.sync_all()

start_bal = self.nodes[0].getbalance()

sparkAddress = self.nodes[0].getsparkdefaultaddress()[0]

mint_trans = list()
mint_trans.append(self.nodes[0].mintspark({sparkAddress: {"amount": 1, "memo": "Test memo"}}))
mint_trans.append(self.nodes[0].mintspark({sparkAddress: {"amount": 2, "memo":"Test memo"}}))

# Get last added transaction and fee for it
info = self.nodes[0].gettransaction(mint_trans[-1][0])

# fee in transaction is negative
fee = -(info['fee'] * 2)
cur_bal = self.nodes[0].getbalance()
start_bal = float(start_bal) - float(fee) - 3
start_bal = Decimal(format(start_bal, '.8f'))

assert start_bal == cur_bal, \
'Unexpected current balance: {}, should be minus two mints and two fee, ' \
'but start was {}'.format(cur_bal, start_bal)

for tr in mint_trans:
info = self.nodes[0].gettransaction(tr[0])
confrms = info['confirmations']
assert confrms == 0, \
'Confirmations should be {}, ' \
'due to {} blocks was generated after transaction was created,' \
'but was {}'.format(0, 0, confrms)

tr_type = info['details'][0]['category']
assert tr_type == 'mint', 'Unexpected transaction type: {}'.format(tr_type)
# assert(self.wait_for_instantlock(tr, self.nodes[0]))

self.nodes[0].generate(1)
self.sync_all()

res = False
firoAddress = self.nodes[0].getnewaddress()
try:
res = self.nodes[0].spendspark({firoAddress: {"amount": 1, "subtractFee": False}}, {})
except JSONRPCException as ex:
assert ex.error['message'] == 'Spark spend creation failed.'

assert not res, 'Did not raise spend exception, but should be.'

# generate last confirmation block - now all transactions should be confimed
self.nodes[0].generate(1)
self.sync_all()

for tr in mint_trans:
info = self.nodes[0].gettransaction(tr[0])
confrms = info['confirmations']
assert confrms >= 1, \
'Confirmations should be 3, ' \
'due to 3 blocks was generated after transaction was created,' \
'but was {}.'.format(confrms)
tr_type = info['details'][0]['category']
assert tr_type == 'mint', 'Unexpected transaction type'

spend_trans = list()
spend_total = Decimal(0)

self.sync_all()

spend_trans.append(self.nodes[0].spendspark({firoAddress: {"amount": 1, "subtractFee": False}}, {}))

info = self.nodes[0].gettransaction(spend_trans[-1])
confrms = info['confirmations']
tr_type = info['details'][0]['category']

assert confrms == 0, \
'Confirmations should be 0, ' \
'due to 0 blocks was generated after transaction was created,' \
'but was {}.'.format(confrms)

assert tr_type == 'spend', 'Unexpected transaction type'

before_bal = self.nodes[0].getbalance()
self.nodes[0].generate(2)
self.sync_all()
after_new = self.nodes[0].getbalance()
delta = after_new - before_bal
start_bal = before_bal + delta
cur_bal = Decimal(format(self.nodes[0].getbalance(), '.1f'))
spend_total = Decimal(format(1, '.8f'))

assert start_bal == cur_bal, \
'Unexpected current balance: {}, should increase on {}, ' \
'but start was {}'.format(cur_bal, spend_total, start_bal)

for tr in spend_trans:
info = self.nodes[0].gettransaction(tr)

confrms = info['confirmations']
tr_type = info['details'][0]['category']
assert confrms >= 1, \
'Confirmations should be 1 or more, ' \
'due to 1 blocks was generated after transaction was created,' \
'but was {}.'.format(confrms)
assert tr_type == 'spend', 'Unexpected transaction type'


if __name__ == '__main__':
SparkMintSpendTest().main()
Loading

0 comments on commit 0579884

Please sign in to comment.