[DEV-347] Normalize the way 'subnetwork' is capitalized (#161)

This commit is contained in:
Svarog 2019-01-13 18:00:34 +02:00 committed by stasatdaglabs
parent 6b55950901
commit e3994cddac
24 changed files with 245 additions and 245 deletions

View File

@ -96,9 +96,9 @@ type BlockDAG struct {
// virtual tracks the current tips. // virtual tracks the current tips.
virtual *virtualBlock virtual *virtualBlock
// lastSubNetworkID holds the last registered sub-network ID in the DAG. // lastSubnetworkID holds the last registered subnetwork ID in the DAG.
// Note that it is NOT the total amount of registered (or active) sub-networks. // Note that it is NOT the total amount of registered (or active) subnetworks.
lastSubNetworkID uint64 lastSubnetworkID uint64
// These fields are related to handling of orphan blocks. They are // 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 chain lock and the orphan lock.
@ -567,10 +567,10 @@ func (dag *BlockDAG) connectBlock(node *blockNode, block *util.Block, fastAdd bo
return err return err
} }
// Scan all accepted transactions and register any sub-network registry // Scan all accepted transactions and register any subnetwork registry
// transaction. If any sub-network registry transaction is not well-formed, // transaction. If any subnetwork registry transaction is not well-formed,
// fail the entire block. // fail the entire block.
err = registerSubNetworks(dbTx, acceptedTxsData) err = registerSubnetworks(dbTx, acceptedTxsData)
if err != nil { if err != nil {
return err return err
} }

View File

@ -53,17 +53,17 @@ var (
// unspent transaction output set. // unspent transaction output set.
utxoSetBucketName = []byte("utxoset") utxoSetBucketName = []byte("utxoset")
// pendingSubNetworksBucketName is the name of the db bucket used to store the // pendingSubnetworksBucketName is the name of the db bucket used to store the
// pending sub-networks. // pending subnetworks.
pendingSubNetworksBucketName = []byte("pendingsubnetworks") pendingSubnetworksBucketName = []byte("pendingsubnetworks")
// registeredSubNetworkTxsBucketName is the name of the db bucket used to house // registeredSubnetworkTxsBucketName is the name of the db bucket used to house
// the transactions that have been used to register sub-networks. // the transactions that have been used to register subnetworks.
registeredSubNetworkTxsBucketName = []byte("registeredsubnetworktxs") registeredSubnetworkTxsBucketName = []byte("registeredsubnetworktxs")
// subNetworksBucketName is the name of the db bucket used to store the // subnetworksBucketName is the name of the db bucket used to store the
// sub-network registry. // subnetwork registry.
subNetworksBucketName = []byte("subnetworks") subnetworksBucketName = []byte("subnetworks")
// byteOrder is the preferred byte order used for serializing numeric // byteOrder is the preferred byte order used for serializing numeric
// fields for storage in the database. // fields for storage in the database.
@ -670,7 +670,7 @@ func dbFetchHeightByHash(dbTx database.Tx, hash *daghash.Hash) (int32, error) {
type dagState struct { type dagState struct {
TipHashes []daghash.Hash TipHashes []daghash.Hash
LastFinalityPoint daghash.Hash LastFinalityPoint daghash.Hash
LastSubNetworkID uint64 LastSubnetworkID uint64
} }
// serializeDAGState returns the serialization of the DAG state. // serializeDAGState returns the serialization of the DAG state.
@ -776,21 +776,21 @@ func (dag *BlockDAG) createDAGState() error {
return err return err
} }
// Create the bucket that houses the pending sub-networks. // Create the bucket that houses the pending subnetworks.
_, err = meta.CreateBucket(pendingSubNetworksBucketName) _, err = meta.CreateBucket(pendingSubnetworksBucketName)
if err != nil { if err != nil {
return err return err
} }
// Create the bucket that houses the registered sub-networks to // Create the bucket that houses the registered subnetworks to
// their registry transactions index. // their registry transactions index.
_, err = meta.CreateBucket(registeredSubNetworkTxsBucketName) _, err = meta.CreateBucket(registeredSubnetworkTxsBucketName)
if err != nil { if err != nil {
return err return err
} }
// Create the bucket that houses the registered sub-networks. // Create the bucket that houses the registered subnetworks.
_, err = meta.CreateBucket(subNetworksBucketName) _, err = meta.CreateBucket(subnetworksBucketName)
if err != nil { if err != nil {
return err return err
} }

View File

@ -547,18 +547,18 @@ func TestDAGStateSerialization(t *testing.T) {
state: &dagState{ state: &dagState{
TipHashes: []daghash.Hash{*newHashFromStr("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f")}, TipHashes: []daghash.Hash{*newHashFromStr("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f")},
LastFinalityPoint: *newHashFromStr("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f"), LastFinalityPoint: *newHashFromStr("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f"),
LastSubNetworkID: 123456, LastSubnetworkID: 123456,
}, },
serialized: []byte("{\"TipHashes\":[[111,226,140,10,182,241,179,114,193,166,162,70,174,99,247,79,147,30,131,101,225,90,8,156,104,214,25,0,0,0,0,0]],\"LastFinalityPoint\":[111,226,140,10,182,241,179,114,193,166,162,70,174,99,247,79,147,30,131,101,225,90,8,156,104,214,25,0,0,0,0,0],\"LastSubNetworkID\":123456}"), serialized: []byte("{\"TipHashes\":[[111,226,140,10,182,241,179,114,193,166,162,70,174,99,247,79,147,30,131,101,225,90,8,156,104,214,25,0,0,0,0,0]],\"LastFinalityPoint\":[111,226,140,10,182,241,179,114,193,166,162,70,174,99,247,79,147,30,131,101,225,90,8,156,104,214,25,0,0,0,0,0],\"LastSubnetworkID\":123456}"),
}, },
{ {
name: "block 1", name: "block 1",
state: &dagState{ state: &dagState{
TipHashes: []daghash.Hash{*newHashFromStr("00000000839a8e6886ab5951d76f411475428afc90947ee320161bbf18eb6048")}, TipHashes: []daghash.Hash{*newHashFromStr("00000000839a8e6886ab5951d76f411475428afc90947ee320161bbf18eb6048")},
LastFinalityPoint: *newHashFromStr("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f"), LastFinalityPoint: *newHashFromStr("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f"),
LastSubNetworkID: 684321, LastSubnetworkID: 684321,
}, },
serialized: []byte("{\"TipHashes\":[[72,96,235,24,191,27,22,32,227,126,148,144,252,138,66,117,20,65,111,215,81,89,171,134,104,142,154,131,0,0,0,0]],\"LastFinalityPoint\":[111,226,140,10,182,241,179,114,193,166,162,70,174,99,247,79,147,30,131,101,225,90,8,156,104,214,25,0,0,0,0,0],\"LastSubNetworkID\":684321}"), serialized: []byte("{\"TipHashes\":[[72,96,235,24,191,27,22,32,227,126,148,144,252,138,66,117,20,65,111,215,81,89,171,134,104,142,154,131,0,0,0,0]],\"LastFinalityPoint\":[111,226,140,10,182,241,179,114,193,166,162,70,174,99,247,79,147,30,131,101,225,90,8,156,104,214,25,0,0,0,0,0],\"LastSubnetworkID\":684321}"),
}, },
} }

View File

@ -213,20 +213,20 @@ const (
ErrFinality ErrFinality
// ErrTransactionsNotSorted indicates that transactions in block are not // ErrTransactionsNotSorted indicates that transactions in block are not
// sorted by sub-network // sorted by subnetwork
ErrTransactionsNotSorted ErrTransactionsNotSorted
// ErrInvalidGas transaction wants to use more GAS than allowed // ErrInvalidGas transaction wants to use more GAS than allowed
// by subnetwork // by subnetwork
ErrInvalidGas ErrInvalidGas
// ErrInvalidPayload transaction includes a payload in a sub-network that doesn't allow // ErrInvalidPayload transaction includes a payload in a subnetwork that doesn't allow
// a Payload // a Payload
ErrInvalidPayload ErrInvalidPayload
// ErrSubNetwork indicates that a block doesn't adhere to the sub-network // ErrSubnetwork indicates that a block doesn't adhere to the subnetwork
// registry rules // registry rules
ErrSubNetworkRegistry ErrSubnetworkRegistry
) )
// Map of ErrorCode values back to their constant names for pretty printing. // Map of ErrorCode values back to their constant names for pretty printing.

View File

@ -84,7 +84,7 @@ var (
"4c702b6bf11d5fac"), "4c702b6bf11d5fac"),
}}, }},
LockTime: 0, LockTime: 0,
SubNetworkID: wire.SubNetworkDAGCoin, SubnetworkID: wire.SubnetworkDAGCoin,
}}, }},
} }
) )

View File

@ -151,7 +151,7 @@ var block1 = wire.MsgBlock{
}, },
}, },
LockTime: 0, LockTime: 0,
SubNetworkID: wire.SubNetworkDAGCoin, SubnetworkID: wire.SubnetworkDAGCoin,
}, },
}, },
} }
@ -205,7 +205,7 @@ var block2 = wire.MsgBlock{
}, },
}, },
LockTime: 0, LockTime: 0,
SubNetworkID: wire.SubNetworkDAGCoin, SubnetworkID: wire.SubnetworkDAGCoin,
}, },
{ {
Version: 1, Version: 1,
@ -251,7 +251,7 @@ var block2 = wire.MsgBlock{
}, },
}, },
LockTime: 0, LockTime: 0,
SubNetworkID: wire.SubNetworkDAGCoin, SubnetworkID: wire.SubnetworkDAGCoin,
}, },
}, },
} }
@ -300,7 +300,7 @@ var block3Tx = &wire.MsgTx{
}, },
}, },
LockTime: 0, LockTime: 0,
SubNetworkID: wire.SubNetworkDAGCoin, SubnetworkID: wire.SubnetworkDAGCoin,
} }
var block3 = wire.MsgBlock{ var block3 = wire.MsgBlock{
@ -352,7 +352,7 @@ var block3 = wire.MsgBlock{
}, },
}, },
LockTime: 0, LockTime: 0,
SubNetworkID: wire.SubNetworkDAGCoin, SubnetworkID: wire.SubnetworkDAGCoin,
}, },
block3Tx, block3Tx,
}, },
@ -407,7 +407,7 @@ var block3A = wire.MsgBlock{
}, },
}, },
LockTime: 0, LockTime: 0,
SubNetworkID: wire.SubNetworkDAGCoin, SubnetworkID: wire.SubnetworkDAGCoin,
}, },
block3Tx, block3Tx,
}, },
@ -462,7 +462,7 @@ var block4 = wire.MsgBlock{
}, },
}, },
LockTime: 0, LockTime: 0,
SubNetworkID: wire.SubNetworkDAGCoin, SubnetworkID: wire.SubnetworkDAGCoin,
}, },
}, },
} }
@ -522,7 +522,7 @@ var block5 = wire.MsgBlock{
}, },
}, },
LockTime: 0, LockTime: 0,
SubNetworkID: wire.SubNetworkDAGCoin, SubnetworkID: wire.SubnetworkDAGCoin,
}, },
}, },
} }

View File

@ -11,44 +11,44 @@ import (
"github.com/daglabs/btcd/wire" "github.com/daglabs/btcd/wire"
) )
// registerSubNetworks scans a list of accepted transactions, singles out // registerSubnetworks scans a list of accepted transactions, singles out
// sub-network registry transactions, validates them, and registers a new // subnetwork registry transactions, validates them, and registers a new
// sub-network based on it. // subnetwork based on it.
// This function returns an error if one or more transactions are invalid // This function returns an error if one or more transactions are invalid
func registerSubNetworks(dbTx database.Tx, txs []*TxWithBlockHash) error { func registerSubnetworks(dbTx database.Tx, txs []*TxWithBlockHash) error {
validSubNetworkRegistryTxs := make([]*wire.MsgTx, 0) validSubnetworkRegistryTxs := make([]*wire.MsgTx, 0)
for _, txData := range txs { for _, txData := range txs {
tx := txData.Tx.MsgTx() tx := txData.Tx.MsgTx()
if tx.SubNetworkID == wire.SubNetworkRegistry { if tx.SubnetworkID == wire.SubnetworkRegistry {
err := validateSubNetworkRegistryTransaction(tx) err := validateSubnetworkRegistryTransaction(tx)
if err != nil { if err != nil {
return err return err
} }
validSubNetworkRegistryTxs = append(validSubNetworkRegistryTxs, tx) validSubnetworkRegistryTxs = append(validSubnetworkRegistryTxs, tx)
} }
if subnetworkid.Less(&wire.SubNetworkRegistry, &tx.SubNetworkID) { if subnetworkid.Less(&wire.SubnetworkRegistry, &tx.SubnetworkID) {
// Transactions are ordered by sub-network, so we can safely assume // Transactions are ordered by subnetwork, so we can safely assume
// that the rest of the transactions will not be sub-network registry // that the rest of the transactions will not be subnetwork registry
// transactions. // transactions.
break break
} }
} }
for _, registryTx := range validSubNetworkRegistryTxs { for _, registryTx := range validSubnetworkRegistryTxs {
subNetworkID, err := txToSubNetworkID(registryTx) subnetworkID, err := txToSubnetworkID(registryTx)
if err != nil { if err != nil {
return err return err
} }
sNet, err := dbGetSubNetwork(dbTx, subNetworkID) sNet, err := dbGetSubnetwork(dbTx, subnetworkID)
if err != nil { if err != nil {
return err return err
} }
if sNet == nil { if sNet == nil {
createdSubNetwork := newSubNetwork(registryTx) createdSubnetwork := newSubnetwork(registryTx)
err := dbRegisterSubNetwork(dbTx, subNetworkID, createdSubNetwork) err := dbRegisterSubnetwork(dbTx, subnetworkID, createdSubnetwork)
if err != nil { if err != nil {
return fmt.Errorf("failed registering sub-network"+ return fmt.Errorf("failed registering subnetwork"+
"for tx '%s': %s", registryTx.TxHash(), err) "for tx '%s': %s", registryTx.TxHash(), err)
} }
} }
@ -57,125 +57,125 @@ func registerSubNetworks(dbTx database.Tx, txs []*TxWithBlockHash) error {
return nil return nil
} }
// validateSubNetworkRegistryTransaction makes sure that a given sub-network registry // validateSubnetworkRegistryTransaction makes sure that a given subnetwork registry
// transaction is valid. Such a transaction is valid iff: // transaction is valid. Such a transaction is valid iff:
// - Its entire payload is a uint64 (8 bytes) // - Its entire payload is a uint64 (8 bytes)
func validateSubNetworkRegistryTransaction(tx *wire.MsgTx) error { func validateSubnetworkRegistryTransaction(tx *wire.MsgTx) error {
if len(tx.Payload) != 8 { if len(tx.Payload) != 8 {
return ruleError(ErrSubNetworkRegistry, fmt.Sprintf("validation failed: subnetwork registry"+ return ruleError(ErrSubnetworkRegistry, fmt.Sprintf("validation failed: subnetwork registry"+
"tx '%s' has an invalid payload", tx.TxHash())) "tx '%s' has an invalid payload", tx.TxHash()))
} }
return nil return nil
} }
// txToSubNetworkID creates a sub-network ID from a sub-network registry transaction // txToSubnetworkID creates a subnetwork ID from a subnetwork registry transaction
func txToSubNetworkID(tx *wire.MsgTx) (*subnetworkid.SubNetworkID, error) { func txToSubnetworkID(tx *wire.MsgTx) (*subnetworkid.SubnetworkID, error) {
txHash := tx.TxHash() txHash := tx.TxHash()
return subnetworkid.New(util.Hash160(txHash[:])) return subnetworkid.New(util.Hash160(txHash[:]))
} }
// subNetwork returns a registered sub-network. If the sub-network does not exist // subnetwork returns a registered subnetwork. If the subnetwork does not exist
// this method returns an error. // this method returns an error.
func (dag *BlockDAG) subNetwork(subNetworkID *subnetworkid.SubNetworkID) (*subNetwork, error) { func (dag *BlockDAG) subnetwork(subnetworkID *subnetworkid.SubnetworkID) (*subnetwork, error) {
var sNet *subNetwork var sNet *subnetwork
var err error var err error
dbErr := dag.db.View(func(dbTx database.Tx) error { dbErr := dag.db.View(func(dbTx database.Tx) error {
sNet, err = dbGetSubNetwork(dbTx, subNetworkID) sNet, err = dbGetSubnetwork(dbTx, subnetworkID)
return nil return nil
}) })
if dbErr != nil { if dbErr != nil {
return nil, fmt.Errorf("could not retrieve sub-network '%d': %s", subNetworkID, dbErr) return nil, fmt.Errorf("could not retrieve subnetwork '%d': %s", subnetworkID, dbErr)
} }
if err != nil { if err != nil {
return nil, fmt.Errorf("could not retrieve sub-network '%d': %s", subNetworkID, err) return nil, fmt.Errorf("could not retrieve subnetwork '%d': %s", subnetworkID, err)
} }
return sNet, nil return sNet, nil
} }
// GasLimit returns the gas limit of a registered sub-network. If the sub-network does not // GasLimit returns the gas limit of a registered subnetwork. If the subnetwork does not
// exist this method returns an error. // exist this method returns an error.
func (dag *BlockDAG) GasLimit(subNetworkID *subnetworkid.SubNetworkID) (uint64, error) { func (dag *BlockDAG) GasLimit(subnetworkID *subnetworkid.SubnetworkID) (uint64, error) {
sNet, err := dag.subNetwork(subNetworkID) sNet, err := dag.subnetwork(subnetworkID)
if err != nil { if err != nil {
return 0, err return 0, err
} }
if sNet == nil { if sNet == nil {
return 0, fmt.Errorf("sub-network '%s' not found", subNetworkID) return 0, fmt.Errorf("subnetwork '%s' not found", subnetworkID)
} }
return sNet.gasLimit, nil return sNet.gasLimit, nil
} }
// dbRegisterSubNetwork stores mappings from ID of the sub-network to the sub-network data. // dbRegisterSubnetwork stores mappings from ID of the subnetwork to the subnetwork data.
func dbRegisterSubNetwork(dbTx database.Tx, subNetworkID *subnetworkid.SubNetworkID, network *subNetwork) error { func dbRegisterSubnetwork(dbTx database.Tx, subnetworkID *subnetworkid.SubnetworkID, network *subnetwork) error {
// Serialize the sub-network // Serialize the subnetwork
serializedSubNetwork, err := serializeSubNetwork(network) serializedSubnetwork, err := serializeSubnetwork(network)
if err != nil { if err != nil {
return fmt.Errorf("failed to serialize sub-netowrk '%s': %s", subNetworkID, err) return fmt.Errorf("failed to serialize sub-netowrk '%s': %s", subnetworkID, err)
} }
// Store the sub-network // Store the subnetwork
subNetworksBucket := dbTx.Metadata().Bucket(subNetworksBucketName) subnetworksBucket := dbTx.Metadata().Bucket(subnetworksBucketName)
err = subNetworksBucket.Put(subNetworkID[:], serializedSubNetwork) err = subnetworksBucket.Put(subnetworkID[:], serializedSubnetwork)
if err != nil { if err != nil {
return fmt.Errorf("failed to write sub-netowrk '%s': %s", subNetworkID, err) return fmt.Errorf("failed to write sub-netowrk '%s': %s", subnetworkID, err)
} }
return nil return nil
} }
// dbGetSubNetwork returns the sub-network associated with subNetworkID or nil if the sub-network was not found. // dbGetSubnetwork returns the subnetwork associated with subnetworkID or nil if the subnetwork was not found.
func dbGetSubNetwork(dbTx database.Tx, subNetworkID *subnetworkid.SubNetworkID) (*subNetwork, error) { func dbGetSubnetwork(dbTx database.Tx, subnetworkID *subnetworkid.SubnetworkID) (*subnetwork, error) {
bucket := dbTx.Metadata().Bucket(subNetworksBucketName) bucket := dbTx.Metadata().Bucket(subnetworksBucketName)
serializedSubNetwork := bucket.Get(subNetworkID[:]) serializedSubnetwork := bucket.Get(subnetworkID[:])
if serializedSubNetwork == nil { if serializedSubnetwork == nil {
return nil, nil return nil, nil
} }
return deserializeSubNetwork(serializedSubNetwork) return deserializeSubnetwork(serializedSubnetwork)
} }
type subNetwork struct { type subnetwork struct {
gasLimit uint64 gasLimit uint64
} }
func newSubNetwork(tx *wire.MsgTx) *subNetwork { func newSubnetwork(tx *wire.MsgTx) *subnetwork {
gasLimit := binary.LittleEndian.Uint64(tx.Payload[:8]) gasLimit := binary.LittleEndian.Uint64(tx.Payload[:8])
return &subNetwork{ return &subnetwork{
gasLimit: gasLimit, gasLimit: gasLimit,
} }
} }
// serializeSubNetwork serializes a subNetwork into the following binary format: // serializeSubnetwork serializes a subnetwork into the following binary format:
// | gasLimit (8 bytes) | // | gasLimit (8 bytes) |
func serializeSubNetwork(sNet *subNetwork) ([]byte, error) { func serializeSubnetwork(sNet *subnetwork) ([]byte, error) {
serializedSNet := bytes.NewBuffer(make([]byte, 0, 8)) serializedSNet := bytes.NewBuffer(make([]byte, 0, 8))
// Write the gas limit // Write the gas limit
err := binary.Write(serializedSNet, byteOrder, sNet.gasLimit) err := binary.Write(serializedSNet, byteOrder, sNet.gasLimit)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to serialize sub-network: %s", err) return nil, fmt.Errorf("failed to serialize subnetwork: %s", err)
} }
return serializedSNet.Bytes(), nil return serializedSNet.Bytes(), nil
} }
// deserializeSubNetwork deserializes a byte slice into a subNetwork. // deserializeSubnetwork deserializes a byte slice into a subnetwork.
// See serializeSubNetwork for the binary format. // See serializeSubnetwork for the binary format.
func deserializeSubNetwork(serializedSNetBytes []byte) (*subNetwork, error) { func deserializeSubnetwork(serializedSNetBytes []byte) (*subnetwork, error) {
serializedSNet := bytes.NewBuffer(serializedSNetBytes) serializedSNet := bytes.NewBuffer(serializedSNetBytes)
// Read the gas limit // Read the gas limit
var gasLimit uint64 var gasLimit uint64
err := binary.Read(serializedSNet, byteOrder, &gasLimit) err := binary.Read(serializedSNet, byteOrder, &gasLimit)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to deserialize sub-network: %s", err) return nil, fmt.Errorf("failed to deserialize subnetwork: %s", err)
} }
return &subNetwork{ return &subnetwork{
gasLimit: gasLimit, gasLimit: gasLimit,
}, nil }, nil
} }

View File

@ -7,11 +7,11 @@ import (
"github.com/daglabs/btcd/dagconfig" "github.com/daglabs/btcd/dagconfig"
) )
// TestSubNetworkRegistry tests the full sub-network registry flow // TestSubnetworkRegistry tests the full subnetwork registry flow
func TestSubNetworkRegistry(t *testing.T) { func TestSubnetworkRegistry(t *testing.T) {
params := dagconfig.SimNetParams params := dagconfig.SimNetParams
params.K = 1 params.K = 1
dag, teardownFunc, err := DAGSetup("TestSubNetworkRegistry", Config{ dag, teardownFunc, err := DAGSetup("TestSubnetworkRegistry", Config{
DAGParams: &params, DAGParams: &params,
}) })
if err != nil { if err != nil {
@ -20,11 +20,11 @@ func TestSubNetworkRegistry(t *testing.T) {
defer teardownFunc() defer teardownFunc()
gasLimit := uint64(12345) gasLimit := uint64(12345)
subNetworkID, err := RegisterSubNetworkForTest(dag, gasLimit) subnetworkID, err := RegisterSubnetworkForTest(dag, gasLimit)
if err != nil { if err != nil {
t.Fatalf("could not register network: %s", err) t.Fatalf("could not register network: %s", err)
} }
limit, err := dag.GasLimit(subNetworkID) limit, err := dag.GasLimit(subnetworkID)
if err != nil { if err != nil {
t.Fatalf("could not retrieve gas limit: %s", err) t.Fatalf("could not retrieve gas limit: %s", err)
} }
@ -33,22 +33,22 @@ func TestSubNetworkRegistry(t *testing.T) {
} }
} }
func TestSerializeSubNetwork(t *testing.T) { func TestSerializeSubnetwork(t *testing.T) {
sNet := &subNetwork{ sNet := &subnetwork{
gasLimit: 1000, gasLimit: 1000,
} }
serializedSNet, err := serializeSubNetwork(sNet) serializedSNet, err := serializeSubnetwork(sNet)
if err != nil { if err != nil {
t.Fatalf("sub-network serialization unexpectedly failed: %s", err) t.Fatalf("subnetwork serialization unexpectedly failed: %s", err)
} }
deserializedSNet, err := deserializeSubNetwork(serializedSNet) deserializedSNet, err := deserializeSubnetwork(serializedSNet)
if err != nil { if err != nil {
t.Fatalf("sub-network deserialization unexpectedly failed: %s", err) t.Fatalf("subnetwork deserialization unexpectedly failed: %s", err)
} }
if !reflect.DeepEqual(sNet, deserializedSNet) { if !reflect.DeepEqual(sNet, deserializedSNet) {
t.Errorf("original sub-network and deserialized sub-network are not equal") t.Errorf("original subnetwork and deserialized subnetwork are not equal")
} }
} }

View File

@ -106,7 +106,7 @@ func DAGSetup(dbName string, config Config) (*BlockDAG, func(), error) {
var OpTrueScript = []byte{txscript.OpTrue} var OpTrueScript = []byte{txscript.OpTrue}
type txSubnetworkData struct { type txSubnetworkData struct {
subnetworkID subnetworkid.SubNetworkID subnetworkID subnetworkid.SubnetworkID
Gas uint64 Gas uint64
Payload []byte Payload []byte
} }
@ -129,11 +129,11 @@ func createTxForTest(numInputs uint32, numOutputs uint32, outputValue uint64, su
} }
if subnetworkData != nil { if subnetworkData != nil {
tx.SubNetworkID = subnetworkData.subnetworkID tx.SubnetworkID = subnetworkData.subnetworkID
tx.Gas = subnetworkData.Gas tx.Gas = subnetworkData.Gas
tx.Payload = subnetworkData.Payload tx.Payload = subnetworkData.Payload
} else { } else {
tx.SubNetworkID = wire.SubNetworkDAGCoin tx.SubnetworkID = wire.SubnetworkDAGCoin
tx.Gas = 0 tx.Gas = 0
tx.Payload = []byte{} tx.Payload = []byte{}
} }
@ -180,8 +180,8 @@ func createCoinbaseTxForTest(blockHeight int32, numOutputs uint32, extraNonce in
return tx, nil return tx, nil
} }
// RegisterSubNetworkForTest is used to register network on DAG with specified gas limit // RegisterSubnetworkForTest is used to register network on DAG with specified gas limit
func RegisterSubNetworkForTest(dag *BlockDAG, gasLimit uint64) (*subnetworkid.SubNetworkID, error) { func RegisterSubnetworkForTest(dag *BlockDAG, gasLimit uint64) (*subnetworkid.SubnetworkID, error) {
blockTime := time.Unix(dag.selectedTip().timestamp, 0) blockTime := time.Unix(dag.selectedTip().timestamp, 0)
extraNonce := int64(0) extraNonce := int64(0)
@ -227,9 +227,9 @@ func RegisterSubNetworkForTest(dag *BlockDAG, gasLimit uint64) (*subnetworkid.Su
currentNode := dag.selectedTip() currentNode := dag.selectedTip()
// Create a block with a valid sub-network registry transaction // Create a block with a valid subnetwork registry transaction
registryTx := wire.NewMsgTx(wire.TxVersion) registryTx := wire.NewMsgTx(wire.TxVersion)
registryTx.SubNetworkID = wire.SubNetworkRegistry registryTx.SubnetworkID = wire.SubnetworkRegistry
registryTx.Payload = make([]byte, 8) registryTx.Payload = make([]byte, 8)
binary.LittleEndian.PutUint64(registryTx.Payload, gasLimit) binary.LittleEndian.PutUint64(registryTx.Payload, gasLimit)
@ -243,10 +243,10 @@ func RegisterSubNetworkForTest(dag *BlockDAG, gasLimit uint64) (*subnetworkid.Su
return nil, fmt.Errorf("could not add registry block to DAG: %s", err) return nil, fmt.Errorf("could not add registry block to DAG: %s", err)
} }
// Build a sub-network ID from the registry transaction // Build a subnetwork ID from the registry transaction
subNetworkID, err := txToSubNetworkID(registryTx) subnetworkID, err := txToSubnetworkID(registryTx)
if err != nil { if err != nil {
return nil, fmt.Errorf("could not build sub-network ID: %s", err) return nil, fmt.Errorf("could not build subnetwork ID: %s", err)
} }
return subNetworkID, nil return subnetworkID, nil
} }

View File

@ -262,27 +262,27 @@ func CheckTransactionSanity(tx *util.Tx) error {
} }
} }
// Transactions in native and SubNetworkRegistry SubNetworks must have Gas = 0 // Transactions in native and SubnetworkRegistry Subnetworks must have Gas = 0
if (msgTx.SubNetworkID == wire.SubNetworkDAGCoin || if (msgTx.SubnetworkID == wire.SubnetworkDAGCoin ||
msgTx.SubNetworkID == wire.SubNetworkRegistry) && msgTx.SubnetworkID == wire.SubnetworkRegistry) &&
msgTx.Gas > 0 { msgTx.Gas > 0 {
return ruleError(ErrInvalidGas, "transaction in the native or "+ return ruleError(ErrInvalidGas, "transaction in the native or "+
"registry sub-networks has gas > 0 ") "registry subnetworks has gas > 0 ")
} }
if msgTx.SubNetworkID == wire.SubNetworkDAGCoin && if msgTx.SubnetworkID == wire.SubnetworkDAGCoin &&
len(msgTx.Payload) > 0 { len(msgTx.Payload) > 0 {
return ruleError(ErrInvalidPayload, return ruleError(ErrInvalidPayload,
"transaction in the native sub-network includes a payload") "transaction in the native subnetwork includes a payload")
} }
if msgTx.SubNetworkID == wire.SubNetworkRegistry && if msgTx.SubnetworkID == wire.SubnetworkRegistry &&
len(msgTx.Payload) != 8 { len(msgTx.Payload) != 8 {
return ruleError(ErrInvalidPayload, return ruleError(ErrInvalidPayload,
"transaction in the sub-network registry include a payload "+ "transaction in the subnetwork registry include a payload "+
"with length != 8 bytes") "with length != 8 bytes")
} }
@ -516,7 +516,7 @@ func checkBlockSanity(block *util.Block, powLimit *big.Int, timeSource MedianTim
"index %d", i+1) "index %d", i+1)
return ruleError(ErrMultipleCoinbases, str) return ruleError(ErrMultipleCoinbases, str)
} }
if subnetworkid.Less(&tx.MsgTx().SubNetworkID, &transactions[i].MsgTx().SubNetworkID) { if subnetworkid.Less(&tx.MsgTx().SubnetworkID, &transactions[i].MsgTx().SubnetworkID) {
return ruleError(ErrTransactionsNotSorted, "transactions must be sorted by subnetwork") return ruleError(ErrTransactionsNotSorted, "transactions must be sorted by subnetwork")
} }
} }

View File

@ -753,7 +753,7 @@ var Block100000 = wire.MsgBlock{
}, },
}, },
LockTime: 0, LockTime: 0,
SubNetworkID: wire.SubNetworkDAGCoin, SubnetworkID: wire.SubnetworkDAGCoin,
}, },
{ {
Version: 1, Version: 1,
@ -822,7 +822,7 @@ var Block100000 = wire.MsgBlock{
}, },
}, },
LockTime: 0, LockTime: 0,
SubNetworkID: wire.SubNetworkDAGCoin, SubnetworkID: wire.SubnetworkDAGCoin,
}, },
{ {
Version: 1, Version: 1,
@ -879,7 +879,7 @@ var Block100000 = wire.MsgBlock{
}, },
}, },
LockTime: 0, LockTime: 0,
SubNetworkID: wire.SubNetworkDAGCoin, SubnetworkID: wire.SubnetworkDAGCoin,
}, },
}, },
} }
@ -1015,7 +1015,7 @@ var BlockWithWrongTxOrder = wire.MsgBlock{
}, },
}, },
LockTime: 0, LockTime: 0,
SubNetworkID: subnetworkid.SubNetworkID{11}, SubnetworkID: subnetworkid.SubnetworkID{11},
}, },
{ {
Version: 1, Version: 1,
@ -1084,7 +1084,7 @@ var BlockWithWrongTxOrder = wire.MsgBlock{
}, },
}, },
LockTime: 0, LockTime: 0,
SubNetworkID: wire.SubNetworkDAGCoin, SubnetworkID: wire.SubnetworkDAGCoin,
}, },
{ {
Version: 1, Version: 1,
@ -1141,7 +1141,7 @@ var BlockWithWrongTxOrder = wire.MsgBlock{
}, },
}, },
LockTime: 0, LockTime: 0,
SubNetworkID: wire.SubNetworkDAGCoin, SubnetworkID: wire.SubnetworkDAGCoin,
}, },
}, },
} }
@ -1166,16 +1166,16 @@ func TestCheckTransactionSanity(t *testing.T) {
func(tx *wire.MsgTx) { tx.TxIn[1].PreviousOutPoint.Index = 0 }, func(tx *wire.MsgTx) { tx.TxIn[1].PreviousOutPoint.Index = 0 },
ruleError(ErrDuplicateTxInputs, "")}, ruleError(ErrDuplicateTxInputs, "")},
{"non-zero gas in DAGCoin", 1, 1, 0, {"non-zero gas in DAGCoin", 1, 1, 0,
&txSubnetworkData{wire.SubNetworkDAGCoin, 1, []byte{}}, &txSubnetworkData{wire.SubnetworkDAGCoin, 1, []byte{}},
nil, ruleError(ErrInvalidGas, "")}, nil, ruleError(ErrInvalidGas, "")},
{"non-zero gas in subnetwork registry", 1, 1, 0, {"non-zero gas in subnetwork registry", 1, 1, 0,
&txSubnetworkData{wire.SubNetworkRegistry, 1, []byte{}}, &txSubnetworkData{wire.SubnetworkRegistry, 1, []byte{}},
nil, ruleError(ErrInvalidGas, "")}, nil, ruleError(ErrInvalidGas, "")},
{"non-zero payload in DAGCoin", 1, 1, 0, {"non-zero payload in DAGCoin", 1, 1, 0,
&txSubnetworkData{wire.SubNetworkDAGCoin, 0, []byte{1}}, &txSubnetworkData{wire.SubnetworkDAGCoin, 0, []byte{1}},
nil, ruleError(ErrInvalidPayload, "")}, nil, ruleError(ErrInvalidPayload, "")},
{"payload in subnetwork registry isn't 8 bytes", 1, 1, 0, {"payload in subnetwork registry isn't 8 bytes", 1, 1, 0,
&txSubnetworkData{wire.SubNetworkRegistry, 0, []byte{1, 2, 3, 4, 5, 6, 7}}, &txSubnetworkData{wire.SubnetworkRegistry, 0, []byte{1, 2, 3, 4, 5, 6, 7}},
nil, ruleError(ErrInvalidPayload, "")}, nil, ruleError(ErrInvalidPayload, "")},
} }

View File

@ -166,7 +166,7 @@ type configFlags struct {
DropAddrIndex bool `long:"dropaddrindex" description:"Deletes the address-based transaction index from the database on start up and then exits."` DropAddrIndex bool `long:"dropaddrindex" description:"Deletes the address-based transaction index from the database on start up and then exits."`
RelayNonStd bool `long:"relaynonstd" description:"Relay non-standard transactions regardless of the default settings for the active network."` RelayNonStd bool `long:"relaynonstd" description:"Relay non-standard transactions regardless of the default settings for the active network."`
RejectNonStd bool `long:"rejectnonstd" description:"Reject non-standard transactions regardless of the default settings for the active network."` RejectNonStd bool `long:"rejectnonstd" description:"Reject non-standard transactions regardless of the default settings for the active network."`
SubNetwork string `string:"subnetwork" description:"If subnetwork != 0, than node will request and process only payloads from specified subnetwork. And if subnetwork is 0, than payloads of all subnetworks are processed. Subnetworks 3 through 255 are reserved for future use and are currently not allowed."` Subnetwork string `string:"subnetwork" description:"If subnetwork != 0, than node will request and process only payloads from specified subnetwork. And if subnetwork is 0, than payloads of all subnetworks are processed. Subnetworks 3 through 255 are reserved for future use and are currently not allowed."`
} }
// Config defines the configuration options for btcd. // Config defines the configuration options for btcd.
@ -181,7 +181,7 @@ type Config struct {
MiningAddrs []util.Address MiningAddrs []util.Address
MinRelayTxFee util.Amount MinRelayTxFee util.Amount
Whitelists []*net.IPNet Whitelists []*net.IPNet
SubNetwork *subnetworkid.SubNetworkID Subnetwork *subnetworkid.SubnetworkID
} }
// serviceOptions defines the configuration options for the daemon as a service on // serviceOptions defines the configuration options for the daemon as a service on
@ -753,15 +753,15 @@ func loadConfig() (*Config, []string, error) {
cfg.MiningAddrs = append(cfg.MiningAddrs, addr) cfg.MiningAddrs = append(cfg.MiningAddrs, addr)
} }
if cfg.configFlags.SubNetwork != "" { if cfg.configFlags.Subnetwork != "" {
cfg.SubNetwork, err = subnetworkid.NewFromStr(cfg.configFlags.SubNetwork) cfg.Subnetwork, err = subnetworkid.NewFromStr(cfg.configFlags.Subnetwork)
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
} }
} }
// Check that 'generate' and 'subnetwork' flags do not conflict // Check that 'generate' and 'subnetwork' flags do not conflict
if cfg.Generate && *cfg.SubNetwork != wire.SubNetworkSupportsAll { if cfg.Generate && *cfg.Subnetwork != wire.SubnetworkSupportsAll {
str := "%s: both generate flag and subnetwork filtering are set " str := "%s: both generate flag and subnetwork filtering are set "
err := fmt.Errorf(str, funcName) err := fmt.Errorf(str, funcName)
fmt.Fprintln(os.Stderr, err) fmt.Fprintln(os.Stderr, err)

View File

@ -76,8 +76,8 @@ func TestCreateDefaultConfigFile(t *testing.T) {
// TestConstants makes sure that all constants hard-coded into the help text were not modified. // TestConstants makes sure that all constants hard-coded into the help text were not modified.
func TestConstants(t *testing.T) { func TestConstants(t *testing.T) {
zero := subnetworkid.SubNetworkID{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} zero := subnetworkid.SubnetworkID{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
if wire.SubNetworkSupportsAll != zero { if wire.SubnetworkSupportsAll != zero {
t.Errorf("wire.SubNetworkSupportsAll value was changed from 0, therefore you probably need to update the help text for SubNetwork") t.Errorf("wire.SubnetworkSupportsAll value was changed from 0, therefore you probably need to update the help text for Subnetwork")
} }
} }

View File

@ -54,7 +54,7 @@ var genesisCoinbaseTx = wire.MsgTx{
}, },
}, },
LockTime: 0, LockTime: 0,
SubNetworkID: wire.SubNetworkDAGCoin, SubnetworkID: wire.SubnetworkDAGCoin,
} }
// genesisHash is the hash of the first block in the block chain for the main // genesisHash is the hash of the first block in the block chain for the main

View File

@ -143,7 +143,7 @@ var genesisCoinbaseTx = wire.MsgTx{
}, },
}, },
LockTime: 0, LockTime: 0,
SubNetworkID: wire.SubNetworkDAGCoin, SubnetworkID: wire.SubnetworkDAGCoin,
} }
var genesisMerkleRoot = daghash.Hash([daghash.HashSize]byte{ // Make go vet happy. var genesisMerkleRoot = daghash.Hash([daghash.HashSize]byte{ // Make go vet happy.

View File

@ -659,10 +659,10 @@ func (mp *TxPool) maybeAcceptTransaction(tx *util.Tx, isNew, rateLimit, rejectDu
// Check that transaction does not overuse GAS // Check that transaction does not overuse GAS
msgTx := tx.MsgTx() msgTx := tx.MsgTx()
if msgTx.SubNetworkID == wire.SubNetworkSupportsAll { if msgTx.SubnetworkID == wire.SubnetworkSupportsAll {
return nil, nil, txRuleError(wire.RejectInvalid, "Subnetwork 0 is not permited in transaction") return nil, nil, txRuleError(wire.RejectInvalid, "Subnetwork 0 is not permited in transaction")
} else if msgTx.SubNetworkID != wire.SubNetworkDAGCoin { } else if msgTx.SubnetworkID != wire.SubnetworkDAGCoin {
gasLimit, err := mp.cfg.DAG.GasLimit(&msgTx.SubNetworkID) gasLimit, err := mp.cfg.DAG.GasLimit(&msgTx.SubnetworkID)
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
} }

View File

@ -156,11 +156,11 @@ func (p *poolHarness) CreateCoinbaseTx(blockHeight int32, numOutputs uint32) (*u
return util.NewTx(tx), nil return util.NewTx(tx), nil
} }
// CreateSignedTxForSubNetwork creates a new signed transaction that consumes the provided // CreateSignedTxForSubnetwork creates a new signed transaction that consumes the provided
// inputs and generates the provided number of outputs by evenly splitting the // inputs and generates the provided number of outputs by evenly splitting the
// total input amount. All outputs will be to the payment script associated // total input amount. All outputs will be to the payment script associated
// with the harness and all inputs are assumed to do the same. // with the harness and all inputs are assumed to do the same.
func (p *poolHarness) CreateSignedTxForSubNetwork(inputs []spendableOutpoint, numOutputs uint32, subNetworkID *subnetworkid.SubNetworkID, gas uint64) (*util.Tx, error) { func (p *poolHarness) CreateSignedTxForSubnetwork(inputs []spendableOutpoint, numOutputs uint32, subnetworkID *subnetworkid.SubnetworkID, gas uint64) (*util.Tx, error) {
// Calculate the total input amount and split it amongst the requested // Calculate the total input amount and split it amongst the requested
// number of outputs. // number of outputs.
var totalInput util.Amount var totalInput util.Amount
@ -171,7 +171,7 @@ func (p *poolHarness) CreateSignedTxForSubNetwork(inputs []spendableOutpoint, nu
remainder := uint64(totalInput) - amountPerOutput*uint64(numOutputs) remainder := uint64(totalInput) - amountPerOutput*uint64(numOutputs)
tx := wire.NewMsgTx(wire.TxVersion) tx := wire.NewMsgTx(wire.TxVersion)
tx.SubNetworkID = *subNetworkID tx.SubnetworkID = *subnetworkID
tx.Gas = gas tx.Gas = gas
for _, input := range inputs { for _, input := range inputs {
tx.AddTxIn(&wire.TxIn{ tx.AddTxIn(&wire.TxIn{
@ -211,7 +211,7 @@ func (p *poolHarness) CreateSignedTxForSubNetwork(inputs []spendableOutpoint, nu
// total input amount. All outputs will be to the payment script associated // total input amount. All outputs will be to the payment script associated
// with the harness and all inputs are assumed to do the same. // with the harness and all inputs are assumed to do the same.
func (p *poolHarness) CreateSignedTx(inputs []spendableOutpoint, numOutputs uint32) (*util.Tx, error) { func (p *poolHarness) CreateSignedTx(inputs []spendableOutpoint, numOutputs uint32) (*util.Tx, error) {
return p.CreateSignedTxForSubNetwork(inputs, numOutputs, &wire.SubNetworkDAGCoin, 0) return p.CreateSignedTxForSubnetwork(inputs, numOutputs, &wire.SubnetworkDAGCoin, 0)
} }
// CreateTxChain creates a chain of zero-fee transactions (each subsequent // CreateTxChain creates a chain of zero-fee transactions (each subsequent
@ -610,7 +610,7 @@ func TestProcessTransaction(t *testing.T) {
PkScript: p2shPKScript, PkScript: p2shPKScript,
}}, }},
LockTime: 0, LockTime: 0,
SubNetworkID: wire.SubNetworkDAGCoin, SubnetworkID: wire.SubnetworkDAGCoin,
}) })
harness.txPool.mpUTXOSet.AddTx(p2shTx.MsgTx(), curHeight+1) harness.txPool.mpUTXOSet.AddTx(p2shTx.MsgTx(), curHeight+1)
@ -626,7 +626,7 @@ func TestProcessTransaction(t *testing.T) {
PkScript: dummyPkScript, PkScript: dummyPkScript,
}}, }},
LockTime: 0, LockTime: 0,
SubNetworkID: wire.SubNetworkDAGCoin, SubnetworkID: wire.SubnetworkDAGCoin,
}) })
_, err = harness.txPool.ProcessTransaction(nonStdSigScriptTx, true, false, 0) _, err = harness.txPool.ProcessTransaction(nonStdSigScriptTx, true, false, 0)
if err == nil { if err == nil {
@ -671,7 +671,7 @@ func TestProcessTransaction(t *testing.T) {
}}, }},
TxOut: []*wire.TxOut{}, TxOut: []*wire.TxOut{},
LockTime: 0, LockTime: 0,
SubNetworkID: wire.SubNetworkDAGCoin, SubnetworkID: wire.SubnetworkDAGCoin,
}) })
_, err = harness.txPool.ProcessTransaction(noOutsTx, true, false, 0) _, err = harness.txPool.ProcessTransaction(noOutsTx, true, false, 0)
if err == nil { if err == nil {
@ -748,7 +748,7 @@ func TestProcessTransaction(t *testing.T) {
PkScript: dummyPkScript, PkScript: dummyPkScript,
}}, }},
LockTime: 0, LockTime: 0,
SubNetworkID: wire.SubNetworkDAGCoin, SubnetworkID: wire.SubnetworkDAGCoin,
}) })
_, err = harness.txPool.ProcessTransaction(tx, true, false, 0) _, err = harness.txPool.ProcessTransaction(tx, true, false, 0)
fmt.Println(err) fmt.Println(err)
@ -1830,7 +1830,7 @@ var dummyBlock = wire.MsgBlock{
}, },
}, },
LockTime: 0, LockTime: 0,
SubNetworkID: wire.SubNetworkDAGCoin, SubnetworkID: wire.SubnetworkDAGCoin,
}, },
}, },
} }
@ -1844,13 +1844,13 @@ func TestTransactionGas(t *testing.T) {
// tc := &testContext{t, harness} // tc := &testContext{t, harness}
const gasLimit = 10000 const gasLimit = 10000
subNetworkID, err := blockdag.RegisterSubNetworkForTest(harness.txPool.cfg.DAG, gasLimit) subnetworkID, err := blockdag.RegisterSubnetworkForTest(harness.txPool.cfg.DAG, gasLimit)
if err != nil { if err != nil {
t.Fatalf("unable to register network: %v", err) t.Fatalf("unable to register network: %v", err)
} }
// Create valid transaction // Create valid transaction
tx, err := harness.CreateSignedTxForSubNetwork(spendableOuts[:1], 1, subNetworkID, gasLimit) tx, err := harness.CreateSignedTxForSubnetwork(spendableOuts[:1], 1, subnetworkID, gasLimit)
if err != nil { if err != nil {
t.Fatalf("unable to create transaction: %v", err) t.Fatalf("unable to create transaction: %v", err)
} }
@ -1860,7 +1860,7 @@ func TestTransactionGas(t *testing.T) {
} }
// Create invalid transaction // Create invalid transaction
tx, err = harness.CreateSignedTxForSubNetwork(spendableOuts[1:], 1, subNetworkID, gasLimit+1) tx, err = harness.CreateSignedTxForSubnetwork(spendableOuts[1:], 1, subnetworkID, gasLimit+1)
if err != nil { if err != nil {
t.Fatalf("unable to create transaction: %v", err) t.Fatalf("unable to create transaction: %v", err)
} }

View File

@ -476,7 +476,7 @@ func (g *BlkTmplGenerator) NewBlockTemplate(payToAddress util.Address) (*BlockTe
totalFees := uint64(0) totalFees := uint64(0)
// Create map of GAS usage per subnetwork // Create map of GAS usage per subnetwork
gasUsageMap := make(map[subnetworkid.SubNetworkID]uint64) gasUsageMap := make(map[subnetworkid.SubnetworkID]uint64)
// Choose which transactions make it into the block. // Choose which transactions make it into the block.
for priorityQueue.Len() > 0 { for priorityQueue.Len() > 0 {
@ -485,24 +485,24 @@ func (g *BlkTmplGenerator) NewBlockTemplate(payToAddress util.Address) (*BlockTe
prioItem := heap.Pop(priorityQueue).(*txPrioItem) prioItem := heap.Pop(priorityQueue).(*txPrioItem)
tx := prioItem.tx tx := prioItem.tx
if tx.MsgTx().SubNetworkID != wire.SubNetworkDAGCoin { if tx.MsgTx().SubnetworkID != wire.SubnetworkDAGCoin {
subNetwork := tx.MsgTx().SubNetworkID subnetwork := tx.MsgTx().SubnetworkID
gasUsage, ok := gasUsageMap[subNetwork] gasUsage, ok := gasUsageMap[subnetwork]
if !ok { if !ok {
gasUsage = 0 gasUsage = 0
} }
gasLimit, err := g.dag.GasLimit(&subNetwork) gasLimit, err := g.dag.GasLimit(&subnetwork)
if err != nil { if err != nil {
log.Errorf("Cannot get GAS limit for subNetwork %v", subNetwork) log.Errorf("Cannot get GAS limit for subnetwork %v", subnetwork)
continue continue
} }
txGas := tx.MsgTx().Gas txGas := tx.MsgTx().Gas
if gasLimit-gasUsage < txGas { if gasLimit-gasUsage < txGas {
log.Tracef("Transaction %v (GAS=%v) ignored because gas overusage (GASUsage=%v) in subNetwork %v (GASLimit=%v)", log.Tracef("Transaction %v (GAS=%v) ignored because gas overusage (GASUsage=%v) in subnetwork %v (GASLimit=%v)",
tx.MsgTx().TxHash, txGas, gasUsage, subNetwork, gasLimit) tx.MsgTx().TxHash, txGas, gasUsage, subnetwork, gasLimit)
continue continue
} }
gasUsageMap[subNetwork] = gasUsage + txGas gasUsageMap[subnetwork] = gasUsage + txGas
} }
// Enforce maximum block size. Also check for overflow. // Enforce maximum block size. Also check for overflow.
@ -646,7 +646,7 @@ func (g *BlkTmplGenerator) NewBlockTemplate(payToAddress util.Address) (*BlockTe
// Sort transactions by subnetwork ID before building Merkle tree // Sort transactions by subnetwork ID before building Merkle tree
sort.Slice(blockTxns, func(i, j int) bool { sort.Slice(blockTxns, func(i, j int) bool {
return subnetworkid.Less(&blockTxns[i].MsgTx().SubNetworkID, &blockTxns[j].MsgTx().SubNetworkID) return subnetworkid.Less(&blockTxns[i].MsgTx().SubnetworkID, &blockTxns[j].MsgTx().SubnetworkID)
}) })
// Create a new block ready to be solved. // Create a new block ready to be solved.

View File

@ -889,7 +889,7 @@ func handleGenerate(s *Server, cmd interface{}, closeChan <-chan struct{}) (inte
} }
} }
if !config.MainConfig().SubNetwork.IsEqual(&wire.SubNetworkSupportsAll) { if !config.MainConfig().Subnetwork.IsEqual(&wire.SubnetworkSupportsAll) {
return nil, &btcjson.RPCError{ return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCInvalidRequest.Code, Code: btcjson.ErrRPCInvalidRequest.Code,
Message: "`generate` is not supported on partial nodes.", Message: "`generate` is not supported on partial nodes.",
@ -2230,7 +2230,7 @@ func handleGetGenerate(s *Server, cmd interface{}, closeChan <-chan struct{}) (i
// handleGetHashesPerSec implements the getHashesPerSec command. // handleGetHashesPerSec implements the getHashesPerSec command.
func handleGetHashesPerSec(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { func handleGetHashesPerSec(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
if !config.MainConfig().SubNetwork.IsEqual(&wire.SubNetworkSupportsAll) { if !config.MainConfig().Subnetwork.IsEqual(&wire.SubnetworkSupportsAll) {
return nil, &btcjson.RPCError{ return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCInvalidRequest.Code, Code: btcjson.ErrRPCInvalidRequest.Code,
Message: "`getHashesPerSec` is not supported on partial nodes.", Message: "`getHashesPerSec` is not supported on partial nodes.",
@ -2319,7 +2319,7 @@ func handleGetMempoolInfo(s *Server, cmd interface{}, closeChan <-chan struct{})
// handleGetMiningInfo implements the getMiningInfo command. We only return the // handleGetMiningInfo implements the getMiningInfo command. We only return the
// fields that are not related to wallet functionality. // fields that are not related to wallet functionality.
func handleGetMiningInfo(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { func handleGetMiningInfo(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
if !config.MainConfig().SubNetwork.IsEqual(&wire.SubNetworkSupportsAll) { if !config.MainConfig().Subnetwork.IsEqual(&wire.SubnetworkSupportsAll) {
return nil, &btcjson.RPCError{ return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCInvalidRequest.Code, Code: btcjson.ErrRPCInvalidRequest.Code,
Message: "`getMiningInfo` is not supported on partial nodes.", Message: "`getMiningInfo` is not supported on partial nodes.",
@ -2381,7 +2381,7 @@ func handleGetNetTotals(s *Server, cmd interface{}, closeChan <-chan struct{}) (
// This command had been (possibly temporarily) dropped. // This command had been (possibly temporarily) dropped.
// Originally it relied on height, which no longer makes sense. // Originally it relied on height, which no longer makes sense.
func handleGetNetworkHashPS(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { func handleGetNetworkHashPS(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
if !config.MainConfig().SubNetwork.IsEqual(&wire.SubNetworkSupportsAll) { if !config.MainConfig().Subnetwork.IsEqual(&wire.SubnetworkSupportsAll) {
return nil, &btcjson.RPCError{ return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCInvalidRequest.Code, Code: btcjson.ErrRPCInvalidRequest.Code,
Message: "`getNetworkHashPS` is not supported on partial nodes.", Message: "`getNetworkHashPS` is not supported on partial nodes.",
@ -3286,7 +3286,7 @@ func handleSendRawTransaction(s *Server, cmd interface{}, closeChan <-chan struc
// handleSetGenerate implements the setGenerate command. // handleSetGenerate implements the setGenerate command.
func handleSetGenerate(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) { func handleSetGenerate(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
if !config.MainConfig().SubNetwork.IsEqual(&wire.SubNetworkSupportsAll) { if !config.MainConfig().Subnetwork.IsEqual(&wire.SubnetworkSupportsAll) {
return nil, &btcjson.RPCError{ return nil, &btcjson.RPCError{
Code: btcjson.ErrRPCInvalidRequest.Code, Code: btcjson.ErrRPCInvalidRequest.Code,
Message: "`setGenerate` is not supported on partial nodes.", Message: "`setGenerate` is not supported on partial nodes.",

View File

@ -362,7 +362,7 @@ var Block100000 = wire.MsgBlock{
}, },
}, },
LockTime: 0, LockTime: 0,
SubNetworkID: wire.SubNetworkDAGCoin, SubnetworkID: wire.SubnetworkDAGCoin,
}, },
{ {
Version: 1, Version: 1,
@ -432,7 +432,7 @@ var Block100000 = wire.MsgBlock{
}, },
}, },
LockTime: 0, LockTime: 0,
SubNetworkID: wire.SubNetworkDAGCoin, SubnetworkID: wire.SubnetworkDAGCoin,
}, },
{ {
Version: 1, Version: 1,
@ -501,7 +501,7 @@ var Block100000 = wire.MsgBlock{
}, },
}, },
LockTime: 0, LockTime: 0,
SubNetworkID: wire.SubNetworkDAGCoin, SubnetworkID: wire.SubnetworkDAGCoin,
}, },
{ {
Version: 1, Version: 1,
@ -558,7 +558,7 @@ var Block100000 = wire.MsgBlock{
}, },
}, },
LockTime: 0, LockTime: 0,
SubNetworkID: wire.SubNetworkDAGCoin, SubnetworkID: wire.SubnetworkDAGCoin,
}, },
}, },
} }

View File

@ -13,23 +13,23 @@ import (
"strings" "strings"
) )
// IDLength of array used to store the sub-network ID. See SubNetworkID. // IDLength of array used to store the subnetwork ID. See SubnetworkID.
const IDLength = 20 const IDLength = 20
// MaxStringSize is the maximum length of a SubNetworkID string. // MaxStringSize is the maximum length of a SubnetworkID string.
const MaxStringSize = IDLength * 2 const MaxStringSize = IDLength * 2
// ErrIDStrSize describes an error that indicates the caller specified an ID // ErrIDStrSize describes an error that indicates the caller specified an ID
// string that has too many characters. // string that has too many characters.
var ErrIDStrSize = fmt.Errorf("max ID string length is %v bytes", MaxStringSize) var ErrIDStrSize = fmt.Errorf("max ID string length is %v bytes", MaxStringSize)
// SubNetworkID is used in several of the bitcoin messages and common structures. It // SubnetworkID is used in several of the bitcoin messages and common structures. It
// typically represents ripmed160(sha256(data)). // typically represents ripmed160(sha256(data)).
type SubNetworkID [IDLength]byte type SubnetworkID [IDLength]byte
// String returns the SubNetworkID as the hexadecimal string of the byte-reversed // String returns the SubnetworkID as the hexadecimal string of the byte-reversed
// hash. // hash.
func (id SubNetworkID) String() string { func (id SubnetworkID) String() string {
for i := 0; i < IDLength/2; i++ { for i := 0; i < IDLength/2; i++ {
id[i], id[IDLength-1-i] = id[IDLength-1-i], id[i] id[i], id[IDLength-1-i] = id[IDLength-1-i], id[i]
} }
@ -37,7 +37,7 @@ func (id SubNetworkID) String() string {
} }
// Strings returns a slice of strings representing the IDs in the given slice of IDs // Strings returns a slice of strings representing the IDs in the given slice of IDs
func Strings(ids []SubNetworkID) []string { func Strings(ids []SubnetworkID) []string {
strings := make([]string, len(ids)) strings := make([]string, len(ids))
for i, id := range ids { for i, id := range ids {
strings[i] = id.String() strings[i] = id.String()
@ -51,7 +51,7 @@ func Strings(ids []SubNetworkID) []string {
// //
// NOTE: It is generally cheaper to just slice the ID directly thereby reusing // NOTE: It is generally cheaper to just slice the ID directly thereby reusing
// the same bytes rather than calling this method. // the same bytes rather than calling this method.
func (id *SubNetworkID) CloneBytes() []byte { func (id *SubnetworkID) CloneBytes() []byte {
newID := make([]byte, IDLength) newID := make([]byte, IDLength)
copy(newID, id[:]) copy(newID, id[:])
@ -60,7 +60,7 @@ func (id *SubNetworkID) CloneBytes() []byte {
// SetBytes sets the bytes which represent the ID. An error is returned if // SetBytes sets the bytes which represent the ID. An error is returned if
// the number of bytes passed in is not IDLength. // the number of bytes passed in is not IDLength.
func (id *SubNetworkID) SetBytes(newID []byte) error { func (id *SubnetworkID) SetBytes(newID []byte) error {
nhlen := len(newID) nhlen := len(newID)
if nhlen != IDLength { if nhlen != IDLength {
return fmt.Errorf("invalid ID length of %v, want %v", nhlen, return fmt.Errorf("invalid ID length of %v, want %v", nhlen,
@ -72,7 +72,7 @@ func (id *SubNetworkID) SetBytes(newID []byte) error {
} }
// IsEqual returns true if target is the same as ID. // IsEqual returns true if target is the same as ID.
func (id *SubNetworkID) IsEqual(target *SubNetworkID) bool { func (id *SubnetworkID) IsEqual(target *SubnetworkID) bool {
if id == nil && target == nil { if id == nil && target == nil {
return true return true
} }
@ -84,7 +84,7 @@ func (id *SubNetworkID) IsEqual(target *SubNetworkID) bool {
// AreEqual returns true if both slices contain the same IDs. // AreEqual returns true if both slices contain the same IDs.
// Either slice must not contain duplicates. // Either slice must not contain duplicates.
func AreEqual(first []SubNetworkID, second []SubNetworkID) bool { func AreEqual(first []SubnetworkID, second []SubnetworkID) bool {
if len(first) != len(second) { if len(first) != len(second) {
return false return false
} }
@ -100,8 +100,8 @@ func AreEqual(first []SubNetworkID, second []SubNetworkID) bool {
// New returns a new ID from a byte slice. An error is returned if // New returns a new ID from a byte slice. An error is returned if
// the number of bytes passed in is not IDLength. // the number of bytes passed in is not IDLength.
func New(newID []byte) (*SubNetworkID, error) { func New(newID []byte) (*SubnetworkID, error) {
var sh SubNetworkID var sh SubnetworkID
err := sh.SetBytes(newID) err := sh.SetBytes(newID)
if err != nil { if err != nil {
return nil, err return nil, err
@ -109,11 +109,11 @@ func New(newID []byte) (*SubNetworkID, error) {
return &sh, err return &sh, err
} }
// NewFromStr creates a SubNetworkID from a string. The string should be // NewFromStr creates a SubnetworkID from a string. The string should be
// the hexadecimal string of a byte-reversed hash, but any missing characters // the hexadecimal string of a byte-reversed hash, but any missing characters
// result in zero padding at the end of the SubNetworkID. // result in zero padding at the end of the SubnetworkID.
func NewFromStr(id string) (*SubNetworkID, error) { func NewFromStr(id string) (*SubnetworkID, error) {
ret := new(SubNetworkID) ret := new(SubnetworkID)
err := Decode(ret, id) err := Decode(ret, id)
if err != nil { if err != nil {
return nil, err return nil, err
@ -121,9 +121,9 @@ func NewFromStr(id string) (*SubNetworkID, error) {
return ret, nil return ret, nil
} }
// Decode decodes the byte-reversed hexadecimal string encoding of a SubNetworkID to a // Decode decodes the byte-reversed hexadecimal string encoding of a SubnetworkID to a
// destination. // destination.
func Decode(dst *SubNetworkID, src string) error { func Decode(dst *SubnetworkID, src string) error {
// Return error if ID string is too long. // Return error if ID string is too long.
if len(src) > MaxStringSize { if len(src) > MaxStringSize {
return ErrIDStrSize return ErrIDStrSize
@ -141,7 +141,7 @@ func Decode(dst *SubNetworkID, src string) error {
} }
// Hex decode the source bytes to a temporary destination. // Hex decode the source bytes to a temporary destination.
var reversedHash SubNetworkID var reversedHash SubnetworkID
_, err := hex.Decode(reversedHash[IDLength-hex.DecodedLen(len(srcBytes)):], srcBytes) _, err := hex.Decode(reversedHash[IDLength-hex.DecodedLen(len(srcBytes)):], srcBytes)
if err != nil { if err != nil {
return err return err
@ -156,9 +156,9 @@ func Decode(dst *SubNetworkID, src string) error {
return nil return nil
} }
// ToBig converts a SubNetworkID into a big.Int that can be used to // ToBig converts a SubnetworkID into a big.Int that can be used to
// perform math comparisons. // perform math comparisons.
func ToBig(id *SubNetworkID) *big.Int { func ToBig(id *SubnetworkID) *big.Int {
// A Hash is in little-endian, but the big package wants the bytes in // A Hash is in little-endian, but the big package wants the bytes in
// big-endian, so reverse them. // big-endian, so reverse them.
buf := *id buf := *id
@ -176,22 +176,22 @@ func ToBig(id *SubNetworkID) *big.Int {
// 0 if id == target // 0 if id == target
// +1 if id > target // +1 if id > target
// //
func (id *SubNetworkID) Cmp(target *SubNetworkID) int { func (id *SubnetworkID) Cmp(target *SubnetworkID) int {
return ToBig(id).Cmp(ToBig(target)) return ToBig(id).Cmp(ToBig(target))
} }
// Less returns true iff id a is less than id b // Less returns true iff id a is less than id b
func Less(a *SubNetworkID, b *SubNetworkID) bool { func Less(a *SubnetworkID, b *SubnetworkID) bool {
return a.Cmp(b) < 0 return a.Cmp(b) < 0
} }
// JoinIDsStrings joins all the stringified IDs separated by a separator // JoinIDsStrings joins all the stringified IDs separated by a separator
func JoinIDsStrings(ids []SubNetworkID, separator string) string { func JoinIDsStrings(ids []SubnetworkID, separator string) string {
return strings.Join(Strings(ids), separator) return strings.Join(Strings(ids), separator)
} }
// Sort sorts a slice of ids // Sort sorts a slice of ids
func Sort(ids []SubNetworkID) { func Sort(ids []SubnetworkID) {
sort.Slice(ids, func(i, j int) bool { sort.Slice(ids, func(i, j int) bool {
return Less(&ids[i], &ids[j]) return Less(&ids[i], &ids[j])
}) })

View File

@ -533,7 +533,7 @@ var blockOne = MsgBlock{
}, },
}, },
LockTime: 0, LockTime: 0,
SubNetworkID: SubNetworkDAGCoin, SubnetworkID: SubnetworkDAGCoin,
}, },
}, },
} }

View File

@ -99,14 +99,14 @@ const (
) )
var ( var (
// SubNetworkSupportsAll is the sub-network id that is used to signal to peers that you support all sub-networks // SubnetworkSupportsAll is the subnetwork id that is used to signal to peers that you support all subnetworks
SubNetworkSupportsAll = subnetworkid.SubNetworkID{} SubnetworkSupportsAll = subnetworkid.SubnetworkID{}
// SubNetworkDAGCoin is the default sub-network which is used for transactions without related payload data // SubnetworkDAGCoin is the default subnetwork which is used for transactions without related payload data
SubNetworkDAGCoin = subnetworkid.SubNetworkID{1} SubnetworkDAGCoin = subnetworkid.SubnetworkID{1}
// SubNetworkRegistry is the sub-network which is used for adding new sub networks to the registry // SubnetworkRegistry is the subnetwork which is used for adding new sub networks to the registry
SubNetworkRegistry = subnetworkid.SubNetworkID{2} SubnetworkRegistry = subnetworkid.SubnetworkID{2}
) )
// scriptFreeList defines a free list of byte slices (up to the maximum number // scriptFreeList defines a free list of byte slices (up to the maximum number
@ -259,7 +259,7 @@ type MsgTx struct {
TxIn []*TxIn TxIn []*TxIn
TxOut []*TxOut TxOut []*TxOut
LockTime uint64 LockTime uint64
SubNetworkID subnetworkid.SubNetworkID SubnetworkID subnetworkid.SubnetworkID
Gas uint64 Gas uint64
Payload []byte Payload []byte
} }
@ -295,7 +295,7 @@ func (msg *MsgTx) Copy() *MsgTx {
TxIn: make([]*TxIn, 0, len(msg.TxIn)), TxIn: make([]*TxIn, 0, len(msg.TxIn)),
TxOut: make([]*TxOut, 0, len(msg.TxOut)), TxOut: make([]*TxOut, 0, len(msg.TxOut)),
LockTime: msg.LockTime, LockTime: msg.LockTime,
SubNetworkID: msg.SubNetworkID, SubnetworkID: msg.SubnetworkID,
Gas: msg.Gas, Gas: msg.Gas,
} }
@ -458,18 +458,18 @@ func (msg *MsgTx) BtcDecode(r io.Reader, pver uint32) error {
return err return err
} }
_, err = io.ReadFull(r, msg.SubNetworkID[:]) _, err = io.ReadFull(r, msg.SubnetworkID[:])
if err != nil { if err != nil {
returnScriptBuffers() returnScriptBuffers()
return err return err
} }
if msg.SubNetworkID == SubNetworkSupportsAll { if msg.SubnetworkID == SubnetworkSupportsAll {
str := fmt.Sprintf("%v is a reserved sub network and cannot be used as part of a transaction", msg.SubNetworkID) str := fmt.Sprintf("%v is a reserved sub network and cannot be used as part of a transaction", msg.SubnetworkID)
return messageError("MsgTx.BtcDecode", str) return messageError("MsgTx.BtcDecode", str)
} }
if msg.SubNetworkID != SubNetworkDAGCoin { if msg.SubnetworkID != SubnetworkDAGCoin {
msg.Gas, err = binarySerializer.Uint64(r, littleEndian) msg.Gas, err = binarySerializer.Uint64(r, littleEndian)
if err != nil { if err != nil {
returnScriptBuffers() returnScriptBuffers()
@ -596,14 +596,14 @@ func (msg *MsgTx) BtcEncode(w io.Writer, pver uint32) error {
return err return err
} }
_, err = w.Write(msg.SubNetworkID[:]) _, err = w.Write(msg.SubnetworkID[:])
if err != nil { if err != nil {
return err return err
} }
if msg.SubNetworkID != SubNetworkDAGCoin { if msg.SubnetworkID != SubnetworkDAGCoin {
if msg.SubNetworkID == SubNetworkRegistry && msg.Gas != 0 { if msg.SubnetworkID == SubnetworkRegistry && msg.Gas != 0 {
str := fmt.Sprintf("Transactions from subnetwork %v should have 0 gas", msg.SubNetworkID) str := fmt.Sprintf("Transactions from subnetwork %v should have 0 gas", msg.SubnetworkID)
return messageError("MsgTx.BtcEncode", str) return messageError("MsgTx.BtcEncode", str)
} }
@ -621,10 +621,10 @@ func (msg *MsgTx) BtcEncode(w io.Writer, pver uint32) error {
return err return err
} }
} else if msg.Payload != nil { } else if msg.Payload != nil {
str := fmt.Sprintf("Transactions from subnetwork %v should have <nil> payload", msg.SubNetworkID) str := fmt.Sprintf("Transactions from subnetwork %v should have <nil> payload", msg.SubnetworkID)
return messageError("MsgTx.BtcEncode", str) return messageError("MsgTx.BtcEncode", str)
} else if msg.Gas != 0 { } else if msg.Gas != 0 {
str := fmt.Sprintf("Transactions from subnetwork %v should have 0 gas", msg.SubNetworkID) str := fmt.Sprintf("Transactions from subnetwork %v should have 0 gas", msg.SubnetworkID)
return messageError("MsgTx.BtcEncode", str) return messageError("MsgTx.BtcEncode", str)
} }
@ -657,7 +657,7 @@ func (msg *MsgTx) SerializeSize() int {
n := 32 + VarIntSerializeSize(uint64(len(msg.TxIn))) + n := 32 + VarIntSerializeSize(uint64(len(msg.TxIn))) +
VarIntSerializeSize(uint64(len(msg.TxOut))) VarIntSerializeSize(uint64(len(msg.TxOut)))
if msg.SubNetworkID != SubNetworkDAGCoin { if msg.SubnetworkID != SubnetworkDAGCoin {
// Gas 8 bytes + Serialized varint size for the length of the payload // Gas 8 bytes + Serialized varint size for the length of the payload
n += 8 + VarIntSerializeSize(uint64(len(msg.Payload))) n += 8 + VarIntSerializeSize(uint64(len(msg.Payload)))
} }
@ -735,13 +735,13 @@ func NewMsgTx(version int32) *MsgTx {
Version: version, Version: version,
TxIn: make([]*TxIn, 0, defaultTxInOutAlloc), TxIn: make([]*TxIn, 0, defaultTxInOutAlloc),
TxOut: make([]*TxOut, 0, defaultTxInOutAlloc), TxOut: make([]*TxOut, 0, defaultTxInOutAlloc),
SubNetworkID: SubNetworkDAGCoin, SubnetworkID: SubnetworkDAGCoin,
} }
} }
func newRegistryMsgTx(version int32, gasLimit uint64) *MsgTx { func newRegistryMsgTx(version int32, gasLimit uint64) *MsgTx {
tx := NewMsgTx(version) tx := NewMsgTx(version)
tx.SubNetworkID = SubNetworkRegistry tx.SubnetworkID = SubnetworkRegistry
tx.Payload = make([]byte, 8) tx.Payload = make([]byte, 8)
binary.LittleEndian.PutUint64(tx.Payload, gasLimit) binary.LittleEndian.PutUint64(tx.Payload, gasLimit)
return tx return tx

View File

@ -403,12 +403,12 @@ func TestTxSerialize(t *testing.T) {
0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Payload / Gas limit 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Payload / Gas limit
} }
subNetworkTx := NewMsgTx(1) subnetworkTx := NewMsgTx(1)
subNetworkTx.SubNetworkID = subnetworkid.SubNetworkID{0xff} subnetworkTx.SubnetworkID = subnetworkid.SubnetworkID{0xff}
subNetworkTx.Gas = 5 subnetworkTx.Gas = 5
subNetworkTx.Payload = []byte{0, 1, 2} subnetworkTx.Payload = []byte{0, 1, 2}
subNetworkTxEncoded := []byte{ subnetworkTxEncoded := []byte{
0x01, 0x00, 0x00, 0x00, // Version 0x01, 0x00, 0x00, 0x00, // Version
0x00, // Varint for number of input transactions 0x00, // Varint for number of input transactions
0x00, // Varint for number of output transactions 0x00, // Varint for number of output transactions
@ -445,9 +445,9 @@ func TestTxSerialize(t *testing.T) {
// Sub Network Transaction. // Sub Network Transaction.
{ {
subNetworkTx, subnetworkTx,
subNetworkTx, subnetworkTx,
subNetworkTxEncoded, subnetworkTxEncoded,
nil, nil,
}, },
@ -569,12 +569,12 @@ func TestTxSerializeErrors(t *testing.T) {
} }
registryTx := NewMsgTx(1) registryTx := NewMsgTx(1)
registryTx.SubNetworkID = SubNetworkRegistry registryTx.SubnetworkID = SubnetworkRegistry
registryTx.Gas = 1 registryTx.Gas = 1
w := bytes.NewBuffer(make([]byte, 0, registryTx.SerializeSize())) w := bytes.NewBuffer(make([]byte, 0, registryTx.SerializeSize()))
err := registryTx.Serialize(w) err := registryTx.Serialize(w)
str := fmt.Sprintf("Transactions from subnetwork %v should have 0 gas", SubNetworkRegistry) str := fmt.Sprintf("Transactions from subnetwork %v should have 0 gas", SubnetworkRegistry)
expectedErr := messageError("MsgTx.BtcEncode", str) expectedErr := messageError("MsgTx.BtcEncode", str)
if err == nil || err.Error() != expectedErr.Error() { if err == nil || err.Error() != expectedErr.Error() {
t.Errorf("TestTxSerializeErrors: expected error %v but got %v", expectedErr, err) t.Errorf("TestTxSerializeErrors: expected error %v but got %v", expectedErr, err)
@ -585,7 +585,7 @@ func TestTxSerializeErrors(t *testing.T) {
w = bytes.NewBuffer(make([]byte, 0, registryTx.SerializeSize())) w = bytes.NewBuffer(make([]byte, 0, registryTx.SerializeSize()))
err = dagCoinTx.Serialize(w) err = dagCoinTx.Serialize(w)
str = fmt.Sprintf("Transactions from subnetwork %v should have 0 gas", SubNetworkDAGCoin) str = fmt.Sprintf("Transactions from subnetwork %v should have 0 gas", SubnetworkDAGCoin)
expectedErr = messageError("MsgTx.BtcEncode", str) expectedErr = messageError("MsgTx.BtcEncode", str)
if err == nil || err.Error() != expectedErr.Error() { if err == nil || err.Error() != expectedErr.Error() {
t.Errorf("TestTxSerializeErrors: expected error %v but got %v", expectedErr, err) t.Errorf("TestTxSerializeErrors: expected error %v but got %v", expectedErr, err)
@ -596,7 +596,7 @@ func TestTxSerializeErrors(t *testing.T) {
w = bytes.NewBuffer(make([]byte, 0, registryTx.SerializeSize())) w = bytes.NewBuffer(make([]byte, 0, registryTx.SerializeSize()))
err = dagCoinTx.Serialize(w) err = dagCoinTx.Serialize(w)
str = fmt.Sprintf("Transactions from subnetwork %v should have <nil> payload", SubNetworkDAGCoin) str = fmt.Sprintf("Transactions from subnetwork %v should have <nil> payload", SubnetworkDAGCoin)
expectedErr = messageError("MsgTx.BtcEncode", str) expectedErr = messageError("MsgTx.BtcEncode", str)
if err == nil || err.Error() != expectedErr.Error() { if err == nil || err.Error() != expectedErr.Error() {
t.Errorf("TestTxSerializeErrors: expected error %v but got %v", expectedErr, err) t.Errorf("TestTxSerializeErrors: expected error %v but got %v", expectedErr, err)
@ -619,7 +619,7 @@ func TestTxSerializeErrors(t *testing.T) {
var tx MsgTx var tx MsgTx
err = tx.Deserialize(r) err = tx.Deserialize(r)
str = fmt.Sprintf("%v is a reserved sub network and cannot be used as part of a transaction", SubNetworkSupportsAll) str = fmt.Sprintf("%v is a reserved sub network and cannot be used as part of a transaction", SubnetworkSupportsAll)
expectedErr = messageError("MsgTx.BtcDecode", str) expectedErr = messageError("MsgTx.BtcDecode", str)
if err == nil || err.Error() != expectedErr.Error() { if err == nil || err.Error() != expectedErr.Error() {
t.Errorf("TestTxSerializeErrors: expected error %v but got %v", expectedErr, err) t.Errorf("TestTxSerializeErrors: expected error %v but got %v", expectedErr, err)
@ -870,7 +870,7 @@ var multiTx = &MsgTx{
}, },
}, },
LockTime: 0, LockTime: 0,
SubNetworkID: SubNetworkDAGCoin, SubnetworkID: SubnetworkDAGCoin,
} }
// multiTxEncoded is the wire encoded bytes for multiTx using protocol version // multiTxEncoded is the wire encoded bytes for multiTx using protocol version