Skip to content

Commit

Permalink
[NOD-532] Replace "chain" with "DAG" where appropriate (#537)
Browse files Browse the repository at this point in the history
* [NOD-532] Change chain to DAG in the root package.

* [NOD-532] Change chain to DAG in checkpoints.go.

* [NOD-532] Change chain to DAG in blockdag.

* [NOD-532] Change chain to DAG in cmd.

* [NOD-532] Change chain to DAG in dagconfig.

* [NOD-532] Change chain to DAG in database.

* [NOD-532] Change chain to DAG in mempool.

* [NOD-532] Change chain to DAG in mempool.

* [NOD-532] Change chain to DAG in netsync.

* [NOD-532] Change chain to DAG in rpcclient.

* [NOD-532] Change chain to DAG in server.

* [NOD-532] Change chain to DAG in txscript.

* [NOD-532] Change chain to DAG in util.

* [NOD-532] Change chain to DAG in wire.

* [NOD-532] Remove block heights in dagio.go examples.

* [NOD-532] Rename fakeChain to fakeDAG.

* [NOD-532] Fix comments, remove unused EnableBCInfoHacks flag.

* [NOD-532] Fix comments and variable names.

* [NOD-532] Fix comments.

* [NOD-532] Fix merge errors.

* [NOD-532] Formatted project.
  • Loading branch information
stasatdaglabs authored and svarogg committed Dec 17, 2019
1 parent e3d7e83 commit 03b7af9
Show file tree
Hide file tree
Showing 76 changed files with 287 additions and 373 deletions.
5 changes: 1 addition & 4 deletions blockdag/blockindex.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,7 @@ import (
)

// blockIndex provides facilities for keeping track of an in-memory index of the
// block chain. Although the name block chain suggests a single chain of
// blocks, it is actually a tree-shaped structure where any node can have
// multiple children. However, there can only be one active branch which does
// indeed form a chain from the tip all the way back to the genesis block.
// block DAG.
type blockIndex struct {
// The following fields are set when the instance is created and can't
// be changed afterwards, so there is no need to protect them with a
Expand Down
7 changes: 3 additions & 4 deletions blockdag/blocknode.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,10 +81,9 @@ type blockNode struct {
// chainHeight is the number of hops you need to go down the selected parent chain in order to get to the genesis block.
chainHeight uint64

// Some fields from block headers to aid in best chain selection and
// reconstructing headers from memory. These must be treated as
// immutable and are intentionally ordered to avoid padding on 64-bit
// platforms.
// Some fields from block headers to aid in reconstructing headers
// from memory. These must be treated as immutable and are intentionally
// ordered to avoid padding on 64-bit platforms.
version int32
bits uint32
nonce uint64
Expand Down
4 changes: 2 additions & 2 deletions blockdag/common_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,12 +109,12 @@ func (dag *BlockDAG) TestSetCoinbaseMaturity(maturity uint64) {
}

// newTestDAG returns a DAG that is usable for syntetic tests. It is
// important to note that this chain has no database associated with it, so
// important to note that this DAG has no database associated with it, so
// it is not usable with all functions and the tests must take care when making
// use of it.
func newTestDAG(params *dagconfig.Params) *BlockDAG {
// Create a genesis block node and block index index populated with it
// for use when creating the fake chain below.
// for use when creating the fake DAG below.
node := newBlockNode(&params.GenesisBlock.Header, newSet(), params.K)
index := newBlockIndex(nil, params)
index.AddNode(node)
Expand Down
23 changes: 11 additions & 12 deletions blockdag/dag.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ type chainUpdates struct {

// BlockDAG provides functions for working with the kaspa block DAG.
// It includes functionality such as rejecting duplicate blocks, ensuring blocks
// follow all rules, orphan handling, and best chain selection with reorganization.
// follow all rules, and orphan handling.
type BlockDAG struct {
// The following fields are set when the instance is created and can't
// be changed afterwards, so there is no need to protect them with a
Expand Down Expand Up @@ -93,7 +93,7 @@ type BlockDAG struct {
subnetworkID *subnetworkid.SubnetworkID

// These fields are related to handling of orphan blocks. They are
// protected by a combination of the chain lock and the orphan lock.
// protected by a combination of the DAG lock and the orphan lock.
orphanLock sync.RWMutex
orphans map[daghash.Hash]*orphanBlock
prevOrphans map[daghash.Hash][]*orphanBlock
Expand Down Expand Up @@ -128,7 +128,7 @@ type BlockDAG struct {
unknownVersionsWarned bool

// The notifications field stores a slice of callbacks to be executed on
// certain blockchain events.
// certain blockDAG events.
notificationsLock sync.RWMutex
notifications []NotificationCallback

Expand Down Expand Up @@ -1251,8 +1251,8 @@ func (dag *BlockDAG) isCurrent() bool {
return dagTimestamp >= minus24Hours
}

// IsCurrent returns whether or not the chain believes it is current. Several
// factors are used to guess, but the key factors that allow the chain to
// IsCurrent returns whether or not the DAG believes it is current. Several
// factors are used to guess, but the key factors that allow the DAG to
// believe it is current are:
// - Latest block has a timestamp newer than 24 hours ago
//
Expand Down Expand Up @@ -1800,10 +1800,9 @@ func (dag *BlockDAG) SubnetworkID() *subnetworkid.SubnetworkID {
}

// IndexManager provides a generic interface that is called when blocks are
// connected and disconnected to and from the tip of the main chain for the
// purpose of supporting optional indexes.
// connected to the DAG for the purpose of supporting optional indexes.
type IndexManager interface {
// Init is invoked during chain initialize in order to allow the index
// Init is invoked during DAG initialize in order to allow the index
// manager to initialize itself and any indexes it is managing. The
// channel parameter specifies a channel the caller can close to signal
// that the process should be interrupted. It can be nil if that
Expand All @@ -1815,7 +1814,7 @@ type IndexManager interface {
ConnectBlock(dbTx database.Tx, block *util.Block, blockID uint64, dag *BlockDAG, acceptedTxsData MultiBlockTxsAcceptanceData, virtualTxsAcceptanceData MultiBlockTxsAcceptanceData) error
}

// Config is a descriptor which specifies the blockchain instance configuration.
// Config is a descriptor which specifies the blockDAG instance configuration.
type Config struct {
// DB defines the database which houses the blocks and will be used to
// store all metadata created by this package such as the utxo set.
Expand All @@ -1837,7 +1836,7 @@ type Config struct {
DAGParams *dagconfig.Params

// TimeSource defines the median time source to use for things such as
// block processing and determining whether or not the chain is current.
// block processing and determining whether or not the DAG is current.
//
// The caller is expected to keep a reference to the time source as well
// and add time samples from other peers on the network so the local
Expand All @@ -1854,7 +1853,7 @@ type Config struct {
SigCache *txscript.SigCache

// IndexManager defines an index manager to use when initializing the
// chain and connecting and disconnecting blocks.
// DAG and connecting blocks.
//
// This field can be nil if the caller does not wish to make use of an
// index manager.
Expand Down Expand Up @@ -1907,7 +1906,7 @@ func New(config *Config) (*BlockDAG, error) {

dag.utxoDiffStore = newUTXODiffStore(&dag)

// Initialize the chain state from the passed database. When the db
// Initialize the DAG state from the passed database. When the db
// does not yet contain any DAG state, both it and the DAG state
// will be initialized to contain only the genesis block.
err := dag.initDAGState()
Expand Down
4 changes: 2 additions & 2 deletions blockdag/dag_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,7 @@ func TestCalcSequenceLock(t *testing.T) {
medianTime := node.RelativeAncestor(5).PastMedianTime(dag).Unix()

// The median time calculated from the PoV of the best block in the
// test chain. For unconfirmed inputs, this value will be used since
// test DAG. For unconfirmed inputs, this value will be used since
// the MTP will be calculated from the PoV of the yet-to-be-mined
// block.
nextMedianTime := node.PastMedianTime(dag).Unix()
Expand Down Expand Up @@ -689,7 +689,7 @@ func TestChainHeightToHashRange(t *testing.T) {
// TestIntervalBlockHashes ensures that fetching block hashes at specified
// intervals by end hash works as expected.
func TestIntervalBlockHashes(t *testing.T) {
// Construct a synthetic block chain with a block index consisting of
// Construct a synthetic block DAG with a block index consisting of
// the following structure.
// genesis -> 1 -> 2 -> ... -> 15 -> 16 -> 17 -> 18
// \-> 16a -> 17a -> 18a (unvalidated)
Expand Down
13 changes: 5 additions & 8 deletions blockdag/dagio.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,8 +139,7 @@ func dbPutVersion(dbTx database.Tx, key []byte, version uint32) error {
// bits 1-x - height of the block that contains the unspent txout
//
// Example 1:
// From tx in main blockchain:
// Blk 1, b7c3332bc138e2c9429818f5fed500bcc1746544218772389054dc8047d7cd3f:0
// b7c3332bc138e2c9429818f5fed500bcc1746544218772389054dc8047d7cd3f:0
//
// 03320496b538e853519c726a2c91e61ec11600ae1390813a627c66fb8be7947be63c52
// <><------------------------------------------------------------------>
Expand All @@ -154,8 +153,7 @@ func dbPutVersion(dbTx database.Tx, key []byte, version uint32) error {
// - 0x96...52: x-coordinate of the pubkey
//
// Example 2:
// From tx in main blockchain:
// Blk 113931, 4a16969aa4764dd7507fc1de7f0baa4850a246de90c45e59a3207f9a26b5036f:2
// 4a16969aa4764dd7507fc1de7f0baa4850a246de90c45e59a3207f9a26b5036f:2
//
// 8cf316800900b8025be1b3efc63b0ad48e7f9f10e87544528d58
// <----><------------------------------------------>
Expand All @@ -169,8 +167,7 @@ func dbPutVersion(dbTx database.Tx, key []byte, version uint32) error {
// - 0xb8...58: pubkey hash
//
// Example 3:
// From tx in main blockchain:
// Blk 338156, 1b02d1c8cfef60a189017b9a420c682cf4a0028175f2f563209e4ff61c8c3620:22
// 1b02d1c8cfef60a189017b9a420c682cf4a0028175f2f563209e4ff61c8c3620:22
//
// a8a2588ba5b9e763011dd46a006572d820e448e12d2bbb38640bc718e6
// <----><-------------------------------------------------->
Expand Down Expand Up @@ -432,7 +429,7 @@ func (dag *BlockDAG) initDAGState() error {

if !initialized {
// At this point the database has not already been initialized, so
// initialize both it and the chain state to the genesis block.
// initialize both it and the DAG state to the genesis block.
return dag.createDAGState()
}

Expand Down Expand Up @@ -792,7 +789,7 @@ func (dag *BlockDAG) BlockByHash(hash *daghash.Hash) (*util.Block, error) {
// Lookup the block hash in block index and ensure it is in the DAG
node := dag.index.LookupNode(hash)
if node == nil {
str := fmt.Sprintf("block %s is not in the main chain", hash)
str := fmt.Sprintf("block %s is not in the DAG", hash)
return nil, errNotInDAG(str)
}

Expand Down
4 changes: 0 additions & 4 deletions blockdag/dagio_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,6 @@ func TestUtxoSerialization(t *testing.T) {
entry *UTXOEntry
serialized []byte
}{
// From tx in main blockchain:
// b7c3332bc138e2c9429818f5fed500bcc1746544218772389054dc8047d7cd3f:0
{
name: "blue score 1, coinbase",
entry: &UTXOEntry{
Expand All @@ -58,8 +56,6 @@ func TestUtxoSerialization(t *testing.T) {
},
serialized: hexToBytes("03320496b538e853519c726a2c91e61ec11600ae1390813a627c66fb8be7947be63c52"),
},
// From tx in main blockchain:
// 8131ffb0a2c945ecaf9b9063e59558784f9c3a74741ce6ae2a18d0571dac15bb:1
{
name: "blue score 100001, not coinbase",
entry: &UTXOEntry{
Expand Down
29 changes: 12 additions & 17 deletions blockdag/doc.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,20 +13,20 @@ transactions, so it is extremely important that fully validating nodes agree on
all rules.
At a high level, this package provides support for inserting new blocks into
the block chain according to the aforementioned rules. It includes
the block DAG according to the aforementioned rules. It includes
functionality such as rejecting duplicate blocks, ensuring blocks and
transactions follow all rules, orphan handling, and best chain selection along
transactions follow all rules, orphan handling, and DAG order along
with reorganization.
Since this package does not deal with other kaspa specifics such as network
communication or wallets, it provides a notification system which gives the
caller a high level of flexibility in how they want to react to certain events
such as orphan blocks which need their parents requested and newly connected
main chain blocks which might result in wallet updates.
DAG blocks which might result in wallet updates.
Kaspa DAG Processing Overview
Before a block is allowed into the block chain, it must go through an intensive
Before a block is allowed into the block DAG, it must go through an intensive
series of validation rules. The following list serves as a general outline of
those rules to provide some intuition into what is going on under the hood, but
is by no means exhaustive:
Expand All @@ -38,32 +38,27 @@ is by no means exhaustive:
- Save the most recent orphan blocks for a limited time in case their parent
blocks become available
- Stop processing if the block is an orphan as the rest of the processing
depends on the block's position within the block chain
depends on the block's position within the block DAG
- Perform a series of more thorough checks that depend on the block's position
within the block chain such as verifying block difficulties adhere to
within the block DAG such as verifying block difficulties adhere to
difficulty retarget rules, timestamps are after the median of the last
several blocks, all transactions are finalized, and
block versions are in line with the previous blocks
- Determine how the block fits into the chain and perform different actions
accordingly in order to ensure any side chains which have higher difficulty
than the main chain become the new main chain
- When a block is being connected to the main chain (either through
reorganization of a side chain to the main chain or just extending the
main chain), perform further checks on the block's transactions such as
verifying transaction duplicates, script complexity for the combination of
connected scripts, coinbase maturity, double spends, and connected
transaction values
- When a block is being connected to the DAG, perform further checks on the
block's transactions such as verifying transaction duplicates, script
complexity for the combination of connected scripts, coinbase maturity,
double spends, and connected transaction values
- Run the transaction scripts to verify the spender is allowed to spend the
coins
- Insert the block into the block database
Errors
Errors returned by this package are either the raw errors provided by underlying
calls or of type blockchain.RuleError. This allows the caller to differentiate
calls or of type blockdag.RuleError. This allows the caller to differentiate
between unexpected errors, such as database errors, versus errors due to rule
violations through type assertions. In addition, callers can programmatically
determine the specific rule violation by examining the ErrorCode field of the
type asserted blockchain.RuleError.
type asserted blockdag.RuleError.
*/
package blockdag
4 changes: 2 additions & 2 deletions blockdag/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,12 @@ const (
ErrBlockVersionTooOld

// ErrInvalidTime indicates the time in the passed block has a precision
// that is more than one second. The chain consensus rules require
// that is more than one second. The DAG consensus rules require
// timestamps to have a maximum precision of one second.
ErrInvalidTime

// ErrTimeTooOld indicates the time is either before the median time of
// the last several blocks per the chain consensus rules.
// the last several blocks per the DAG consensus rules.
ErrTimeTooOld

// ErrTimeTooNew indicates the time is too far in the future as compared
Expand Down
20 changes: 10 additions & 10 deletions blockdag/fullblocks_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,8 @@ func isSupportedDbType(dbType string) bool {
return false
}

// DAGSetup is used to create a new db and chain instance with the genesis
// block already inserted. In addition to the new chain instance, it returns
// DAGSetup is used to create a new db and DAG instance with the genesis
// block already inserted. In addition to the new DAG instance, it returns
// a teardown function the caller should invoke when done testing to clean up.
func DAGSetup(dbName string, params *dagconfig.Params) (*blockdag.BlockDAG, func(), error) {
if !isSupportedDbType(testDbType) {
Expand Down Expand Up @@ -109,23 +109,23 @@ func DAGSetup(dbName string, params *dagconfig.Params) (*blockdag.BlockDAG, func
}
}

// Copy the chain params to ensure any modifications the tests do to
// Copy the DAG params to ensure any modifications the tests do to
// the DAG parameters do not affect the global instance.
paramsCopy := *params

// Create the main chain instance.
chain, err := blockdag.New(&blockdag.Config{
// Create the DAG instance.
dag, err := blockdag.New(&blockdag.Config{
DB: db,
DAGParams: &paramsCopy,
TimeSource: blockdag.NewMedianTime(),
SigCache: txscript.NewSigCache(1000),
})
if err != nil {
teardown()
err := errors.Errorf("failed to create chain instance: %v", err)
err := errors.Errorf("failed to create DAG instance: %v", err)
return nil, nil, err
}
return chain, teardown, nil
return dag, teardown, nil
}

// TestFullBlocks ensures all tests generated by the fullblocktests package
Expand All @@ -140,7 +140,7 @@ func TestFullBlocks(t *testing.T) {
t.Fatalf("failed to generate tests: %v", err)
}

// Create a new database and chain instance to run tests against.
// Create a new database and DAG instance to run tests against.
dag, teardownFunc, err := DAGSetup("fullblocktest",
&dagconfig.RegressionNetParams)
if err != nil {
Expand Down Expand Up @@ -255,7 +255,7 @@ func TestFullBlocks(t *testing.T) {
if _, ok := err.(blockdag.RuleError); !ok {
t.Fatalf("block %q (hash %s, height %d) "+
"returned unexpected error type -- "+
"got %T, want blockchain.RuleError",
"got %T, want blockdag.RuleError",
item.Name, block.Hash(), blockHeight,
err)
}
Expand All @@ -274,7 +274,7 @@ func TestFullBlocks(t *testing.T) {
}
}

// testExpectedTip ensures the current tip of the blockchain is the
// testExpectedTip ensures the current tip of the blockDAG is the
// block specified in the provided test instance.
testExpectedTip := func(item fullblocktests.ExpectedTip) {
blockHeight := item.Height
Expand Down
Loading

0 comments on commit 03b7af9

Please sign in to comment.