Commit Graph

2924 Commits

Author SHA1 Message Date
Conrado Gouvea 94175c6955
Add ZIP-221 history tree to non-finalized state (#2583)
* Refactor HistoryTree into NonEmptyHistoryTree and HistoryTree

* HistoryTree: use Deref instead of AsRef; remove unneeded PartialEq

* ZIP-221: Validate chain history commitments in the non-finalized state (#2301)

* sketch of implementation

* refined implementation; still incomplete

* update librustzcash, change zcash_history to work with it

* simplified code per review; renamed MMR to HistoryTree

* expand HistoryTree implementation

* handle and propagate errors

* simplify check.rs tracing

* add suggested TODO

* add HistoryTree::prune

* fix bug in pruning

* fix compilation of tests; still need to make them pass

* Apply suggestions from code review

Co-authored-by: teor <teor@riseup.net>

* Apply suggestions from code review

Co-authored-by: teor <teor@riseup.net>

* improvements from code review

* improve check.rs comments and variable names

* fix HistoryTree which should use BTreeMap and not HashMap; fix non_finalized_state prop tests

* fix finalized_state proptest

* fix non_finalized_state tests by setting the correct commitments

* renamed mmr.rs to history_tree.rs

* Add HistoryTree struct

* expand non_finalized_state protest

* fix typo

* Add HistoryTree struct

* Update zebra-chain/src/primitives/zcash_history.rs

Co-authored-by: Deirdre Connolly <deirdre@zfnd.org>

* fix formatting

* Apply suggestions from code review

Co-authored-by: Deirdre Connolly <deirdre@zfnd.org>

* history_tree.rs: fixes from code review

* fixes to work with updated HistoryTree

* Improvements from code review

* Add Debug implementations to allow comparing Chains with proptest_assert_eq

Co-authored-by: teor <teor@riseup.net>
Co-authored-by: Deirdre Connolly <deirdre@zfnd.org>

* Apply suggestions from code review

Co-authored-by: teor <teor@riseup.net>

* Improvements from code review

* Restore blocks returned by PreparedChain since other tests broken; adjust tests with history trees

Co-authored-by: teor <teor@riseup.net>
Co-authored-by: Deirdre Connolly <deirdre@zfnd.org>
2021-08-11 10:42:40 -03:00
teor 298ececabe
Refactor value balances to support generated data modification (#2596)
Co-authored-by: Alfredo Garcia <oxarbitrage@gmail.com>
2021-08-10 14:42:02 +00:00
Conrado Gouvea eac95bdf10
Cache note commitment tree roots (#2584)
* Cache note commitment tree roots

* Add comments to cached root fields

* Apply suggestions from code review

Co-authored-by: teor <teor@riseup.net>

Co-authored-by: teor <teor@riseup.net>
2021-08-10 10:33:34 -03:00
Conrado Gouvea 9fc49827d6
Refactor HistoryTree into NonEmptyHistoryTree and HistoryTree (#2582)
* Refactor HistoryTree into NonEmptyHistoryTree and HistoryTree

* HistoryTree: use Deref instead of AsRef; remove unneeded PartialEq
2021-08-10 09:51:50 -03:00
teor f09f2a9022
Check remaining transaction value & make value balance signs match the spec (#2566)
* Make Amount arithmetic more generic

To modify generated amounts, we need some extra operations on `Amount`.

We also need to extend existing operations to both `NonNegative` and
`NegativeAllowed` amounts.

* Add a constrain method for ValueBalance

* Derive Eq for ValueBalance

* impl Neg for ValueBalance

* Make some Amount arithmetic expectations explicit

* Explain why we use i128 for multiplication

And expand the overflow error details.

* Expand Amount::sum error details

* Make amount::Error field order consistent

* Rename an amount::Error variant to Constraint, so it's clearer

* Add specific pool variants to ValueBalanceError

* Update coinbase remaining value consensus rule comment

This consensus rule was updated recently to include coinbase transactions,
but Zebra doesn't check block subsidy or miner fees yet.

* Add test methods for modifying transparent values and shielded value balances

* Temporarily set values and value balances to zero in proptests

In both generated chains and proptests that construct their own transactions.

Using zero values reduces value calculation and value check test coverage.
A future change will use non-zero values, and fix them so the check passes.

* Add extra fields to remaining transaction value errors

* Swap the transparent value balance sign to match shielded value balances

This makes the signs of all the chain value pools consistent.

* Use a NonNegative constraint for transparent values

This fix:
* makes the type signature match the consensus rules
* avoids having to write code to handle negative values

* Allocate total generated transaction input value to outputs

If there isn't enough input value for an output, set it to zero.

Temporarily reduce all generated values to avoid overflow.
(We'll remove this workaround when we calculate chain value balances.)

* Consistently use ValueBalanceError for ValueBalances

* Make the value balance signs match the spec

And rename and document methods so their signs are clearer.

* Convert amount::Errors to specific pool ValueBalanceErrors

* Move some error changes to the next PR

* Add extra info to remaining transaction value errors (#2585)

* Distinguish between overflow and negative remaining transaction value errors

And make some error types cloneable.

* Add methods for updating chain value pools (#2586)

* Move amount::test to amount::tests:vectors

* Make ValueBalance traits more consistent with Amount

- implement Add and Sub variants with Result and Assign
- derive Hash

* Clarify some comments and expects

* Create ValueBalance update methods for blocks and transactions

Co-authored-by: Alfredo Garcia <oxarbitrage@gmail.com>
2021-08-09 14:22:26 -03:00
teor fc68240fa0
Add extra arithmetic operations and error details to Amount and ValueBalance (#2577)
* Make Amount arithmetic more generic

To modify generated amounts, we need some extra operations on `Amount`.

We also need to extend existing operations to both `NonNegative` and
`NegativeAllowed` amounts.

* Add a constrain method for ValueBalance

* Derive Eq for ValueBalance

* impl Neg for ValueBalance

* Make some Amount arithmetic expectations explicit

* Explain why we use i128 for multiplication

And expand the overflow error details.

* Expand Amount::sum error details

* Make amount::Error field order consistent

* Rename an amount::Error variant to Constraint, so it's clearer

* Add specific pool variants to ValueBalanceError
2021-08-09 10:13:27 -03:00
Alfredo Garcia 910f0ff5dc
Add Chain ValueBalance serialization (#2554)
* add serialization for value balances

* change test names

* change panic messages

* add a deserialization test

* return the errors from `from_bytes()` methods

* add prop test for serialize/deserialize Amount

* Move amount proptests to amount::tests::prop

Co-authored-by: teor <teor@riseup.net>
2021-08-09 11:22:27 +10:00
Janito Vaqueiro Ferreira Filho 4c4dbfe7cd
Reject connections from outdated peers (#2519)
* Simplify state service initialization in test

Use the test helper function to remove redundant code.

* Create `BestTipHeight` helper type

This type abstracts away the calculation of the best tip height based on
the finalized block height and the best non-finalized chain's tip.

* Add `best_tip_height` field to `StateService`

The receiver endpoint is currently ignored.

* Return receiver endpoint from service constructor

Make it available so that the best tip height can be watched.

* Update finalized height after finalizing blocks

After blocks from the queue are finalized and committed to disk, update
the finalized block height.

* Update best non-finalized height after validation

Update the value of the best non-finalized chain tip block height after
a new block is committed to the non-finalized state.

* Update finalized height after loading from disk

When `FinalizedState` is first created, it loads the state from
persistent storage, and the finalized tip height is updated. Therefore,
the `best_tip_height` must be notified of the initial value.

* Update the finalized height on checkpoint commit

When a checkpointed block is commited, it bypasses the non-finalized
state, so there's an extra place where the finalized height has to be
updated.

* Add `best_tip_height` to `Handshake` service

It can be configured using the `Builder::with_best_tip_height`. It's
currently not used, but it will be used to determine if a connection to
a remote peer should be rejected or not based on that peer's protocol
version.

* Require best tip height to init. `zebra_network`

Without it the handshake service can't properly enforce the minimum
network protocol version from peers. Zebrad obtains the best tip height
endpoint from `zebra_state`, and the test vectors simply use a dummy
endpoint that's fixed at the genesis height.

* Pass `best_tip_height` to proto. ver. negotiation

The protocol version negotiation code will reject connections to peers
if they are using an old protocol version. An old version is determined
based on the current known best chain tip height.

* Handle an optional height in `Version`

Fallback to the genesis height in `None` is specified.

* Reject connections to peers on old proto. versions

Avoid connecting to peers that are on protocol versions that don't
recognize a network update.

* Document why peers on old versions are rejected

Describe why it's a security issue above the check.

* Test if `BestTipHeight` starts with `None`

Check if initially there is no best tip height.

* Test if best tip height is max. of latest values

After applying a list of random updates where each one either sets the
finalized height or the non-finalized height, check that the best tip
height is the maximum of the most recently set finalized height and the
most recently set non-finalized height.

* Add `queue_and_commit_finalized` method

A small refactor to make testing easier. The handling of requests for
committing non-finalized and finalized blocks is now more consistent.

* Add `assert_block_can_be_validated` helper

Refactor to move into a separate method some assertions that are done
before a block is validated. This is to allow moving these assertions
more easily to simplify testing.

* Remove redundant PoW block assertion

It's also checked in
`zebra_state::service::check::block_is_contextually_valid`, and it was
getting in the way of tests that received a gossiped block before
finalizing enough blocks.

* Create a test strategy for test vector chain

Splits a chain loaded from the test vectors in two parts, containing the
blocks to finalize and the blocks to keep in the non-finalized state.

* Test committing blocks update best tip height

Create a mock blockchain state, with a chain of finalized blocks and a
chain of non-finalized blocks. Commit all the blocks appropriately, and
verify that the best tip height is updated.

Co-authored-by: teor <teor@riseup.net>
2021-08-08 23:52:52 +00:00
Alfredo Garcia 751185d4ec
Use the same value balance sign for transparent and shielded outputs (#2569)
* change signs

* make impl of Neg generic

* change implementation of Neg for Amount

Co-authored-by: teor <teor@riseup.net>
2021-08-08 22:41:34 +00:00
teor 8f4c3b09ea
Add test methods for modifying orchard shielded data and joinsplits (#2580)
Co-authored-by: Alfredo Garcia <oxarbitrage@gmail.com>
2021-08-07 13:23:32 +00:00
teor a1cec27871
Update the signs in the value pools design to match the spec (#2576)
* Update the signs in the value pools design to match the spec

Also split the definitions and guide sections into transaction value balances
and chain value pools. And explain the sign differences between them in terms of
inputs and outputs.

* fix typo

Co-authored-by: Alfredo Garcia <oxarbitrage@gmail.com>
2021-08-06 22:00:02 +00:00
teor faae1c08bf
Stop using prop_filter_map to produce valid sapling shielded data (#2579)
This improves proptest results in CI and locally.

Proptests should be faster, because they are not discarding 1/16 results.

Failures should be minimised more often, improving failure logs,
and generating proptest seeds locally and in CI.

Co-authored-by: Conrado Gouvea <conrado@zfnd.org>
2021-08-06 17:32:35 +00:00
teor 4eb0344f01
impl TryFrom for vector references for AtLeastOne (#2578)
Co-authored-by: Conrado Gouvea <conrado@zfnd.org>
2021-08-06 16:39:32 +00:00
Conrado P. L. Gouvea 0cc773f4b8 Increase timeout of cached database creation 2021-08-06 11:52:29 -04:00
Alfredo Garcia 14532e44c1
reduce the number of default test cases (#2574) 2021-08-06 16:17:02 +10:00
Conrado Gouvea bf713bec91
Add ZIP-221 (history tree) to finalized state (#2553)
* Add ZIP-221 history tree to finalized state

* Improve error / panic handling; improve documentation

* Return error again when preparing batch, fix expect messages

* Fix bug when pushing the Heartwood actiation block to the history tree

* Re-increase database version since it was increased in main

Co-authored-by: teor <teor@riseup.net>
2021-08-05 10:02:37 -03:00
teor 1a18f841f7
Add a random number of transactions to generated blocks, rather than always 2 (#2567)
* Add 1 to 3 transactions to generated blocks, rather than always 2

This change improves test coverage.

As a side-effect, it reduces the average number of generated
transactions, which should improve performance.

* Add 1 to max_size generated transparent inputs, rather than always max_size

Co-authored-by: Deirdre Connolly <deirdre@zfnd.org>
2021-08-04 20:48:15 +00:00
Conrado Gouvea 8747d6682e
Fix the storage of anchors in the state (#2563)
* Fix the storage of anchors in the state

* Bump database version
2021-08-04 18:50:41 +00:00
teor 7ad5f1cd0a
Use fixed genesis coinbase data in generated genesis blocks (#2568)
* Return an error if genesis transparent coinbase data is invalid

This error prevents cryptic errors during genesis coinbase deserialization.

And fix and improve documentation.

* Use the fixed Zcash constant for generated genesis coinbase data

This change is required, because genesis transactions do not have a
coinbase height in their coinbase data.
2021-08-04 08:43:46 -03:00
teor 86bbafd02d
Return valid `Utxo`s from `check::transparent_spend` (#2561)
Later PRs will use these UTXOs to check other transparent consensus rules.

Co-authored-by: Alfredo Garcia <oxarbitrage@gmail.com>
2021-08-03 20:53:47 +00:00
Conrado Gouvea 29a658be11
Use RUSTFLAGS=-O to optimize builds and make regenerating state faster (#2552) 2021-08-03 19:12:24 +00:00
Conrado Gouvea fe989e0758
ZIP-221: Add Orchard support to history tree (#2531)
* Add Orchard support to HistoryTree

* Handle network upgrades in HistoryTree

* Add additional methods to save/load HistoryTree

* Apply suggestions from code review

Co-authored-by: Deirdre Connolly <deirdre@zfnd.org>

* Clarification of Entry documentation

* Improvements from code review

* Add HistoryTree tests

* Improved test comments and variable names based on feedback from #2458 on similar test

* Update zebra-chain/src/history_tree.rs

Co-authored-by: Deirdre Connolly <deirdre@zfnd.org>

* Use type aliases for V1 and V2 history trees

Co-authored-by: Deirdre Connolly <deirdre@zfnd.org>
Co-authored-by: teor <teor@riseup.net>
2021-08-03 18:33:51 +00:00
teor 7218aec19f
Design: Fix Transparent Value Sign and Definition (#2555)
* Design: Fix Transparent Value Sign and Definition

* make the transparent value pool the sum of unspent output values, like other pools
* swap the sign of the transparent value balance
* make the remaining transaction value balance the sum of unspent input values
* update the consensus rules based on recent spec changes
* explain why the transparent chain value pool balance can't be negative
* clarify the guide and consensus rules sections

* Use consistent notation for sprout value balances

* Fix typos

Co-authored-by: Alfredo Garcia <oxarbitrage@gmail.com>
2021-08-02 23:52:21 +00:00
teor f9c0620576
Remove unreliable generated chain prevouts tests (#2548)
And adjust the chain lengths for better coverage.
2021-07-30 14:49:25 -03:00
Alfredo Garcia 0325aa2517
Add value_balance() method to Block (#2546)
* add value_balance() method to Block

* Fix a comment typo

Co-authored-by: teor <teor@riseup.net>
2021-07-29 23:46:52 +00:00
teor 4f96a4bb40
Increase coverage for generated chains and proptests (#2540)
* Make legacy chain limit clearer

That way, it doesn't get confused with the coinbase maturity limit.

* Allow 1-5 transactions in each generated block, not always 5

* rustfmt

Co-authored-by: Alfredo Garcia <oxarbitrage@gmail.com>
2021-07-30 09:22:10 +10:00
Pili Guerra b2d1c0e222
Update release date in CHANGELOG (#2545)
* Update release date
2021-07-29 17:03:43 -04:00
Pili Guerra 564b902f94
CHANGELOG for Zebra 1.0.0-alpha.14 (#2538)
* Draft CHANGELOG for Zebra 1.0.0-alpha.14

* Add PR #2533 to CHANGELOG

* Apply suggestions from code review

Co-authored-by: teor <teor@riseup.net>

* Remove entry about updating the changelog

* move #2497

* add #2529

* Add a missing space

* Add #2458, #2525, #2486, #2542 and  #2539 to CHANGELOG

Co-authored-by: teor <teor@riseup.net>
Co-authored-by: Deirdre Connolly <deirdre@zfnd.org>
2021-07-29 21:44:07 +01:00
Pili Guerra f59d552721
Update versions for zebra v1.0.0-alpha.14 release (#2537)
Co-authored-by: teor <teor@riseup.net>
2021-07-29 19:42:21 +00:00
Deirdre Connolly e719c46b1b
Track anchors and note commitment trees in zebra-state (#2458)
* Tidy chain Cargo.toml

* Organize imports

* Add method to get note commitments from all Actions in Orchard shielded data

* Add method to get note commitments from all JoinSplits in Sprout JoinSplitData

* Add Request and Response variants for awaiting anchors

* Add anchors and note commitment trees to finalized state db

* Add (From|Into)Disk impls for tree::Roots and stubs for NoteCommitmentTrees

* Track anchors and note commitment trees in Chain

Append note commitments to their trees when doing update_chain_state_with,
then use the resulting Sapling and Orchard roots to pass to history_tree, and add
new roots to the anchor sets.

* Handle errors when appending to note commitment trees

* Add comments explaining why note commitment are not removed from the tree in revert_chain_state_with

* Implementing note commitments in finalized state

* Finish serialization of Orchard tree; remove old tree when updating finalize state

* Add serialization and finalized state updates for Sprout and Sapling trees

* Partially handle trees in non-finalized state. Use Option for trees in Chain

* Rebuild trees when forking; change finalized state tree getters to not require height

* Pass empty trees to tests; use empty trees by default in Chain

* Also rebuild anchor sets when forking

* Use empty tree as default in finalized state tree getters (for now)

* Use HashMultiSet for anchors in order to make pop_root() work correctly

* Reduce DEFAULT_PARTIAL_CHAIN_PROPTEST_CASES and MAX_PARTIAL_CHAIN_BLOCKS

* Reduce DEFAULT_PARTIAL_CHAIN_PROPTEST_CASES and MAX_PARTIAL_CHAIN_BLOCKS even more

* Apply suggestions from code review

* Add comments about order of note commitments and related methods/fields

* Don't use Option for trees

* Set DEFAULT_PARTIAL_CHAIN_PROPTEST_CASES=1 and restore MAX_PARTIAL_CHAIN_BLOCKS

* Remove unneeded anchor set rebuilding in fork()

* Improve proptest formatting

* Add missing comparisons to eq_internal_state

* Renamed sprout::tree::NoteCommitmentTree::hash() to root()

* Improve comments

* Add asserts, add issues to TODOs

* Remove impl Default for Chain since it was only used by tests

* Improve documentation and assertions; add tree serialization tests

* Remove Sprout code, which will be moved to another branch

* Add todo! in Sprout tree append()

* Remove stub request, response *Anchor* handling for now

* Add test for validating Sapling note commitment tree using test blocks

* Increase database version (new columns added for note commitment trees and anchors)

* Update test to make sure the order of sapling_note_commitments() is being tested

* Improve comments and structure of the test

* Improve variable names again

* Rustfmt

Co-authored-by: Deirdre Connolly <deirdre@zfnd.org>
Co-authored-by: Conrado P. L. Gouvea <conradoplg@gmail.com>
Co-authored-by: Conrado Gouvea <conrado@zfnd.org>
Co-authored-by: teor <teor@riseup.net>
2021-07-29 09:37:18 -04:00
teor 3d792f7195
Validate spends of transparent coinbase outputs (#2525)
* Validate transparent coinbase output maturity and shielding

- Add a CoinbaseSpendRestriction enum and Transaction method
- Validate transparent coinbase spends in non-finalized chains

* Don't use genesis created UTXOs for spends in generated block chains

* Refactor out a new_transaction_ordered_outputs function

* Add Transaction::outputs_mut for tests

* Generate valid transparent spends in arbitrary block chains

* When generating blocks, fixup the block contents, then the block hash

* Test that generated chains contain at least one transparent spend

* Make generated chains long enough for reliable tests

* Add transparent and shielded input and output methods to Transaction

* Split chain generation into 3 functions

* Test that unshielded and immature transparent coinbase spends fail

* Comment punctuation

* Clarify a comment

* Clarify probability calculation

* Test that shielded mature coinbase output spends succeed
2021-07-29 14:23:50 +10:00
Alfredo Garcia ee3c992ca6
Calculate the remaining value in the transparent transaction value pool (#2486)
* add value_balance methods to transparent and shielded

* add value_balance() to transaction

* check the remaining value consensus rule

* change error name

* fix doc and nitpick

* refactor value_balance() method for joinsplit

* changes to value_balance() of Inputs

* implement joinsplits() method(not working)

* remove created methods

* remove special case

* change return error in utilities

* move utils functions to transaction methods

* fix the docs

* simplify some code

* add constrains explicitly

* remove turbofish

* refactor some transaction methods

* fix value balance signs, add docs

* simplify some code

* avoid panic in consensus check

* add missing doc

* move remaining value balance check to the state

* make changes from the last review

Co-authored-by: teor <teor@riseup.net>
2021-07-29 13:49:36 +10:00
teor e2a3a38047
Disable Rust beta tests in CI, due to a rust bug (#2542) 2021-07-29 13:02:12 +10:00
Janito Vaqueiro Ferreira Filho 79d41b3aea
Add `zebra_state::init_test` helper function for tests (#2539)
* Create a `zebra_state::init_test` helper function

This function will be used as a replacement for `zebra_state::init`
inside tests. It's a simpler alternative because it can ignore any
details that aren't relevant for tests.

* Use `init_test` inside `zebra-state` tests

Update usages of `init` to use `init_test` instead, which simplifies
most cases.

* Use `zebra_state::init_test` in `zebra-consensus`

Replace usages of `zebra_state::init` with the new helper function. This
simplifies the code a bit.
2021-07-28 20:55:01 -03:00
Janito Vaqueiro Ferreira Filho 76b70fb408
Add `proptest-impl` feature to `zebra-state` (#2529)
* Add `proptest-impl` feature to `zebra-state`

This prepares the `zebra-state` crate to be able to export some
test-specific helper types and functions.

* Add `arbitrary` module to `zebra-state` root

A separate module to contain the `Prepare` trait, since it's required by
some prop-test strategies and therefore can't be in the `tests` module.

* Replace usages of `tests::Prepare`

Use the same trait but placed in a new module that's accessible based on
the feature flag.

* Remove old `Prepare` trait

It was obsoleted by the new copy in the `arbitrary` module.

* Make `StateService` crate-accessible

Prepare for it to be accessible in some test modules.

* Refactor strategy function import

Import the function directly, instead of just its containing module.

* Move some strategy functions to `tests::setup`

Create a new module for the strategy functions that are only used
internally.

Co-authored-by: teor <teor@riseup.net>
2021-07-28 00:01:19 +00:00
teor 5684667a31
Update to google-github-actions/setup-gcloud in workflows (#2533)
* Update to google-github-actions/setup-gcloud in workflows

See https://github.com/google-github-actions/setup-gcloud#use-google-github-actionssetup-gcloud

* Also update the Google Cloud test workflow

* Also update regenerate stateful test disks

* Also update Manual Deploy

* Also update zcashd deploy
2021-07-27 12:13:04 -04:00
teor a7b0a521d5
rustfmt inside nullifier and utxo proptests (#2515)
* rustfmt inside nullifier and utxo proptests

* Fix a comment typo

* Use a `chain` binding to simplify test assertions
2021-07-26 13:10:24 +10:00
Alfredo Garcia 064bef62a5
decrease number of tests (#2521)
Co-authored-by: Conrado Gouvea <conrado@zfnd.org>
2021-07-23 16:46:32 +00:00
teor 236388909e
Make nullifier tests faster and consistent with UTXO tests (#2513)
* Make some NonFinalizedState methods test-only

* Rename nullifier tests for clarity

* Reduce test times by reducing default proptest cases

The state tests should be about 4x faster after these changes.

They reduce total state test "user CPU" time to 20-30 seconds on my
machine. Previously it was around 2 minutes.

* Replace multiple pushes with extend

Co-authored-by: Alfredo Garcia <oxarbitrage@gmail.com>
2021-07-23 14:27:10 +00:00
Alfredo Garcia fba8a63912
Add value pools design to book summary (#2520)
* add value pools design to book summary
2021-07-23 14:49:47 +01:00
teor e6e03247ba
Reject UTXO double spends (#2511)
* Reject transparent output double-spends

Check that transparent spends use unspent outputs from:
* earlier transaction in the same block,
* earlier blocks in the parent non-finalized chain, or
* the finalized state.

* Fixup UTXOs in proptests

* Add a comment

* Clarify a consensus rule implementation

* Fix an incorrect comment

* Fix an incorrect error message

* Clarify a comment

* Document `unspent_utxos`

* Simplify the UTXO check

Co-authored-by: Janito Vaqueiro Ferreira Filho <janito.vff@gmail.com>

* Further simplify and fix the UTXO check

- split each error case into a separate check
- combine `contains` and `insert`
- add a missing check against the non-finalized unspent UTXOs
- rename arguments and edit error strings for clarity

* Share test methods between check test modules

* Make some chain fields available to tests

* Make error field names consistent with transparent::Input

* WIP: Add tests for UTXO double-spends

- accept output and spend in the same block
- accept output and spend in a later block
- reject output and double-spend all in the same block
- reject output then double-spend in a later block
- reject output, spend, then double-spend all in different blocks

* Use Extend rather than multiple pushes

Co-authored-by: Janito Vaqueiro Ferreira Filho <janito.vff@gmail.com>

* Use Extend for more pushes

* Limit the number of proptest cases, to speed up tests

* Test rejection of UTXOs that were never in the chain

* Test rejection of spends of later transactions in the same block

Co-authored-by: Janito Vaqueiro Ferreira Filho <janito.vff@gmail.com>
2021-07-22 23:40:15 +00:00
Alfredo Garcia 429ccf7f79
Add a `ValueBalance` type (#2505)
* add a zero() method to Amount

* add a value balance type

* change some docs

* rename methods

* Doc changes

Co-authored-by: Janito Vaqueiro Ferreira Filho <janito.vff@gmail.com>

* add getters and setters for `ValueBalance`

* remove commented out code

* impl Add for ValueBalance

* split the tests

* change tests

* fix derives

* change default() to zero()

* remove default constraint

* use matches!

* separate testing code into submodules

* change mod struct

Co-authored-by: Janito Vaqueiro Ferreira Filho <janito.vff@gmail.com>
2021-07-22 12:49:18 +00:00
teor 6df17ff78c
Clarify indexes in `new_ordered_outputs` (#2510) 2021-07-21 10:53:32 +10:00
teor 170e343905
Rename the nullifier test module (#2504) 2021-07-21 09:25:27 +10:00
teor 544be14c70
Reject duplicate Sapling and Orchard nullifiers (#2497)
* Add sapling and orchard duplicate nullifier errors

* Reject duplicate finalized sapling and orchard nullifiers

Reject duplicate sapling and orchard nullifiers in a new block,
when the block is added to a non-finalized chain,
and the duplicate nullifier is already in the finalized state.

* Reject duplicate non-finalized sapling and orchard nullifiers

Reject duplicate sapling and orchard nullifiers in a new block,
when the block is added to a non-finalized chain,
and the duplicate nullifier is in:
* the same shielded data,
* the same transaction,
* the same block, or
* an earlier block in the non-finalized chain.

* Refactor sprout nullifier tests to remove common code

* Add sapling nullifier tests

Test that the state rejects duplicate sapling nullifiers in a new block,
when the block is added to a non-finalized chain,
and the duplicate nullifier is in:
* the same shielded data,
* the same transaction,
* the same block,
* an earlier block in the non-finalized chain, or
* the finalized state.

* Add orchard nullifier tests

Test that the state rejects duplicate orchard nullifiers in a new block,
when the block is added to a non-finalized chain,
and the duplicate nullifier is in:
* the same shielded data,
* the same transaction,
* the same block,
* an earlier block in the non-finalized chain, or
* the finalized state.

* Check for specific nullifiers in the state in tests

* Replace slices with vectors in arguments

* Remove redundant code and variables

* Simplify sapling TransferData tests

Co-authored-by: Janito Vaqueiro Ferreira Filho <janito.vff@gmail.com>

* Remove an extra :

* Remove redundant vec!

Co-authored-by: Janito Vaqueiro Ferreira Filho <janito.vff@gmail.com>
2021-07-19 21:39:05 -03:00
Alfredo Garcia 1dae1f49df
implement Sum for Amount (#2500)
* implement Sum for Amount

* check overflows

* add a `zero()` method to `Amount`

* impl iter::Sum<&Amount<C>> for Result<Amount<C>>

And modify the tests so they test both reference and value based sums.

* use `try_fold()`

* change error doc

* use iter::repeat()

* fix test

Co-authored-by: teor <teor@riseup.net>
2021-07-19 23:05:36 +00:00
teor bfc3e4a46c
Add an OrderedUtxo type for transparent spend validation (#2502)
* Add an OrderedUtxo type for validation of spends within a block

This change allows us to check that transparent spends use outputs from
earlier in their block. (But we don't actually do that check yet.)

We need to keep the order of UTXOs when we're contextually verifying
each new block that is added to a chain. But the block order is
irrelevant for UTXOs stored in the state.

* Take ownership in utxos_from_ordered_utxos

* Delete a confusing comment
2021-07-19 10:52:32 -03:00
teor 684ce70f12
Pass the finalized state to chain contextual validation (#2503)
This change is required to validate UTXOs against a forked chain.

Also abstract chain contextual validation into a new method.
2021-07-19 10:59:30 +10:00
Deirdre Connolly 8a4add55f1
Fix Orchard implementation, refactor, and add more test vectors (#2445)
* Support incomplete Pallas addition, all the way down

* Check Orchard key derivation against test vectors (currently not passing)

* Fix up Orchard keys, notes, nullifiers, address, and their tests

* Fix Incoming Viewing Key generation

* Move around test vectors, impl From<SpendingKey> for FullViewingKey

* Add orchard test vectors module

* Pull in and use the Sinsemilla test vectors

* Test Pallas group hashes for Orchard with test vectors

* Move Orchard Arbitrary implementations to arbitrary.rs

* Improvements from code review

* Derive Eq instead of implementing it for SpendAuthorizingKey

* Dedupe Orchard NoteCommitment::extract_x; fix documentation

* Update zebra-chain/src/orchard/note.rs

Co-authored-by: Deirdre Connolly <deirdre@zfnd.org>

Co-authored-by: Conrado P. L. Gouvea <conradoplg@gmail.com>
Co-authored-by: teor <teor@riseup.net>
Co-authored-by: Conrado Gouvea <conrado@zfnd.org>
2021-07-16 13:52:35 +00:00
teor 049c92374e
clippy: remove a needless borrow (#2501) 2021-07-16 10:29:22 -03:00