Browse Source

yuge modularization... now nil panics on config

master
Loki Verloren 3 months ago
parent
commit
f7caaa6c07
100 changed files with 1176 additions and 1848 deletions
  1. 1
    1
      pkg/app/create/gen.go
  2. 6
    5
      pkg/app/g/generators.go
  3. 7
    6
      pkg/app/g/validators.go
  4. 9
    9
      pkg/app/nine/config.go
  5. 1
    1
      pkg/app/wallet/gen.go
  6. 2
    2
      pkg/chain/accept.go
  7. 44
    45
      pkg/chain/chain.go
  8. 12
    13
      pkg/chain/chainio.go
  9. 3
    3
      pkg/chain/checkpoints.go
  10. 0
    58
      pkg/chain/config/README.md
  11. 22
    23
      pkg/chain/config/address.go
  12. 0
    37
      pkg/chain/config/doc.go
  13. 1
    1
      pkg/chain/config/genesis.go
  14. 0
    269
      pkg/chain/config/genesis_test.go
  15. 119
    83
      pkg/chain/config/params-defs.go
  16. 4
    2
      pkg/chain/config/params-mainnet.go
  17. 3
    3
      pkg/chain/config/params-regtest.go
  18. 3
    3
      pkg/chain/config/params-simnet.go
  19. 3
    3
      pkg/chain/config/params-testnet.go
  20. 89
    0
      pkg/chain/config/params.go
  21. 0
    41
      pkg/chain/config/params/params.go
  22. 0
    32
      pkg/chain/config/params_test.go
  23. 0
    507
      pkg/chain/config/register_test.go
  24. 0
    38
      pkg/chain/config/util.go
  25. 3
    4
      pkg/chain/config/wif.go
  26. 1
    1
      pkg/chain/fork/fork.go
  27. 18
    18
      pkg/chain/index/addrindex.go
  28. 2
    2
      pkg/chain/index/blocklogger.go
  29. 3
    4
      pkg/chain/index/cfindex.go
  30. 3
    3
      pkg/chain/index/common.go
  31. 6
    7
      pkg/chain/index/manager.go
  32. 4
    5
      pkg/chain/index/txindex.go
  33. 4
    4
      pkg/chain/merkle.go
  34. 6
    5
      pkg/chain/mining/cpu/cpuminer.go
  35. 12
    11
      pkg/chain/mining/mining.go
  36. 2
    2
      pkg/chain/process.go
  37. 7
    7
      pkg/chain/protocol/protocol.go
  38. 3
    4
      pkg/chain/scriptval.go
  39. 2
    2
      pkg/chain/sync/blocklogger.go
  40. 2
    3
      pkg/chain/sync/interface.go
  41. 12
    12
      pkg/chain/sync/manager.go
  42. 3
    5
      pkg/chain/tx/author/author.go
  43. 12
    12
      pkg/chain/tx/script/sign.go
  44. 17
    17
      pkg/chain/tx/script/standard.go
  45. 7
    8
      pkg/chain/utxoviewpoint.go
  46. 15
    15
      pkg/chain/validate.go
  47. 3
    6
      pkg/chain/weight.go
  48. 7
    6
      pkg/chain/wire/common.go
  49. 11
    10
      pkg/chain/wire/message.go
  50. 4
    2
      pkg/chain/wire/msgaddr.go
  51. 5
    3
      pkg/chain/wire/msgfeefilter.go
  52. 5
    3
      pkg/chain/wire/msgfilteradd.go
  53. 5
    3
      pkg/chain/wire/msgfilterclear.go
  54. 5
    3
      pkg/chain/wire/msgfilterload.go
  55. 2
    1
      pkg/chain/wire/msggetblocks.go
  56. 5
    3
      pkg/chain/wire/msgmempool.go
  57. 4
    3
      pkg/chain/wire/msgmerkleblock.go
  58. 9
    7
      pkg/chain/wire/msgping.go
  59. 7
    5
      pkg/chain/wire/msgpong.go
  60. 6
    5
      pkg/chain/wire/msgreject.go
  61. 5
    3
      pkg/chain/wire/msgsendheaders.go
  62. 9
    7
      pkg/chain/wire/msgversion.go
  63. 15
    16
      pkg/chain/wire/netaddress.go
  64. 3
    3
      pkg/db/ffldb/blockio.go
  65. 3
    3
      pkg/db/ffldb/db.go
  66. 3
    3
      pkg/db/ffldb/driver.go
  67. 2
    2
      pkg/db/interface.go
  68. 1
    2
      pkg/node/getwork.go
  69. 2
    2
      pkg/node/main.go
  70. 3
    2
      pkg/node/mempool/estimatefee.go
  71. 27
    27
      pkg/node/mempool/mempool.go
  72. 3
    4
      pkg/node/mempool/policy.go
  73. 5
    5
      pkg/node/params.go
  74. 31
    3
      pkg/node/rpcadapters.go
  75. 25
    24
      pkg/node/rpcserver.go
  76. 48
    47
      pkg/node/rpcwebsocket.go
  77. 23
    23
      pkg/node/server.go
  78. 5
    4
      pkg/peer/addrmgr/addrmanager.go
  79. 3
    2
      pkg/peer/connmgr/seed.go
  80. 19
    18
      pkg/peer/peer.go
  81. 7
    6
      pkg/rpc/client/extensions.go
  82. 4
    3
      pkg/rpc/client/mining.go
  83. 17
    16
      pkg/rpc/client/notify.go
  84. 10
    9
      pkg/rpc/client/rawtransactions.go
  85. 65
    64
      pkg/rpc/client/wallet.go
  86. 17
    16
      pkg/rpc/legacy/methods.go
  87. 6
    6
      pkg/rpc/server/server.go
  88. 4
    4
      pkg/spv/blockmanager.go
  89. 5
    2
      pkg/spv/cache/cacheable_block.go
  90. 4
    5
      pkg/spv/query.go
  91. 70
    28
      pkg/spv/rescan.go
  92. 93
    23
      pkg/spv/spv.go
  93. 31
    11
      pkg/spv/utxoscanner.go
  94. 2
    3
      pkg/util/bloom/filter.go
  95. 1
    3
      pkg/util/bloom/merkleblock.go
  96. 1
    2
      pkg/util/hash160.go
  97. 3
    2
      pkg/util/hdkeychain/extendedkey.go
  98. 40
    39
      pkg/util/legacy/keystore/keystore.go
  99. 10
    10
      pkg/wallet/Recovery.go
  100. 0
    0
      pkg/wallet/Rescan.go

+ 1
- 1
pkg/app/create/gen.go View File

@@ -23,7 +23,7 @@ var Gen = g.Cmd("create",
23 23
 		func(app *def.App) int {
24 24
 			netDir := walletmain.NetworkDir(
25 25
 				filepath.Join(*app.Config.DataDir, "wallet"),
26
-				app.Config.ActiveNetParams.Params)
26
+				app.Config.ActiveNetParams)
27 27
 			wdb := netDir // + "/wallet.db"
28 28
 			if exists, _ := util.FileExists(wdb); !exists {
29 29
 				if e := walletmain.CreateWallet(

+ 6
- 5
pkg/app/g/generators.go View File

@@ -11,6 +11,7 @@ import (
11 11
 
12 12
 	"git.parallelcoin.io/dev/9/pkg/app/def"
13 13
 	"git.parallelcoin.io/dev/9/pkg/app/nine"
14
+	"git.parallelcoin.io/dev/9/pkg/chain/config"
14 15
 	"git.parallelcoin.io/dev/9/pkg/ifc"
15 16
 	"git.parallelcoin.io/dev/9/pkg/util"
16 17
 	"git.parallelcoin.io/dev/9/pkg/util/cl"
@@ -24,11 +25,11 @@ var DataDir = filepath.Dir(util.AppDataDir("9", false))
24 25
 var Networks = []string{"mainnet", "testnet", "simnet", "regtestnet"}
25 26
 
26 27
 // NetParams stores the information required to set the parameters for the network
27
-var NetParams = map[string]*nine.Params{
28
-	"mainnet":    &nine.MainNetParams,
29
-	"testnet":    &nine.TestNet3Params,
30
-	"simnet":     &nine.SimNetParams,
31
-	"regtestnet": &nine.RegressionNetParams,
28
+var NetParams = map[string]*config.Params{
29
+	"mainnet":    &config.MainNetParams,
30
+	"testnet":    &config.TestNet3Params,
31
+	"simnet":     &config.SimNetParams,
32
+	"regtestnet": &config.RegressionNetParams,
32 33
 }
33 34
 
34 35
 // NewApp generates a new App using a collection of generator functions passed to it

+ 7
- 6
pkg/app/g/validators.go View File

@@ -12,8 +12,9 @@ import (
12 12
 	"strings"
13 13
 	"time"
14 14
 
15
+	"git.parallelcoin.io/dev/9/pkg/chain/config"
16
+
15 17
 	"git.parallelcoin.io/dev/9/pkg/app/def"
16
-	"git.parallelcoin.io/dev/9/pkg/app/nine"
17 18
 	"git.parallelcoin.io/dev/9/pkg/chain"
18 19
 	"git.parallelcoin.io/dev/9/pkg/chain/fork"
19 20
 	"git.parallelcoin.io/dev/9/pkg/ifc"
@@ -503,7 +504,7 @@ func init() {
503 504
 		for _, x := range Networks {
504 505
 			if x == sn {
505 506
 				found = true
506
-				*nine.ActiveNetParams = *NetParams[x]
507
+				*r.App.Config.ActiveNetParams = *NetParams[x]
507 508
 			}
508 509
 		}
509 510
 		if r != nil && found {
@@ -719,19 +720,19 @@ func ValidateMiner(app *def.App) int {
719 720
 	// log <- cl.Debug{"checking mining addresses"}
720 721
 	if app.Config.MiningAddrs != nil {
721 722
 		app.Config.State.ActiveMiningAddrs =
722
-			make([]util.Address, 0, len(*app.Config.MiningAddrs))
723
+			make([]config.Address, 0, len(*app.Config.MiningAddrs))
723 724
 		if len(*app.Config.MiningAddrs) > 0 {
724 725
 			for _, strAddr := range *app.Config.MiningAddrs {
725 726
 				if len(strAddr) > 1 {
726
-					addr, err := util.DecodeAddress(strAddr,
727
-						app.Config.ActiveNetParams.Params)
727
+					addr, err := config.DecodeAddress(strAddr,
728
+						app.Config.ActiveNetParams)
728 729
 					if err != nil {
729 730
 						str := "%s: mining address '%s' failed to decode: %v"
730 731
 						err := fmt.Errorf(str, "runNode", strAddr, err)
731 732
 						fmt.Fprintln(os.Stderr, err)
732 733
 						return 1
733 734
 					}
734
-					if !addr.IsForNet(app.Config.ActiveNetParams.Params) {
735
+					if !addr.IsForNet(app.Config.ActiveNetParams) {
735 736
 						str := "%s: mining address '%s' is on the wrong network"
736 737
 						err := fmt.Errorf(str, "runNode", strAddr)
737 738
 						fmt.Fprintln(os.Stderr, err)

+ 9
- 9
pkg/app/nine/config.go View File

@@ -5,7 +5,7 @@ import (
5 5
 	"strings"
6 6
 	"time"
7 7
 
8
-	chaincfg "git.parallelcoin.io/dev/9/pkg/chain/config"
8
+	"git.parallelcoin.io/dev/9/pkg/chain/config"
9 9
 	"git.parallelcoin.io/dev/9/pkg/util"
10 10
 )
11 11
 
@@ -108,7 +108,7 @@ type Config struct {
108 108
 	LegacyRPCMaxWebsockets   *int
109 109
 	ExperimentalRPCListeners *[]string
110 110
 	State                    *StateConfig
111
-	ActiveNetParams          *Params
111
+	ActiveNetParams          *config.Params
112 112
 	TestnetNumber            *int
113 113
 }
114 114
 
@@ -119,8 +119,8 @@ type StateConfig struct {
119 119
 	DialTimeout         func(network string, address string, timeout time.Duration) (net.Conn, error)
120 120
 	Dial                func(addr net.Addr) (net.Conn, error)
121 121
 	ProxyDial           func(network, addr string) (net.Conn, error)
122
-	AddedCheckpoints    []chaincfg.Checkpoint
123
-	ActiveMiningAddrs   []util.Address
122
+	AddedCheckpoints    []config.Checkpoint
123
+	ActiveMiningAddrs   []config.Address
124 124
 	ActiveMinerKey      []byte
125 125
 	ActiveMinRelayTxFee util.Amount
126 126
 	ActiveWhitelists    []*net.IPNet
@@ -132,31 +132,31 @@ type StateConfig struct {
132 132
 
133 133
 // // Params is used to group parameters for various networks such as the main network and test networks.
134 134
 // type Params struct {
135
-// 	*chaincfg.Params
135
+// 	*config.Params
136 136
 // 	RPCPort string
137 137
 // }
138 138
 
139 139
 // // MainNetParams contains parameters specific to the main network (wire.MainNet).  NOTE: The RPC port is intentionally different than the reference implementation because pod does not handle wallet requests.  The separate wallet process listens on the well-known port and forwards requests it does not handle on to pod.  This approach allows the wallet process to emulate the full reference implementation RPC API.
140 140
 // var MainNetParams = Params{
141
-// 	Params:  &chaincfg.MainNetParams,
141
+// 	Params:  &config.MainNetParams,
142 142
 // 	RPCPort: "11048",
143 143
 // }
144 144
 
145 145
 // // RegressionNetParams contains parameters specific to the regression test network (wire.TestNet).  NOTE: The RPC port is intentionally different than the reference implementation - see the MainNetParams comment for details.
146 146
 // var RegressionNetParams = Params{
147
-// 	Params:  &chaincfg.RegressionNetParams,
147
+// 	Params:  &config.RegressionNetParams,
148 148
 // 	RPCPort: "31048",
149 149
 // }
150 150
 
151 151
 // // SimNetParams contains parameters specific to the simulation test network (wire.SimNet).
152 152
 // var SimNetParams = Params{
153
-// 	Params:  &chaincfg.SimNetParams,
153
+// 	Params:  &config.SimNetParams,
154 154
 // 	RPCPort: "41048",
155 155
 // }
156 156
 
157 157
 // // TestNet3Params contains parameters specific to the test network (version 3) (wire.TestNet3).  NOTE: The RPC port is intentionally different than the reference implementation - see the MainNetParams comment for details.
158 158
 // var TestNet3Params = Params{
159
-// 	Params:  &chaincfg.TestNet3Params,
159
+// 	Params:  &config.TestNet3Params,
160 160
 // 	RPCPort: "21048",
161 161
 // }
162 162
 // var ActiveNetParams = &MainNetParams

+ 1
- 1
pkg/app/wallet/gen.go View File

@@ -20,7 +20,7 @@ var Gen = g.Cmd("wallet",
20 20
 		func(app *def.App) int {
21 21
 			g.SetAppDataDir(app, "wallet")
22 22
 			netDir := walletmain.NetworkDir(*app.Config.AppDataDir,
23
-				app.Config.ActiveNetParams.Params)
23
+				app.Config.ActiveNetParams)
24 24
 			wdb := netDir // + "/wallet.db"
25 25
 			if exists, _ := util.FileExists(wdb); !exists {
26 26
 				if e := walletmain.CreateWallet(

+ 2
- 2
pkg/chain/accept.go View File

@@ -3,12 +3,12 @@ package chain
3 3
 import (
4 4
 	"fmt"
5 5
 
6
+	"git.parallelcoin.io/dev/9/pkg/chain/wire"
6 7
 	database "git.parallelcoin.io/dev/9/pkg/db"
7
-	"git.parallelcoin.io/dev/9/pkg/util"
8 8
 )
9 9
 
10 10
 // maybeAcceptBlock potentially accepts a block into the block chain and, if accepted, returns whether or not it is on the main chain.  It performs several validation checks which depend on its position within the block chain before adding it.  The block is expected to have already gone through ProcessBlock before calling this function with it. The flags are also passed to checkBlockContext and connectBestChain.  See their documentation for how the flags modify their behavior. This function MUST be called with the chain state lock held (for writes).
11
-func (b *BlockChain) maybeAcceptBlock(block *util.Block, flags BehaviorFlags) (bool, error) {
11
+func (b *BlockChain) maybeAcceptBlock(block *wire.Block, flags BehaviorFlags) (bool, error) {
12 12
 	// The height of this block is one more than the referenced previous block.
13 13
 	prevHash := &block.MsgBlock().Header.PrevBlock
14 14
 	prevNode := b.Index.LookupNode(prevHash)

+ 44
- 45
pkg/chain/chain.go View File

@@ -6,12 +6,11 @@ import (
6 6
 	"sync"
7 7
 	"time"
8 8
 
9
-	chaincfg "git.parallelcoin.io/dev/9/pkg/chain/config"
9
+	"git.parallelcoin.io/dev/9/pkg/chain/config"
10 10
 	chainhash "git.parallelcoin.io/dev/9/pkg/chain/hash"
11 11
 	txscript "git.parallelcoin.io/dev/9/pkg/chain/tx/script"
12 12
 	"git.parallelcoin.io/dev/9/pkg/chain/wire"
13 13
 	database "git.parallelcoin.io/dev/9/pkg/db"
14
-	"git.parallelcoin.io/dev/9/pkg/util"
15 14
 	cl "git.parallelcoin.io/dev/9/pkg/util/cl"
16 15
 )
17 16
 
@@ -29,7 +28,7 @@ type BlockLocator []*chainhash.Hash
29 28
 
30 29
 // orphanBlock represents a block that we don't yet have the parent for.  It is a normal block plus an expiration time to prevent caching the orphan forever.
31 30
 type orphanBlock struct {
32
-	block      *util.Block
31
+	block      *wire.Block
33 32
 	expiration time.Time
34 33
 }
35 34
 
@@ -66,10 +65,10 @@ func newBestState(
66 65
 // BlockChain provides functions for working with the bitcoin block chain. It includes functionality such as rejecting duplicate blocks, ensuring blocks follow all rules, orphan handling, checkpoint handling, and best chain selection with reorganization.
67 66
 type BlockChain struct {
68 67
 	// 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 separate mutex.
69
-	checkpoints         []chaincfg.Checkpoint
70
-	checkpointsByHeight map[int32]*chaincfg.Checkpoint
68
+	checkpoints         []config.Checkpoint
69
+	checkpointsByHeight map[int32]*config.Checkpoint
71 70
 	db                  database.DB
72
-	chainParams         *chaincfg.Params
71
+	chainParams         *config.Params
73 72
 	timeSource          MedianTimeSource
74 73
 	sigCache            *txscript.SigCache
75 74
 	indexManager        IndexManager
@@ -92,7 +91,7 @@ type BlockChain struct {
92 91
 	prevOrphans  map[chainhash.Hash][]*orphanBlock
93 92
 	oldestOrphan *orphanBlock
94 93
 	// These fields are related to checkpoint handling.  They are protected by the chain lock.
95
-	nextCheckpoint *chaincfg.Checkpoint
94
+	nextCheckpoint *config.Checkpoint
96 95
 	checkpointNode *blockNode
97 96
 	// The state is used as a fairly efficient way to cache information about the current best chain state that is returned to callers when requested.  It operates on the principle of MVCC such that any time a new block becomes the best block, the state pointer is replaced with a new struct and the old state is left untouched.  In this way, multiple callers can be pointing to different best chain states. This is acceptable for most callers because the state is only being queried at a specific point in time. In addition, some of the fields are stored in the database so the chain state can be quickly reconstructed on load.
98 97
 	stateLock     sync.RWMutex
@@ -180,7 +179,7 @@ func (b *BlockChain) removeOrphanBlock(orphan *orphanBlock) {
180 179
 }
181 180
 
182 181
 // addOrphanBlock adds the passed block (which is already determined to be an orphan prior calling this function) to the orphan pool.  It lazily cleans up any expired blocks so a separate cleanup poller doesn't need to be run. It also imposes a maximum limit on the number of outstanding orphan blocks and will remove the oldest received orphan block if the limit is exceeded.
183
-func (b *BlockChain) addOrphanBlock(block *util.Block) {
182
+func (b *BlockChain) addOrphanBlock(block *wire.Block) {
184 183
 	// Remove expired orphan blocks.
185 184
 	for _, oBlock := range b.orphans {
186 185
 		if time.Now().After(oBlock.expiration) {
@@ -220,14 +219,14 @@ type SequenceLock struct {
220 219
 }
221 220
 
222 221
 // CalcSequenceLock computes a relative lock-time SequenceLock for the passed transaction using the passed UtxoViewpoint to obtain the past median time for blocks in which the referenced inputs of the transactions were included within. The generated SequenceLock lock can be used in conjunction with a block height, and adjusted median block time to determine if all the inputs referenced within a transaction have reached sufficient maturity allowing the candidate transaction to be included in a block. This function is safe for concurrent access.
223
-func (b *BlockChain) CalcSequenceLock(tx *util.Tx, utxoView *UtxoViewpoint, mempool bool) (*SequenceLock, error) {
222
+func (b *BlockChain) CalcSequenceLock(tx *wire.Tx, utxoView *UtxoViewpoint, mempool bool) (*SequenceLock, error) {
224 223
 	b.chainLock.Lock()
225 224
 	defer b.chainLock.Unlock()
226 225
 	return b.calcSequenceLock(b.bestChain.Tip(), tx, utxoView, mempool)
227 226
 }
228 227
 
229 228
 // calcSequenceLock computes the relative lock-times for the passed transaction. See the exported version, CalcSequenceLock for further details. This function MUST be called with the chain state lock held (for writes).
230
-func (b *BlockChain) calcSequenceLock(node *blockNode, tx *util.Tx, utxoView *UtxoViewpoint, mempool bool) (*SequenceLock, error) {
229
+func (b *BlockChain) calcSequenceLock(node *blockNode, tx *wire.Tx, utxoView *UtxoViewpoint, mempool bool) (*SequenceLock, error) {
231 230
 	// A value of -1 for each relative lock type represents a relative time lock value that will allow a transaction to be included in a block at any given height or time. This value is returned as the relative lock time in the case that BIP 68 is disabled, or has not yet been activated.
232 231
 	sequenceLock := &SequenceLock{Seconds: -1, BlockHeight: -1}
233 232
 	// The sequence locks semantics are always active for transactions within the mempool.
@@ -235,7 +234,7 @@ func (b *BlockChain) calcSequenceLock(node *blockNode, tx *util.Tx, utxoView *Ut
235 234
 	// If we're performing block validation, then we need to query the BIP9 state.
236 235
 	if !csvSoftforkActive {
237 236
 		// Obtain the latest BIP9 version bits state for the CSV-package soft-fork deployment. The adherence of sequence locks depends on the current soft-fork state.
238
-		csvState, err := b.deploymentState(node.parent, chaincfg.DeploymentCSV)
237
+		csvState, err := b.deploymentState(node.parent, config.DeploymentCSV)
239 238
 		if err != nil {
240 239
 			return nil, err
241 240
 		}
@@ -348,7 +347,7 @@ func (b *BlockChain) getReorganizeNodes(node *blockNode) (*list.List, *list.List
348 347
 
349 348
 // connectBlock handles connecting the passed node/block to the end of the main (best) chain.
350 349
 // This passed utxo view must have all referenced txos the block spends marked as spent and all of the new txos the block creates added to it.  In addition, the passed stxos slice must be populated with all of the information for the spent txos.  This approach is used because the connection validation that must happen prior to calling this function requires the same details, so it would be inefficient to repeat it. This function MUST be called with the chain state lock held (for writes).
351
-func (b *BlockChain) connectBlock(node *blockNode, block *util.Block,
350
+func (b *BlockChain) connectBlock(node *blockNode, block *wire.Block,
352 351
 	view *UtxoViewpoint, stxos []SpentTxOut) error {
353 352
 	// Make sure it's extending the end of the best chain.
354 353
 	prevHash := &block.MsgBlock().Header.PrevBlock
@@ -443,7 +442,7 @@ func (b *BlockChain) connectBlock(node *blockNode, block *util.Block,
443 442
 }
444 443
 
445 444
 // disconnectBlock handles disconnecting the passed node/block from the end of the main (best) chain. This function MUST be called with the chain state lock held (for writes).
446
-func (b *BlockChain) disconnectBlock(node *blockNode, block *util.Block, view *UtxoViewpoint) error {
445
+func (b *BlockChain) disconnectBlock(node *blockNode, block *wire.Block, view *UtxoViewpoint) error {
447 446
 	// Make sure the node being disconnected is the end of the best chain.
448 447
 	if !node.hash.IsEqual(&b.bestChain.Tip().hash) {
449 448
 		return AssertError(
@@ -452,7 +451,7 @@ func (b *BlockChain) disconnectBlock(node *blockNode, block *util.Block, view *U
452 451
 	}
453 452
 	// Load the previous block since some details for it are needed below.
454 453
 	prevNode := node.parent
455
-	var prevBlock *util.Block
454
+	var prevBlock *wire.Block
456 455
 	err := b.db.View(func(dbTx database.Tx) error {
457 456
 		var err error
458 457
 		prevBlock, err = dbFetchBlockByNode(dbTx, prevNode)
@@ -531,7 +530,7 @@ func (b *BlockChain) disconnectBlock(node *blockNode, block *util.Block, view *U
531 530
 
532 531
 // countSpentOutputs returns the number of utxos the passed block spends.
533 532
 func countSpentOutputs(
534
-	block *util.Block) int {
533
+	block *wire.Block) int {
535 534
 	// Exclude the coinbase transaction since it can't spend anything.
536 535
 	var numSpent int
537 536
 	for _, tx := range block.Transactions()[1:] {
@@ -570,15 +569,15 @@ func (b *BlockChain) reorganizeChain(detachNodes, attachNodes *list.List) error
570 569
 	oldBest := tip
571 570
 	newBest := tip
572 571
 	// All of the blocks to detach and related spend journal entries needed to unspend transaction outputs in the blocks being disconnected must be loaded from the database during the reorg check phase below and then they are needed again when doing the actual database updates. Rather than doing two loads, cache the loaded data into these slices.
573
-	detachBlocks := make([]*util.Block, 0, detachNodes.Len())
572
+	detachBlocks := make([]*wire.Block, 0, detachNodes.Len())
574 573
 	detachSpentTxOuts := make([][]SpentTxOut, 0, detachNodes.Len())
575
-	attachBlocks := make([]*util.Block, 0, attachNodes.Len())
574
+	attachBlocks := make([]*wire.Block, 0, attachNodes.Len())
576 575
 	// Disconnect all of the blocks back to the point of the fork.  This entails loading the blocks and their associated spent txos from the database and using that information to unspend all of the spent txos and remove the utxos created by the blocks.
577 576
 	view := NewUtxoViewpoint()
578 577
 	view.SetBestHash(&oldBest.hash)
579 578
 	for e := detachNodes.Front(); e != nil; e = e.Next() {
580 579
 		n := e.Value.(*blockNode)
581
-		var block *util.Block
580
+		var block *wire.Block
582 581
 		err := b.db.View(func(dbTx database.Tx) error {
583 582
 			var err error
584 583
 			block, err = dbFetchBlockByNode(dbTx, n)
@@ -625,7 +624,7 @@ func (b *BlockChain) reorganizeChain(detachNodes, attachNodes *list.List) error
625 624
 	// NOTE: These checks could be done directly when connecting a block, however the downside to that approach is that if any of these checks fail after disconnecting some blocks or attaching others, all of the operations have to be rolled back to get the chain back into the state it was before the rule violation (or other failure). There are at least a couple of ways accomplish that rollback, but both involve tweaking the chain and/or database.  This approach catches these issues before ever modifying the chain.
626 625
 	for e := attachNodes.Front(); e != nil; e = e.Next() {
627 626
 		n := e.Value.(*blockNode)
628
-		var block *util.Block
627
+		var block *wire.Block
629 628
 		err := b.db.View(func(dbTx database.Tx) error {
630 629
 			var err error
631 630
 			block, err = dbFetchBlockByNode(dbTx, n)
@@ -738,7 +737,7 @@ func (b *BlockChain) reorganizeChain(detachNodes, attachNodes *list.List) error
738 737
 //  - BFFastAdd: Avoids several expensive transaction validation operations.
739 738
 //    This is useful when using checkpoints.
740 739
 // This function MUST be called with the chain state lock held (for writes).
741
-func (b *BlockChain) connectBestChain(node *blockNode, block *util.Block, flags BehaviorFlags) (bool, error) {
740
+func (b *BlockChain) connectBestChain(node *blockNode, block *wire.Block, flags BehaviorFlags) (bool, error) {
742 741
 	fastAdd := flags&BFFastAdd == BFFastAdd
743 742
 	flushIndexState := func() {
744 743
 		// Intentionally ignore errors writing updated node status to DB. If it fails to write, it's not the end of the world. If the block is valid, we flush in connectBlock and if the block is invalid, the worst that can happen is we revalidate the block after a restart.
@@ -1134,9 +1133,9 @@ type IndexManager interface {
1134 1133
 	// Init is invoked during chain 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 behavior is not desired.
1135 1134
 	Init(*BlockChain, <-chan struct{}) error
1136 1135
 	// ConnectBlock is invoked when a new block has been connected to the main chain. The set of output spent within a block is also passed in so indexers can access the previous output scripts input spent if required.
1137
-	ConnectBlock(database.Tx, *util.Block, []SpentTxOut) error
1136
+	ConnectBlock(database.Tx, *wire.Block, []SpentTxOut) error
1138 1137
 	// DisconnectBlock is invoked when a block has been disconnected from the main chain. The set of outputs scripts that were spent within this block is also returned so indexers can clean up the prior index state for this block.
1139
-	DisconnectBlock(database.Tx, *util.Block, []SpentTxOut) error
1138
+	DisconnectBlock(database.Tx, *wire.Block, []SpentTxOut) error
1140 1139
 }
1141 1140
 
1142 1141
 // Config is a descriptor which specifies the blockchain instance configuration.
@@ -1146,9 +1145,9 @@ type Config struct {
1146 1145
 	// Interrupt specifies a channel the caller can close to signal that long running operations, such as catching up indexes or performing database migrations, should be interrupted. This field can be nil if the caller does not desire the behavior.
1147 1146
 	Interrupt <-chan struct{}
1148 1147
 	// ChainParams identifies which chain parameters the chain is associated with. This field is required.
1149
-	ChainParams *chaincfg.Params
1148
+	ChainParams *config.Params
1150 1149
 	// Checkpoints hold caller-defined checkpoints that should be added to the default checkpoints in ChainParams.  Checkpoints must be sorted by height. This field can be nil if the caller does not wish to specify any checkpoints.
1151
-	Checkpoints []chaincfg.Checkpoint
1150
+	Checkpoints []config.Checkpoint
1152 1151
 	// TimeSource defines the median time source to use for things such as block processing and determining whether or not the chain 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 time is adjusted to be in agreement with other peers.
1153 1152
 	TimeSource MedianTimeSource
1154 1153
 	// SigCache defines a signature cache to use when when validating signatures.  This is typically most useful when individual transactions are already being validated prior to their inclusion in a block such as what is usually done via a transaction memory pool. This field can be nil if the caller is not interested in using a signature cache.
@@ -1161,24 +1160,24 @@ type Config struct {
1161 1160
 
1162 1161
 // New returns a BlockChain instance using the provided configuration details.
1163 1162
 func New(
1164
-	config *Config) (*BlockChain, error) {
1163
+	cfg *Config) (*BlockChain, error) {
1165 1164
 	// Enforce required config fields.
1166
-	if config.DB == nil {
1165
+	if cfg.DB == nil {
1167 1166
 		return nil, AssertError("blockchain.New database is nil")
1168 1167
 	}
1169
-	if config.ChainParams == nil {
1168
+	if cfg.ChainParams == nil {
1170 1169
 		return nil, AssertError("blockchain.New chain parameters nil")
1171 1170
 	}
1172
-	if config.TimeSource == nil {
1171
+	if cfg.TimeSource == nil {
1173 1172
 		return nil, AssertError("blockchain.New timesource is nil")
1174 1173
 	}
1175 1174
 	// Generate a checkpoint by height map from the provided checkpoints and assert the provided checkpoints are sorted by height as required.
1176
-	var checkpointsByHeight map[int32]*chaincfg.Checkpoint
1175
+	var checkpointsByHeight map[int32]*config.Checkpoint
1177 1176
 	var prevCheckpointHeight int32
1178
-	if len(config.Checkpoints) > 0 {
1179
-		checkpointsByHeight = make(map[int32]*chaincfg.Checkpoint)
1180
-		for i := range config.Checkpoints {
1181
-			checkpoint := &config.Checkpoints[i]
1177
+	if len(cfg.Checkpoints) > 0 {
1178
+		checkpointsByHeight = make(map[int32]*config.Checkpoint)
1179
+		for i := range cfg.Checkpoints {
1180
+			checkpoint := &cfg.Checkpoints[i]
1182 1181
 			if checkpoint.Height <= prevCheckpointHeight {
1183 1182
 				return nil, AssertError(
1184 1183
 					"blockchain.New checkpoints are not sorted by height")
@@ -1187,28 +1186,28 @@ func New(
1187 1186
 			prevCheckpointHeight = checkpoint.Height
1188 1187
 		}
1189 1188
 	}
1190
-	params := config.ChainParams
1189
+	params := cfg.ChainParams
1191 1190
 	targetTimespan := int64(params.TargetTimespan)
1192 1191
 	targetTimePerBlock := int64(params.TargetTimePerBlock)
1193 1192
 	adjustmentFactor := params.RetargetAdjustmentFactor
1194 1193
 	b := BlockChain{
1195
-		checkpoints:           config.Checkpoints,
1194
+		checkpoints:           cfg.Checkpoints,
1196 1195
 		checkpointsByHeight:   checkpointsByHeight,
1197
-		db:                    config.DB,
1196
+		db:                    cfg.DB,
1198 1197
 		chainParams:           params,
1199
-		timeSource:            config.TimeSource,
1200
-		sigCache:              config.SigCache,
1201
-		indexManager:          config.IndexManager,
1198
+		timeSource:            cfg.TimeSource,
1199
+		sigCache:              cfg.SigCache,
1200
+		indexManager:          cfg.IndexManager,
1202 1201
 		minRetargetTimespan:   targetTimespan / adjustmentFactor,
1203 1202
 		maxRetargetTimespan:   targetTimespan * adjustmentFactor,
1204 1203
 		blocksPerRetarget:     int32(targetTimespan / targetTimePerBlock),
1205
-		Index:                 newBlockIndex(config.DB, params),
1206
-		hashCache:             config.HashCache,
1204
+		Index:                 newBlockIndex(cfg.DB, params),
1205
+		hashCache:             cfg.HashCache,
1207 1206
 		bestChain:             newChainView(nil),
1208 1207
 		orphans:               make(map[chainhash.Hash]*orphanBlock),
1209 1208
 		prevOrphans:           make(map[chainhash.Hash][]*orphanBlock),
1210 1209
 		warningCaches:         newThresholdCaches(vbNumBits),
1211
-		deploymentCaches:      newThresholdCaches(chaincfg.DefinedDeployments),
1210
+		deploymentCaches:      newThresholdCaches(config.DefinedDeployments),
1212 1211
 		DifficultyAdjustments: make(map[string]float64),
1213 1212
 	}
1214 1213
 	// Initialize the chain state from the passed database.  When the db does not yet contain any chain state, both it and the chain state will be initialized to contain only the genesis block.
@@ -1216,12 +1215,12 @@ func New(
1216 1215
 		return nil, err
1217 1216
 	}
1218 1217
 	// Perform any upgrades to the various chain-specific buckets as needed.
1219
-	if err := b.maybeUpgradeDbBuckets(config.Interrupt); err != nil {
1218
+	if err := b.maybeUpgradeDbBuckets(cfg.Interrupt); err != nil {
1220 1219
 		return nil, err
1221 1220
 	}
1222 1221
 	// Initialize and catch up all of the currently active optional indexes as needed.
1223
-	if config.IndexManager != nil {
1224
-		err := config.IndexManager.Init(&b, config.Interrupt)
1222
+	if cfg.IndexManager != nil {
1223
+		err := cfg.IndexManager.Init(&b, cfg.Interrupt)
1225 1224
 		if err != nil {
1226 1225
 			return nil, err
1227 1226
 		}

+ 12
- 13
pkg/chain/chainio.go View File

@@ -12,7 +12,6 @@ import (
12 12
 	chainhash "git.parallelcoin.io/dev/9/pkg/chain/hash"
13 13
 	"git.parallelcoin.io/dev/9/pkg/chain/wire"
14 14
 	database "git.parallelcoin.io/dev/9/pkg/db"
15
-	"git.parallelcoin.io/dev/9/pkg/util"
16 15
 	cl "git.parallelcoin.io/dev/9/pkg/util/cl"
17 16
 )
18 17
 
@@ -178,7 +177,7 @@ type SpentTxOut struct {
178 177
 }
179 178
 
180 179
 // FetchSpendJournal attempts to retrieve the spend journal, or the set of outputs spent for the target block. This provides a view of all the outputs that will be consumed once the target block is connected to the end of the main chain. This function is safe for concurrent access.
181
-func (b *BlockChain) FetchSpendJournal(targetBlock *util.Block) ([]SpentTxOut, error) {
180
+func (b *BlockChain) FetchSpendJournal(targetBlock *wire.Block) ([]SpentTxOut, error) {
182 181
 	b.chainLock.RLock()
183 182
 	defer b.chainLock.RUnlock()
184 183
 	var spendEntries []SpentTxOut
@@ -336,7 +335,7 @@ func serializeSpendJournalEntry(
336 335
 
337 336
 // dbFetchSpendJournalEntry fetches the spend journal entry for the passed block and deserializes it into a slice of spent txout entries. NOTE: Legacy entries will not have the coinbase flag or height set unless it was the final output spend in the containing transaction.  It is up to the caller to handle this properly by looking the information up in the utxo set.
338 337
 func dbFetchSpendJournalEntry(
339
-	dbTx database.Tx, block *util.Block) ([]SpentTxOut, error) {
338
+	dbTx database.Tx, block *wire.Block) ([]SpentTxOut, error) {
340 339
 	// Exclude the coinbase transaction since it can't spend anything.
341 340
 	spendBucket := dbTx.Metadata().Bucket(spendJournalBucketName)
342 341
 	serialized := spendBucket.Get(block.Hash()[:])
@@ -784,7 +783,7 @@ func dbPutBestState(
784 783
 // createChainState initializes both the database and the chain state to the genesis block.  This includes creating the necessary buckets and inserting the genesis block, so it must only be called on an uninitialized database.
785 784
 func (b *BlockChain) createChainState() error {
786 785
 	// Create a new node from the genesis block and set it as the best node.
787
-	genesisBlock := util.NewBlock(b.chainParams.GenesisBlock)
786
+	genesisBlock := wire.NewBlock(b.chainParams.GenesisBlock)
788 787
 	log <- cl.Tracec(func() string {
789 788
 		xx, _ := genesisBlock.Bytes()
790 789
 		return hex.EncodeToString(xx)
@@ -974,7 +973,7 @@ func (b *BlockChain) initChainState() error {
974 973
 		}
975 974
 		// Initialize the state related to the best block.
976 975
 		blockSize := uint64(len(blockBytes))
977
-		blockWeight := uint64(GetBlockWeight(util.NewBlock(&block)))
976
+		blockWeight := uint64(GetBlockWeight(wire.NewBlock(&block)))
978 977
 		numTxns := uint64(len(block.Transactions))
979 978
 		b.stateSnapshot = newBestState(tip, blockSize, blockWeight,
980 979
 			numTxns, state.totalTxns, tip.CalcPastMedianTime())
@@ -1028,16 +1027,16 @@ func dbFetchHeaderByHeight(
1028 1027
 	return dbFetchHeaderByHash(dbTx, hash)
1029 1028
 }
1030 1029
 
1031
-// dbFetchBlockByNode uses an existing database transaction to retrieve the raw block for the provided node, deserialize it, and return a util.Block with the height set.
1030
+// dbFetchBlockByNode uses an existing database transaction to retrieve the raw block for the provided node, deserialize it, and return a wire.Block with the height set.
1032 1031
 func dbFetchBlockByNode(
1033
-	dbTx database.Tx, node *blockNode) (*util.Block, error) {
1032
+	dbTx database.Tx, node *blockNode) (*wire.Block, error) {
1034 1033
 	// Load the raw block bytes from the database.
1035 1034
 	blockBytes, err := dbTx.FetchBlock(&node.hash)
1036 1035
 	if err != nil {
1037 1036
 		return nil, err
1038 1037
 	}
1039 1038
 	// Create the encapsulated block and set the height appropriately.
1040
-	block, err := util.NewBlockFromBytes(blockBytes)
1039
+	block, err := wire.NewBlockFromBytes(blockBytes)
1041 1040
 	if err != nil {
1042 1041
 		return nil, err
1043 1042
 	}
@@ -1068,7 +1067,7 @@ func dbStoreBlockNode(
1068 1067
 
1069 1068
 // dbStoreBlock stores the provided block in the database if it is not already there. The full block data is written to ffldb.
1070 1069
 func dbStoreBlock(
1071
-	dbTx database.Tx, block *util.Block) error {
1070
+	dbTx database.Tx, block *wire.Block) error {
1072 1071
 	hasBlock, err := dbTx.HasBlock(block.Hash())
1073 1072
 	if err != nil {
1074 1073
 		return err
@@ -1089,7 +1088,7 @@ func blockIndexKey(
1089 1088
 }
1090 1089
 
1091 1090
 // BlockByHeight returns the block at the given height in the main chain. This function is safe for concurrent access.
1092
-func (b *BlockChain) BlockByHeight(blockHeight int32) (*util.Block, error) {
1091
+func (b *BlockChain) BlockByHeight(blockHeight int32) (*wire.Block, error) {
1093 1092
 	// Lookup the block height in the best chain.
1094 1093
 	node := b.bestChain.NodeByHeight(blockHeight)
1095 1094
 	if node == nil {
@@ -1097,7 +1096,7 @@ func (b *BlockChain) BlockByHeight(blockHeight int32) (*util.Block, error) {
1097 1096
 		return nil, errNotInMainChain(str)
1098 1097
 	}
1099 1098
 	// Load the block from the database and return it.
1100
-	var block *util.Block
1099
+	var block *wire.Block
1101 1100
 	err := b.db.View(func(dbTx database.Tx) error {
1102 1101
 		var err error
1103 1102
 		block, err = dbFetchBlockByNode(dbTx, node)
@@ -1107,7 +1106,7 @@ func (b *BlockChain) BlockByHeight(blockHeight int32) (*util.Block, error) {
1107 1106
 }
1108 1107
 
1109 1108
 // BlockByHash returns the block from the main chain with the given hash with the appropriate chain height set. This function is safe for concurrent access.
1110
-func (b *BlockChain) BlockByHash(hash *chainhash.Hash) (*util.Block, error) {
1109
+func (b *BlockChain) BlockByHash(hash *chainhash.Hash) (*wire.Block, error) {
1111 1110
 	// Lookup the block hash in block index and ensure it is in the best chain.
1112 1111
 	node := b.Index.LookupNode(hash)
1113 1112
 	if node == nil || !b.bestChain.Contains(node) {
@@ -1115,7 +1114,7 @@ func (b *BlockChain) BlockByHash(hash *chainhash.Hash) (*util.Block, error) {
1115 1114
 		return nil, errNotInMainChain(str)
1116 1115
 	}
1117 1116
 	// Load the block from the database and return it.
1118
-	var block *util.Block
1117
+	var block *wire.Block
1119 1118
 	err := b.db.View(func(dbTx database.Tx) error {
1120 1119
 		var err error
1121 1120
 		block, err = dbFetchBlockByNode(dbTx, node)

+ 3
- 3
pkg/chain/checkpoints.go View File

@@ -7,7 +7,7 @@ import (
7 7
 	chaincfg "git.parallelcoin.io/dev/9/pkg/chain/config"
8 8
 	chainhash "git.parallelcoin.io/dev/9/pkg/chain/hash"
9 9
 	txscript "git.parallelcoin.io/dev/9/pkg/chain/tx/script"
10
-	"git.parallelcoin.io/dev/9/pkg/util"
10
+	"git.parallelcoin.io/dev/9/pkg/chain/wire"
11 11
 	cl "git.parallelcoin.io/dev/9/pkg/util/cl"
12 12
 )
13 13
 
@@ -120,7 +120,7 @@ func (b *BlockChain) findPreviousCheckpoint() (*blockNode, error) {
120 120
 
121 121
 // isNonstandardTransaction determines whether a transaction contains any scripts which are not one of the standard types.
122 122
 func isNonstandardTransaction(
123
-	tx *util.Tx) bool {
123
+	tx *wire.Tx) bool {
124 124
 	// Check all of the output public key scripts for non-standard scripts.
125 125
 	for _, txOut := range tx.MsgTx().TxOut {
126 126
 		scriptClass := txscript.GetScriptClass(txOut.PkScript)
@@ -142,7 +142,7 @@ func isNonstandardTransaction(
142 142
 //  - The block must not contain any strange transaction such as those with
143 143
 //    nonstandard scripts
144 144
 // The intent is that candidates are reviewed by a developer to make the final decision and then manually added to the list of checkpoints for a network. This function is safe for concurrent access.
145
-func (b *BlockChain) IsCheckpointCandidate(block *util.Block) (bool, error) {
145
+func (b *BlockChain) IsCheckpointCandidate(block *wire.Block) (bool, error) {
146 146
 	b.chainLock.RLock()
147 147
 	defer b.chainLock.RUnlock()
148 148
 	// A checkpoint must be in the main chain.

+ 0
- 58
pkg/chain/config/README.md View File

@@ -1,58 +0,0 @@
1
-# chaincfg
2
-
3
-[![ISC License](http://img.shields.io/badge/license-ISC-blue.svg)](http://copyfree.org)
4
-[![GoDoc](https://img.shields.io/badge/godoc-reference-blue.svg)](http://godoc.org/git.parallelcoin.io/dev/pod/chaincfg)
5
-
6
-Package chaincfg defines chain configuration parameters for the three standard Parallelcoin networks and provides the ability for callers to define their own custom networks.
7
-
8
-Although this package was primarily written for pod, it has intentionally been designed so it can be used as a standalone package for any projects needing to use parameters for the standard Bitcoin networks or for projects needing to define their own network.
9
-
10
-## Sample Use
11
-
12
-```Go
13
-package main
14
-import (
15
-	"flag"
16
-	"fmt"
17
-	"log"
18
-	"git.parallelcoin.io/util"
19
-	"git.parallelcoin.io/dev/9/pkg/chain/config"
20
-)
21
-var testnet = flag.Bool("testnet", false, "operate on the testnet Bitcoin network")
22
-// By default (without -testnet), use mainnet.
23
-var chainParams = &chaincfg.MainNetParams
24
-func main(
25
-	) {
26
-
27
-
28
-	flag.Parse()
29
-
30
-	// Modify active network parameters if operating on testnet.
31
-	if *testnet {
32
-		
33
-chainParams = &chaincfg.TestNet3Params
34
-	}
35
-
36
-	// later...
37
-
38
-	// Create and print new payment address, specific to the active network.
39
-	pubKeyHash := make([]byte, 20)
40
-	addr, err := btcutil.NewAddressPubKeyHash(pubKeyHash, chainParams)
41
-	if err != nil {
42
-		
43
-log.Fatal(err)
44
-	}
45
-	fmt.Println(addr)
46
-}
47
-```
48
-
49
-## Installation and Updating
50
-
51
-```bash
52
-$ go get -u git.parallelcoin.io/dev/pod/chaincfg
53
-```
54
-
55
-## License
56
-
57
-Package chaincfg is licensed under the [copyfree](http://copyfree.org) ISC
58
-License.

pkg/util/address.go → pkg/chain/config/address.go View File

@@ -1,4 +1,4 @@
1
-package util
1
+package config
2 2
 
3 3
 import (
4 4
 	"bytes"
@@ -7,7 +7,7 @@ import (
7 7
 	"fmt"
8 8
 	"strings"
9 9
 
10
-	chaincfg "git.parallelcoin.io/dev/9/pkg/chain/config"
10
+	"git.parallelcoin.io/dev/9/pkg/util"
11 11
 	"git.parallelcoin.io/dev/9/pkg/util/base58"
12 12
 	"git.parallelcoin.io/dev/9/pkg/util/bech32"
13 13
 	ec "git.parallelcoin.io/dev/9/pkg/util/elliptic"
@@ -31,7 +31,7 @@ func (e UnsupportedWitnessProgLenError) Error() string {
31 31
 var (
32 32
 	// ErrChecksumMismatch describes an error where decoding failed due to a bad checksum.
33 33
 	ErrChecksumMismatch = errors.New("checksum mismatch")
34
-	// ErrUnknownAddressType describes an error where an address can not decoded as a specific address type due to the string encoding begining with an identifier byte unknown to any standard or registered (via chaincfg.Register) network.
34
+	// ErrUnknownAddressType describes an error where an address can not decoded as a specific address type due to the string encoding begining with an identifier byte unknown to any standard or registered (via Register) network.
35 35
 	ErrUnknownAddressType = errors.New("unknown address type")
36 36
 	// ErrAddressCollision describes an error where an address can not be uniquely determined as either a pay-to-pubkey-hash or pay-to-script-hash address since the leading identifier is used for describing both address kinds, but for different networks.  Rather than assuming or defaulting to one or the other, this error is returned and the caller must decide how to decode the address.
37 37
 	ErrAddressCollision = errors.New("address collision")
@@ -82,17 +82,16 @@ type Address interface {
82 82
 	// ScriptAddress returns the raw bytes of the address to be used when inserting the address into a txout's script.
83 83
 	ScriptAddress() []byte
84 84
 	// IsForNet returns whether or not the address is associated with the passed bitcoin network.
85
-	IsForNet(*chaincfg.Params) bool
85
+	IsForNet(*Params) bool
86 86
 }
87 87
 
88 88
 // DecodeAddress decodes the string encoding of an address and returns the Address if addr is a valid encoding for a known address type. The bitcoin network the address is associated with is extracted if possible. When the address does not encode the network, such as in the case of a raw public key, the address will be associated with the passed defaultNet.
89
-func DecodeAddress(
90
-	addr string, defaultNet *chaincfg.Params) (Address, error) {
89
+func DecodeAddress(addr string, defaultNet *Params) (Address, error) {
91 90
 	// Bech32 encoded segwit addresses start with a human-readable part (hrp) followed by '1'. For Bitcoin mainnet the hrp is "bc", and for testnet it is "tb". If the address string has a prefix that matches one of the prefixes for the known networks, we try to decode it as a segwit address.
92 91
 	oneIndex := strings.LastIndexByte(addr, '1')
93 92
 	if oneIndex > 1 {
94 93
 		prefix := addr[:oneIndex+1]
95
-		if chaincfg.IsBech32SegwitPrefix(prefix) {
94
+		if IsBech32SegwitPrefix(prefix) {
96 95
 			witnessVer, witnessProg, err := decodeSegWitAddress(addr)
97 96
 			if err != nil {
98 97
 				return nil, err
@@ -131,8 +130,8 @@ func DecodeAddress(
131 130
 	}
132 131
 	switch len(decoded) {
133 132
 	case ripemd160.Size: // P2PKH or P2SH
134
-		isP2PKH := chaincfg.IsPubKeyHashAddrID(netID)
135
-		isP2SH := chaincfg.IsScriptHashAddrID(netID)
133
+		isP2PKH := IsPubKeyHashAddrID(netID)
134
+		isP2SH := IsScriptHashAddrID(netID)
136 135
 		switch hash160 := decoded; {
137 136
 		case isP2PKH && isP2SH:
138 137
 			return nil, ErrAddressCollision
@@ -190,7 +189,7 @@ type AddressPubKeyHash struct {
190 189
 
191 190
 // NewAddressPubKeyHash returns a new AddressPubKeyHash.  pkHash must be 20 bytes.
192 191
 func NewAddressPubKeyHash(
193
-	pkHash []byte, net *chaincfg.Params) (*AddressPubKeyHash, error) {
192
+	pkHash []byte, net *Params) (*AddressPubKeyHash, error) {
194 193
 	return newAddressPubKeyHash(pkHash, net.PubKeyHashAddrID)
195 194
 }
196 195
 
@@ -217,7 +216,7 @@ func (a *AddressPubKeyHash) ScriptAddress() []byte {
217 216
 }
218 217
 
219 218
 // IsForNet returns whether or not the pay-to-pubkey-hash address is associated with the passed bitcoin network.
220
-func (a *AddressPubKeyHash) IsForNet(net *chaincfg.Params) bool {
219
+func (a *AddressPubKeyHash) IsForNet(net *Params) bool {
221 220
 	return a.netID == net.PubKeyHashAddrID
222 221
 }
223 222
 
@@ -239,14 +238,14 @@ type AddressScriptHash struct {
239 238
 
240 239
 // NewAddressScriptHash returns a new AddressScriptHash.
241 240
 func NewAddressScriptHash(
242
-	serializedScript []byte, net *chaincfg.Params) (*AddressScriptHash, error) {
243
-	scriptHash := Hash160(serializedScript)
241
+	serializedScript []byte, net *Params) (*AddressScriptHash, error) {
242
+	scriptHash := util.Hash160(serializedScript)
244 243
 	return newAddressScriptHashFromHash(scriptHash, net.ScriptHashAddrID)
245 244
 }
246 245
 
247 246
 // NewAddressScriptHashFromHash returns a new AddressScriptHash.  scriptHash must be 20 bytes.
248 247
 func NewAddressScriptHashFromHash(
249
-	scriptHash []byte, net *chaincfg.Params) (*AddressScriptHash, error) {
248
+	scriptHash []byte, net *Params) (*AddressScriptHash, error) {
250 249
 	return newAddressScriptHashFromHash(scriptHash, net.ScriptHashAddrID)
251 250
 }
252 251
 
@@ -273,7 +272,7 @@ func (a *AddressScriptHash) ScriptAddress() []byte {
273 272
 }
274 273
 
275 274
 // IsForNet returns whether or not the pay-to-script-hash address is associated with the passed bitcoin network.
276
-func (a *AddressScriptHash) IsForNet(net *chaincfg.Params) bool {
275
+func (a *AddressScriptHash) IsForNet(net *Params) bool {
277 276
 	return a.netID == net.ScriptHashAddrID
278 277
 }
279 278
 
@@ -308,7 +307,7 @@ type AddressPubKey struct {
308 307
 
309 308
 // NewAddressPubKey returns a new AddressPubKey which represents a pay-to-pubkey address.  The serializedPubKey parameter must be a valid pubkey and can be uncompressed, compressed, or hybrid.
310 309
 func NewAddressPubKey(
311
-	serializedPubKey []byte, net *chaincfg.Params) (*AddressPubKey, error) {
310
+	serializedPubKey []byte, net *Params) (*AddressPubKey, error) {
312 311
 	pubKey, err := ec.ParsePubKey(serializedPubKey, ec.S256())
313 312
 	if err != nil {
314 313
 		return nil, err
@@ -345,7 +344,7 @@ func (a *AddressPubKey) serialize() []byte {
345 344
 
346 345
 // EncodeAddress returns the string encoding of the public key as a pay-to-pubkey-hash.  Note that the public key format (uncompressed, compressed, etc) will change the resulting address.  This is expected since pay-to-pubkey-hash is a hash of the serialized public key which obviously differs with the format.  At the time of this writing, most Bitcoin addresses are pay-to-pubkey-hash constructed from the uncompressed public key. Part of the Address interface.
347 346
 func (a *AddressPubKey) EncodeAddress() string {
348
-	return encodeAddress(Hash160(a.serialize()), a.pubKeyHashID)
347
+	return encodeAddress(util.Hash160(a.serialize()), a.pubKeyHashID)
349 348
 }
350 349
 
351 350
 // ScriptAddress returns the bytes to be included in a txout script to pay to a public key.  Setting the public key format will affect the output of this function accordingly.  Part of the Address interface.
@@ -354,7 +353,7 @@ func (a *AddressPubKey) ScriptAddress() []byte {
354 353
 }
355 354
 
356 355
 // IsForNet returns whether or not the pay-to-pubkey address is associated with the passed bitcoin network.
357
-func (a *AddressPubKey) IsForNet(net *chaincfg.Params) bool {
356
+func (a *AddressPubKey) IsForNet(net *Params) bool {
358 357
 	return a.pubKeyHashID == net.PubKeyHashAddrID
359 358
 }
360 359
 
@@ -376,7 +375,7 @@ func (a *AddressPubKey) SetFormat(pkFormat PubKeyFormat) {
376 375
 // AddressPubKeyHash returns the pay-to-pubkey address converted to a pay-to-pubkey-hash address.  Note that the public key format (uncompressed, compressed, etc) will change the resulting address.  This is expected since pay-to-pubkey-hash is a hash of the serialized public key which obviously differs with the format.  At the time of this writing, most Bitcoin addresses are pay-to-pubkey-hash constructed from the uncompressed public key.
377 376
 func (a *AddressPubKey) AddressPubKeyHash() *AddressPubKeyHash {
378 377
 	addr := &AddressPubKeyHash{netID: a.pubKeyHashID}
379
-	copy(addr.hash[:], Hash160(a.serialize()))
378
+	copy(addr.hash[:], util.Hash160(a.serialize()))
380 379
 	return addr
381 380
 }
382 381
 
@@ -394,7 +393,7 @@ type AddressWitnessPubKeyHash struct {
394 393
 
395 394
 // NewAddressWitnessPubKeyHash returns a new AddressWitnessPubKeyHash.
396 395
 func NewAddressWitnessPubKeyHash(
397
-	witnessProg []byte, net *chaincfg.Params) (*AddressWitnessPubKeyHash, error) {
396
+	witnessProg []byte, net *Params) (*AddressWitnessPubKeyHash, error) {
398 397
 	return newAddressWitnessPubKeyHash(net.Bech32HRPSegwit, witnessProg)
399 398
 }
400 399
 
@@ -430,7 +429,7 @@ func (a *AddressWitnessPubKeyHash) ScriptAddress() []byte {
430 429
 }
431 430
 
432 431
 // IsForNet returns whether or not the AddressWitnessPubKeyHash is associated with the passed bitcoin network. Part of the Address interface.
433
-func (a *AddressWitnessPubKeyHash) IsForNet(net *chaincfg.Params) bool {
432
+func (a *AddressWitnessPubKeyHash) IsForNet(net *Params) bool {
434 433
 	return a.hrp == net.Bech32HRPSegwit
435 434
 }
436 435
 
@@ -468,7 +467,7 @@ type AddressWitnessScriptHash struct {
468 467
 
469 468
 // NewAddressWitnessScriptHash returns a new AddressWitnessPubKeyHash.
470 469
 func NewAddressWitnessScriptHash(
471
-	witnessProg []byte, net *chaincfg.Params) (*AddressWitnessScriptHash, error) {
470
+	witnessProg []byte, net *Params) (*AddressWitnessScriptHash, error) {
472 471
 	return newAddressWitnessScriptHash(net.Bech32HRPSegwit, witnessProg)
473 472
 }
474 473
 
@@ -504,7 +503,7 @@ func (a *AddressWitnessScriptHash) ScriptAddress() []byte {
504 503
 }
505 504
 
506 505
 // IsForNet returns whether or not the AddressWitnessScriptHash is associated with the passed bitcoin network. Part of the Address interface.
507
-func (a *AddressWitnessScriptHash) IsForNet(net *chaincfg.Params) bool {
506
+func (a *AddressWitnessScriptHash) IsForNet(net *Params) bool {
508 507
 	return a.hrp == net.Bech32HRPSegwit
509 508
 }
510 509
 

+ 0
- 37
pkg/chain/config/doc.go View File

@@ -1,37 +0,0 @@
1
-// Package chaincfg defines chain configuration parameters.
2
-//
3
-// In addition to the main Bitcoin network, which is intended for the transfer of monetary value, there also exists two currently active standard networks: regression test and testnet (version 3).  These networks are incompatible with each other (each sharing a different genesis block) and software should handle errors where input intended for one network is used on an application instance running on a different network. For library packages, chaincfg provides the ability to lookup chain parameters and encoding magics when passed a *Params.
4
-//
5
-// Older APIs not updated to the new convention of passing a *Params may lookup the parameters for a  wire.BitcoinNet using ParamsForNet, but be aware that this usage is deprecated and will be removed from chaincfg in the future. For main packages, a (typically global) var may be assigned the address of one of the standard Param vars for use as the application's "active" network.
6
-//
7
-// When a network parameter is needed, it may then be looked up through this variable (either directly, or hidden in a library call).
8
-//
9
-//  package main
10
-//  import (
11
-//          "flag"
12
-//          "fmt"
13
-//          "git.parallelcoin.io/dev/9/pkg/util/cl"
14
-//          "git.parallelcoin.io/dev/9/pkg/util"
15
-//          "git.parallelcoin.io/dev/9/pkg/chain/config"
16
-//  )
17
-//  var testnet = flag.Bool("testnet", false, "operate on the testnet Bitcoin network")
18
-//  // By default (without -testnet), use mainnet.
19
-//  var chainParams = &chaincfg.MainNetParams
20
-//  func main() {
21
-//          flag.Parse()
22
-//          // Modify active network parameters if operating on testnet.
23
-//          if *testnet {
24
-//                  chainParams = &chaincfg.TestNet3Params
25
-//          }
26
-//          // later...
27
-//          // Create and print new payment address, specific to the active network.
28
-//          pubKeyHash := make([]byte, 20)
29
-//          addr, err := util.NewAddressPubKeyHash(pubKeyHash, chainParams)
30
-//          if err != nil {
31
-//                  Log.Fatal <- err.Error()
32
-//          }
33
-//          fmt.Println(addr)
34
-//  }
35
-//
36
-// If an application does not use one of the three standard Bitcoin networks, a new Params struct may be created which defines the parameters for the non-standard network.  As a general rule of thumb, all network parameters should be unique to the network, but parameter collisions can still occur (unfortunately, this is the case with regtest and testnet3 sharing magics).
37
-package chaincfg

pkg/chain/config/params/genesis.go → pkg/chain/config/genesis.go View File

@@ -1,4 +1,4 @@
1
-package params
1
+package config
2 2
 
3 3
 import (
4 4
 	"time"

+ 0
- 269
pkg/chain/config/genesis_test.go View File

@@ -1,269 +0,0 @@
1
-//+build test
2
-
3
-package chaincfg
4
-
5
-import (
6
-	"bytes"
7
-	"testing"
8
-
9
-	"github.com/davecgh/go-spew/spew"
10
-)
11
-
12
-// TestGenesisBlock tests the genesis block of the main network for validity by checking the encoded bytes and hashes.
13
-func TestGenesisBlock(
14
-	t *testing.T) {
15
-	// Encode the genesis block to raw bytes.
16
-	var buf bytes.Buffer
17
-	err := MainNetParams.GenesisBlock.Serialize(&buf)
18
-	if err != nil {
19
-		t.Fatalf("TestGenesisBlock: %v", err)
20
-	}
21
-	// Ensure the encoded block matches the expected bytes.
22
-	if !bytes.Equal(buf.Bytes(), genesisBlockBytes) {
23
-		t.Fatalf("TestGenesisBlock: Genesis block does not appear valid - "+
24
-			"got %v, want %v", spew.Sdump(buf.Bytes()),
25
-			spew.Sdump(genesisBlockBytes))
26
-	}
27
-	// Check hash of the block against expected hash.
28
-	hash := MainNetParams.GenesisBlock.BlockHash()
29
-	if !MainNetParams.GenesisHash.IsEqual(&hash) {
30
-		t.Fatalf("TestGenesisBlock: Genesis block hash does not "+
31
-			"appear valid - got %v, want %v", spew.Sdump(hash),
32
-			spew.Sdump(MainNetParams.GenesisHash))
33
-	}
34
-}
35
-
36
-// TestRegTestGenesisBlock tests the genesis block of the regression test network for validity by checking the encoded bytes and hashes.
37
-func TestRegTestGenesisBlock(
38
-	t *testing.T) {
39
-	// Encode the genesis block to raw bytes.
40
-	var buf bytes.Buffer
41
-	err := RegressionNetParams.GenesisBlock.Serialize(&buf)
42
-	if err != nil {
43
-		t.Fatalf("TestRegTestGenesisBlock: %v", err)
44
-	}
45
-	// Ensure the encoded block matches the expected bytes.
46
-	if !bytes.Equal(buf.Bytes(), regTestGenesisBlockBytes) {
47
-		t.Fatalf("TestRegTestGenesisBlock: Genesis block does not "+
48
-			"appear valid - got %v, want %v",
49
-			spew.Sdump(buf.Bytes()),
50
-			spew.Sdump(regTestGenesisBlockBytes))
51
-	}
52
-	// Check hash of the block against expected hash.
53
-	hash := RegressionNetParams.GenesisBlock.BlockHash()
54
-	if !RegressionNetParams.GenesisHash.IsEqual(&hash) {
55
-		t.Fatalf("TestRegTestGenesisBlock: Genesis block hash does "+
56
-			"not appear valid - got %v, want %v", spew.Sdump(hash),
57
-			spew.Sdump(RegressionNetParams.GenesisHash))
58
-	}
59
-}
60
-
61
-// TestTestNet3GenesisBlock tests the genesis block of the test network (version 3) for validity by checking the encoded bytes and hashes.
62
-func TestTestNet3GenesisBlock(
63
-	t *testing.T) {
64
-	// Encode the genesis block to raw bytes.
65
-	var buf bytes.Buffer
66
-	err := TestNet3Params.GenesisBlock.Serialize(&buf)
67
-	if err != nil {
68
-		t.Fatalf("TestTestNet3GenesisBlock: %v", err)
69
-	}
70
-	// Ensure the encoded block matches the expected bytes.
71
-	if !bytes.Equal(buf.Bytes(), testNet3GenesisBlockBytes) {
72
-		t.Fatalf("TestTestNet3GenesisBlock: Genesis block does not "+
73
-			"appear valid - got %v, want %v",
74
-			spew.Sdump(buf.Bytes()),
75
-			spew.Sdump(testNet3GenesisBlockBytes))
76
-	}
77
-	// Check hash of the block against expected hash.
78
-	hash := TestNet3Params.GenesisBlock.BlockHash()
79
-	if !TestNet3Params.GenesisHash.IsEqual(&hash) {
80
-		t.Fatalf("TestTestNet3GenesisBlock: Genesis block hash does "+
81
-			"not appear valid - got %v, want %v", spew.Sdump(hash),
82
-			spew.Sdump(TestNet3Params.GenesisHash))
83
-	}
84
-}
85
-
86
-// TestSimNetGenesisBlock tests the genesis block of the simulation test network for validity by checking the encoded bytes and hashes.
87
-func TestSimNetGenesisBlock(
88
-	t *testing.T) {
89
-	// Encode the genesis block to raw bytes.
90
-	var buf bytes.Buffer
91
-	err := SimNetParams.GenesisBlock.Serialize(&buf)
92
-	if err != nil {
93
-		t.Fatalf("TestSimNetGenesisBlock: %v", err)
94
-	}
95
-	// Ensure the encoded block matches the expected bytes.
96
-	if !bytes.Equal(buf.Bytes(), simNetGenesisBlockBytes) {
97
-		t.Fatalf("TestSimNetGenesisBlock: Genesis block does not "+
98
-			"appear valid - got %v, want %v",
99
-			spew.Sdump(buf.Bytes()),
100
-			spew.Sdump(simNetGenesisBlockBytes))
101
-	}
102
-	// Check hash of the block against expected hash.
103
-	hash := SimNetParams.GenesisBlock.BlockHash()
104
-	if !SimNetParams.GenesisHash.IsEqual(&hash) {
105
-		t.Fatalf("TestSimNetGenesisBlock: Genesis block hash does "+
106
-			"not appear valid - got %v, want %v", spew.Sdump(hash),
107
-			spew.Sdump(SimNetParams.GenesisHash))
108
-	}
109
-}
110
-
111
-// genesisBlockBytes are the wire encoded bytes for the genesis block of the main network as of protocol version 60002.
112
-var genesisBlockBytes = []byte{
113
-	0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* |........| */
114
-	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* |........| */
115
-	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* |........| */
116
-	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* |........| */
117
-	0x00, 0x00, 0x00, 0x00, 0x3b, 0xa3, 0xed, 0xfd, /* |....;...| */
118
-	0x7a, 0x7b, 0x12, 0xb2, 0x7a, 0xc7, 0x2c, 0x3e, /* |z{..z.,>| */
119
-	0x67, 0x76, 0x8f, 0x61, 0x7f, 0xc8, 0x1b, 0xc3, /* |gv.a....| */
120
-	0x88, 0x8a, 0x51, 0x32, 0x3a, 0x9f, 0xb8, 0xaa, /* |..Q2:...| */
121
-	0x4b, 0x1e, 0x5e, 0x4a, 0x29, 0xab, 0x5f, 0x49, /* |K.^J)._I| */
122
-	0xff, 0xff, 0x00, 0x1d, 0x1d, 0xac, 0x2b, 0x7c, /* |......+|| */
123
-	0x01, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, /* |........| */
124
-	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* |........| */
125
-	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* |........| */
126
-	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* |........| */
127
-	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, /* |........| */
128
-	0xff, 0xff, 0x4d, 0x04, 0xff, 0xff, 0x00, 0x1d, /* |..M.....| */
129
-	0x01, 0x04, 0x45, 0x54, 0x68, 0x65, 0x20, 0x54, /* |..EThe T| */
130
-	0x69, 0x6d, 0x65, 0x73, 0x20, 0x30, 0x33, 0x2f, /* |imes 03/| */
131
-	0x4a, 0x61, 0x6e, 0x2f, 0x32, 0x30, 0x30, 0x39, /* |Jan/2009| */
132
-	0x20, 0x43, 0x68, 0x61, 0x6e, 0x63, 0x65, 0x6c, /* | Chancel| */
133
-	0x6c, 0x6f, 0x72, 0x20, 0x6f, 0x6e, 0x20, 0x62, /* |lor on b| */
134
-	0x72, 0x69, 0x6e, 0x6b, 0x20, 0x6f, 0x66, 0x20, /* |rink of | */
135
-	0x73, 0x65, 0x63, 0x6f, 0x6e, 0x64, 0x20, 0x62, /* |second b| */
136
-	0x61, 0x69, 0x6c, 0x6f, 0x75, 0x74, 0x20, 0x66, /* |ailout f| */
137
-	0x6f, 0x72, 0x20, 0x62, 0x61, 0x6e, 0x6b, 0x73, /* |or banks| */
138
-	0xff, 0xff, 0xff, 0xff, 0x01, 0x00, 0xf2, 0x05, /* |........| */
139
-	0x2a, 0x01, 0x00, 0x00, 0x00, 0x43, 0x41, 0x04, /* |*....CA.| */
140
-	0x67, 0x8a, 0xfd, 0xb0, 0xfe, 0x55, 0x48, 0x27, /* |g....UH'| */
141
-	0x19, 0x67, 0xf1, 0xa6, 0x71, 0x30, 0xb7, 0x10, /* |.g..q0..| */
142
-	0x5c, 0xd6, 0xa8, 0x28, 0xe0, 0x39, 0x09, 0xa6, /* |\..(.9..| */
143
-	0x79, 0x62, 0xe0, 0xea, 0x1f, 0x61, 0xde, 0xb6, /* |yb...a..| */
144
-	0x49, 0xf6, 0xbc, 0x3f, 0x4c, 0xef, 0x38, 0xc4, /* |I..?L.8.| */
145
-	0xf3, 0x55, 0x04, 0xe5, 0x1e, 0xc1, 0x12, 0xde, /* |.U......| */
146
-	0x5c, 0x38, 0x4d, 0xf7, 0xba, 0x0b, 0x8d, 0x57, /* |\8M....W| */
147
-	0x8a, 0x4c, 0x70, 0x2b, 0x6b, 0xf1, 0x1d, 0x5f, /* |.Lp+k.._|*/
148
-	0xac, 0x00, 0x00, 0x00, 0x00, /* |.....|    */
149
-}
150
-
151
-// regTestGenesisBlockBytes are the wire encoded bytes for the genesis block of the regression test network as of protocol version 60002.
152
-var regTestGenesisBlockBytes = []byte{
153
-	0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* |........| */
154
-	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* |........| */
155
-	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* |........| */
156
-	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* |........| */
157
-	0x00, 0x00, 0x00, 0x00, 0x3b, 0xa3, 0xed, 0xfd, /* |....;...| */
158
-	0x7a, 0x7b, 0x12, 0xb2, 0x7a, 0xc7, 0x2c, 0x3e, /* |z{..z.,>| */
159
-	0x67, 0x76, 0x8f, 0x61, 0x7f, 0xc8, 0x1b, 0xc3, /* |gv.a....| */
160
-	0x88, 0x8a, 0x51, 0x32, 0x3a, 0x9f, 0xb8, 0xaa, /* |..Q2:...| */
161
-	0x4b, 0x1e, 0x5e, 0x4a, 0xda, 0xe5, 0x49, 0x4d, /* |K.^J)._I| */
162
-	0xff, 0xff, 0x7f, 0x20, 0x02, 0x00, 0x00, 0x00, /* |......+|| */
163
-	0x01, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, /* |........| */
164
-	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* |........| */
165
-	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* |........| */
166
-	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* |........| */
167
-	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, /* |........| */
168
-	0xff, 0xff, 0x4d, 0x04, 0xff, 0xff, 0x00, 0x1d, /* |..M.....| */
169
-	0x01, 0x04, 0x45, 0x54, 0x68, 0x65, 0x20, 0x54, /* |..EThe T| */
170
-	0x69, 0x6d, 0x65, 0x73, 0x20, 0x30, 0x33, 0x2f, /* |imes 03/| */
171
-	0x4a, 0x61, 0x6e, 0x2f, 0x32, 0x30, 0x30, 0x39, /* |Jan/2009| */
172
-	0x20, 0x43, 0x68, 0x61, 0x6e, 0x63, 0x65, 0x6c, /* | Chancel| */
173
-	0x6c, 0x6f, 0x72, 0x20, 0x6f, 0x6e, 0x20, 0x62, /* |lor on b| */
174
-	0x72, 0x69, 0x6e, 0x6b, 0x20, 0x6f, 0x66, 0x20, /* |rink of | */
175
-	0x73, 0x65, 0x63, 0x6f, 0x6e, 0x64, 0x20, 0x62, /* |second b| */
176
-	0x61, 0x69, 0x6c, 0x6f, 0x75, 0x74, 0x20, 0x66, /* |ailout f| */
177
-	0x6f, 0x72, 0x20, 0x62, 0x61, 0x6e, 0x6b, 0x73, /* |or banks| */
178
-	0xff, 0xff, 0xff, 0xff, 0x01, 0x00, 0xf2, 0x05, /* |........| */
179
-	0x2a, 0x01, 0x00, 0x00, 0x00, 0x43, 0x41, 0x04, /* |*....CA.| */
180
-	0x67, 0x8a, 0xfd, 0xb0, 0xfe, 0x55, 0x48, 0x27, /* |g....UH'| */
181
-	0x19, 0x67, 0xf1, 0xa6, 0x71, 0x30, 0xb7, 0x10, /* |.g..q0..| */
182
-	0x5c, 0xd6, 0xa8, 0x28, 0xe0, 0x39, 0x09, 0xa6, /* |\..(.9..| */
183
-	0x79, 0x62, 0xe0, 0xea, 0x1f, 0x61, 0xde, 0xb6, /* |yb...a..| */
184
-	0x49, 0xf6, 0xbc, 0x3f, 0x4c, 0xef, 0x38, 0xc4, /* |I..?L.8.| */
185
-	0xf3, 0x55, 0x04, 0xe5, 0x1e, 0xc1, 0x12, 0xde, /* |.U......| */
186
-	0x5c, 0x38, 0x4d, 0xf7, 0xba, 0x0b, 0x8d, 0x57, /* |\8M....W| */
187
-	0x8a, 0x4c, 0x70, 0x2b, 0x6b, 0xf1, 0x1d, 0x5f, /* |.Lp+k.._|*/
188
-	0xac, 0x00, 0x00, 0x00, 0x00, /* |.....|    */
189
-}
190
-
191
-// testNet3GenesisBlockBytes are the wire encoded bytes for the genesis block of the test network (version 3) as of protocol version 60002.
192
-var testNet3GenesisBlockBytes = []byte{
193
-	0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* |........| */
194
-	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* |........| */
195
-	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* |........| */
196
-	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* |........| */
197
-	0x00, 0x00, 0x00, 0x00, 0x3b, 0xa3, 0xed, 0xfd, /* |....;...| */
198
-	0x7a, 0x7b, 0x12, 0xb2, 0x7a, 0xc7, 0x2c, 0x3e, /* |z{..z.,>| */
199
-	0x67, 0x76, 0x8f, 0x61, 0x7f, 0xc8, 0x1b, 0xc3, /* |gv.a....| */
200
-	0x88, 0x8a, 0x51, 0x32, 0x3a, 0x9f, 0xb8, 0xaa, /* |..Q2:...| */
201
-	0x4b, 0x1e, 0x5e, 0x4a, 0xda, 0xe5, 0x49, 0x4d, /* |K.^J)._I| */
202
-	0xff, 0xff, 0x00, 0x1d, 0x1a, 0xa4, 0xae, 0x18, /* |......+|| */
203
-	0x01, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, /* |........| */
204
-	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* |........| */
205
-	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* |........| */
206
-	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* |........| */
207
-	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, /* |........| */
208
-	0xff, 0xff, 0x4d, 0x04, 0xff, 0xff, 0x00, 0x1d, /* |..M.....| */
209
-	0x01, 0x04, 0x45, 0x54, 0x68, 0x65, 0x20, 0x54, /* |..EThe T| */
210
-	0x69, 0x6d, 0x65, 0x73, 0x20, 0x30, 0x33, 0x2f, /* |imes 03/| */
211
-	0x4a, 0x61, 0x6e, 0x2f, 0x32, 0x30, 0x30, 0x39, /* |Jan/2009| */
212
-	0x20, 0x43, 0x68, 0x61, 0x6e, 0x63, 0x65, 0x6c, /* | Chancel| */
213
-	0x6c, 0x6f, 0x72, 0x20, 0x6f, 0x6e, 0x20, 0x62, /* |lor on b| */
214
-	0x72, 0x69, 0x6e, 0x6b, 0x20, 0x6f, 0x66, 0x20, /* |rink of | */
215
-	0x73, 0x65, 0x63, 0x6f, 0x6e, 0x64, 0x20, 0x62, /* |second b| */
216
-	0x61, 0x69, 0x6c, 0x6f, 0x75, 0x74, 0x20, 0x66, /* |ailout f| */
217
-	0x6f, 0x72, 0x20, 0x62, 0x61, 0x6e, 0x6b, 0x73, /* |or banks| */
218
-	0xff, 0xff, 0xff, 0xff, 0x01, 0x00, 0xf2, 0x05, /* |........| */
219
-	0x2a, 0x01, 0x00, 0x00, 0x00, 0x43, 0x41, 0x04, /* |*....CA.| */
220
-	0x67, 0x8a, 0xfd, 0xb0, 0xfe, 0x55, 0x48, 0x27, /* |g....UH'| */
221
-	0x19, 0x67, 0xf1, 0xa6, 0x71, 0x30, 0xb7, 0x10, /* |.g..q0..| */
222
-	0x5c, 0xd6, 0xa8, 0x28, 0xe0, 0x39, 0x09, 0xa6, /* |\..(.9..| */
223
-	0x79, 0x62, 0xe0, 0xea, 0x1f, 0x61, 0xde, 0xb6, /* |yb...a..| */
224
-	0x49, 0xf6, 0xbc, 0x3f, 0x4c, 0xef, 0x38, 0xc4, /* |I..?L.8.| */
225
-	0xf3, 0x55, 0x04, 0xe5, 0x1e, 0xc1, 0x12, 0xde, /* |.U......| */
226
-	0x5c, 0x38, 0x4d, 0xf7, 0xba, 0x0b, 0x8d, 0x57, /* |\8M....W| */
227
-	0x8a, 0x4c, 0x70, 0x2b, 0x6b, 0xf1, 0x1d, 0x5f, /* |.Lp+k.._|*/
228
-	0xac, 0x00, 0x00, 0x00, 0x00, /* |.....|    */
229
-}
230
-
231
-// simNetGenesisBlockBytes are the wire encoded bytes for the genesis block of the simulation test network as of protocol version 70002.
232
-var simNetGenesisBlockBytes = []byte{
233
-	0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* |........| */
234
-	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* |........| */
235
-	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* |........| */
236
-	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* |........| */
237
-	0x00, 0x00, 0x00, 0x00, 0x3b, 0xa3, 0xed, 0xfd, /* |....;...| */
238
-	0x7a, 0x7b, 0x12, 0xb2, 0x7a, 0xc7, 0x2c, 0x3e, /* |z{..z.,>| */
239
-	0x67, 0x76, 0x8f, 0x61, 0x7f, 0xc8, 0x1b, 0xc3, /* |gv.a....| */
240
-	0x88, 0x8a, 0x51, 0x32, 0x3a, 0x9f, 0xb8, 0xaa, /* |..Q2:...| */
241
-	0x4b, 0x1e, 0x5e, 0x4a, 0x45, 0x06, 0x86, 0x53, /* |K.^J)._I| */
242
-	0xff, 0xff, 0x7f, 0x20, 0x02, 0x00, 0x00, 0x00, /* |......+|| */
243
-	0x01, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, /* |........| */
244
-	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* |........| */
245
-	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* |........| */
246
-	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* |........| */
247
-	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, /* |........| */
248
-	0xff, 0xff, 0x4d, 0x04, 0xff, 0xff, 0x00, 0x1d, /* |..M.....| */
249
-	0x01, 0x04, 0x45, 0x54, 0x68, 0x65, 0x20, 0x54, /* |..EThe T| */
250
-	0x69, 0x6d, 0x65, 0x73, 0x20, 0x30, 0x33, 0x2f, /* |imes 03/| */
251
-	0x4a, 0x61, 0x6e, 0x2f, 0x32, 0x30, 0x30, 0x39, /* |Jan/2009| */
252
-	0x20, 0x43, 0x68, 0x61, 0x6e, 0x63, 0x65, 0x6c, /* | Chancel| */
253
-	0x6c, 0x6f, 0x72, 0x20, 0x6f, 0x6e, 0x20, 0x62, /* |lor on b| */
254
-	0x72, 0x69, 0x6e, 0x6b, 0x20, 0x6f, 0x66, 0x20, /* |rink of | */
255
-	0x73, 0x65, 0x63, 0x6f, 0x6e, 0x64, 0x20, 0x62, /* |second b| */
256
-	0x61, 0x69, 0x6c, 0x6f, 0x75, 0x74, 0x20, 0x66, /* |ailout f| */
257
-	0x6f, 0x72, 0x20, 0x62, 0x61, 0x6e, 0x6b, 0x73, /* |or banks| */
258
-	0xff, 0xff, 0xff, 0xff, 0x01, 0x00, 0xf2, 0x05, /* |........| */
259
-	0x2a, 0x01, 0x00, 0x00, 0x00, 0x43, 0x41, 0x04, /* |*....CA.| */
260
-	0x67, 0x8a, 0xfd, 0xb0, 0xfe, 0x55, 0x48, 0x27, /* |g....UH'| */
261
-	0x19, 0x67, 0xf1, 0xa6, 0x71, 0x30, 0xb7, 0x10, /* |.g..q0..| */
262
-	0x5c, 0xd6, 0xa8, 0x28, 0xe0, 0x39, 0x09, 0xa6, /* |\..(.9..| */
263
-	0x79, 0x62, 0xe0, 0xea, 0x1f, 0x61, 0xde, 0xb6, /* |yb...a..| */
264
-	0x49, 0xf6, 0xbc, 0x3f, 0x4c, 0xef, 0x38, 0xc4, /* |I..?L.8.| */
265
-	0xf3, 0x55, 0x04, 0xe5, 0x1e, 0xc1, 0x12, 0xde, /* |.U......| */
266
-	0x5c, 0x38, 0x4d, 0xf7, 0xba, 0x0b, 0x8d, 0x57, /* |\8M....W| */
267
-	0x8a, 0x4c, 0x70, 0x2b, 0x6b, 0xf1, 0x1d, 0x5f, /* |.Lp+k.._|*/
268
-	0xac, 0x00, 0x00, 0x00, 0x00, /* |.....|    */
269
-}

pkg/chain/config/params/params-defs.go → pkg/chain/config/params-defs.go View File

@@ -1,13 +1,14 @@
1
-package params
1
+package config
2 2
 
3 3
 import (
4 4
 	"encoding/hex"
5 5
 	"errors"
6 6
 	"math/big"
7
-	"time"
7
+	"strings"
8 8
 
9 9
 	chainhash "git.parallelcoin.io/dev/9/pkg/chain/hash"
10
-	"git.parallelcoin.io/dev/9/pkg/chain/wire"
10
+	"git.parallelcoin.io/dev/9/pkg/chain/protocol"
11
+	"git.parallelcoin.io/dev/9/pkg/util"
11 12
 )
12 13
 
13 14
 var (
@@ -15,7 +16,7 @@ var (
15 16
 	ErrDuplicateNet = errors.New("duplicate Bitcoin network")
16 17
 	// ErrUnknownHDKeyID describes an error where the provided id which is intended to identify the network for a hierarchical deterministic private extended key is not registered.
17 18
 	ErrUnknownHDKeyID    = errors.New("unknown hd private extended key bytes")
18
-	registeredNets       = make(map[wire.BitcoinNet]struct{})
19
+	registeredNets       = make(map[protocol.BitcoinNet]struct{})
19 20
 	pubKeyHashAddrIDs    = make(map[byte]struct{})
20 21
 	scriptHashAddrIDs    = make(map[byte]struct{})
21 22
 	bech32SegwitPrefixes = make(map[string]struct{})
@@ -38,7 +39,7 @@ var (
38 39
 	// MainPowLimit is the pre-hardfork pow limit
39 40
 	MainPowLimit = mainPowLimit
40 41
 	// MainPowLimitBits is the bits version of the above
41
-	MainPowLimitBits = BigToCompact(&MainPowLimit)
42
+	MainPowLimitBits = util.BigToCompact(&MainPowLimit)
42 43
 	scryptPowLimit   = func() big.Int {
43 44
 		mplb, _ := hex.DecodeString("0000fffff0000000000000000000000000000000000000000000000000000000")
44 45
 		return *big.NewInt(0).SetBytes(mplb) //AllOnes.Rsh(&AllOnes, 0)
@@ -46,7 +47,7 @@ var (
46 47
 	// ScryptPowLimit is the pre-hardfork maximum hash for Scrypt algorithm
47 48
 	ScryptPowLimit = scryptPowLimit
48 49
 	// ScryptPowLimitBits is the bits version of the above
49
-	ScryptPowLimitBits = BigToCompact(&scryptPowLimit)
50
+	ScryptPowLimitBits = util.BigToCompact(&scryptPowLimit)
50 51
 	// regressionPowLbimit is the highest proof of work value a Bitcoin block can have for the regression test network.  It is the value 2^255 - 1, all ones, 256 bits.
51 52
 	regressionPowLimit = &AllOnes
52 53
 	testnetBits        = ScryptPowLimitBits
@@ -93,7 +94,7 @@ type Checkpoint struct {
93 94
 type DNSSeed struct {
94 95
 	// Host defines the hostname of the seed.
95 96
 	Host string
96
-	// HasFiltering defines whether the seed supports filtering by service flags (wire.ServiceFlag).
97
+	// HasFiltering defines whether the seed supports filtering by service flags (params.ServiceFlag).
97 98
 	HasFiltering bool
98 99
 }
99 100
 
@@ -119,80 +120,115 @@ const (
119 120
 	DefinedDeployments
120 121
 )
121 122
 
122
-// Params defines a Bitcoin network by its parameters.  These parameters may be used by Bitcoin applications to differentiate networks as well as addresses and keys for one network from those intended for use on another network.
123
-type Params struct {
124
-	// Name defines a human-readable identifier for the network.
125
-	Name string
126
-	// Net defines the magic bytes used to identify the network.
127
-	Net wire.BitcoinNet
128
-	// DefaultPort defines the default peer-to-peer port for the network.
129
-	DefaultPort string
130
-	// DNSSeeds defines a list of DNS seeds for the network that are used
131
-	// as one method to discover peers.
132
-	DNSSeeds []DNSSeed
133
-	// GenesisBlock defines the first block of the chain.
134
-	GenesisBlock *wire.MsgBlock
135
-	// GenesisHash is the starting block hash.
136
-	GenesisHash *chainhash.Hash
137
-	// PowLimit defines the highest allowed proof of work value for a // as a uint256.
138
-	PowLimit *big.Int
139
-	// PowLimitBits defines the highest allowed proof of work value for a block in compact form.
140
-	PowLimitBits uint32
141
-	// These fields define the block heights at which the specified softfork BIP became active.
142
-	BIP0034Height int32
143
-	BIP0065Height int32
144
-	BIP0066Height int32
145
-	// CoinbaseMaturity is the number of blocks required before newly mined coins (coinbase transactions) can be spent.
146
-	CoinbaseMaturity uint16
147
-	// SubsidyReductionInterval is the interval of blocks before the subsidy is reduced.
148
-	SubsidyReductionInterval int32
149
-	// TargetTimespan is the desired amount of time that should elapse before the block difficulty requirement is examined to determine how it should be changed in order to maintain the desired block generation rate.
150
-	TargetTimespan int64
151
-	// TargetTimePerBlock is the desired amount of time to generate each block. Same as TargetSpacing in legacy client.
152
-	TargetTimePerBlock int64
153
-	// RetargetAdjustmentFactor is the adjustment factor used to limit the minimum and maximum amount of adjustment that can occur between difficulty retargets.
154
-	RetargetAdjustmentFactor int64
155
-	// ReduceMinDifficulty defines whether the network should reduce the minimum required difficulty after a long enough period of time has passed without finding a block.  This is really only useful for test networks and should not be set on a main network.
156
-	ReduceMinDifficulty bool
157
-	// MinDiffReductionTime is the amount of time after which the minimum required difficulty should be reduced when a block hasn't been found. NOTE: This only applies if ReduceMinDifficulty is true.
158
-	MinDiffReductionTime time.Duration
159
-	// GenerateSupported specifies whether or not CPU mining is allowed.
160
-	GenerateSupported bool
161
-	// Checkpoints ordered from oldest to newest.
162
-	Checkpoints []Checkpoint
163
-	// These fields are related to voting on consensus rule changes as defined by BIP0009.
164
-	//
165
-	// RuleChangeActivationThreshold is the number of blocks in a threshold state retarget window for which a positive vote for a rule change must be cast in order to lock in a rule change. It should typically be 95% for the main network and 75% for test networks.
166
-	RuleChangeActivationThreshold uint32
167
-	// MinerConfirmationWindow is the number of blocks in each threshold state retarget window.
168
-	MinerConfirmationWindow uint32
169
-	// Deployments define the specific consensus rule changes to be voted on.
170
-	Deployments [DefinedDeployments]ConsensusDeployment
171
-	// Mempool parameters
172
-	RelayNonStdTxs bool
173
-	// Human-readable part for Bech32 encoded segwit addresses, as defined in BIP 173.
174
-	Bech32HRPSegwit string
175
-	// Address encoding magics
176
-	PubKeyHashAddrID        byte // First byte of a P2PKH address
177
-	ScriptHashAddrID        byte // First byte of a P2SH address
178
-	PrivateKeyID            byte // First byte of a WIF private key
179
-	WitnessPubKeyHashAddrID byte // First byte of a P2WPKH address
180
-	WitnessScriptHashAddrID byte // First byte of a P2WSH address
181
-	// BIP32 hierarchical deterministic extended key magics
182
-	HDPrivateKeyID [4]byte
183
-	HDPublicKeyID  [4]byte
184
-	// BIP44 coin type used in the hierarchical deterministic path for address generation.
185
-	HDCoinType uint32
186
-	// Parallelcoin specific difficulty adjustment parameters
187
-	Interval                int64
188
-	AveragingInterval       int64
189
-	AveragingTargetTimespan int64
190
-	MaxAdjustDown           int64
191
-	MaxAdjustUp             int64
192
-	TargetTimespanAdjDown   int64
193
-	MinActualTimespan       int64
194
-	MaxActualTimespan       int64
195
-	// PowLimit defines the highest allowed proof of work value for a scrypt block as a uint256.
196
-	ScryptPowLimit     *big.Int
197
-	ScryptPowLimitBits uint32
123
+// String returns the hostname of the DNS seed in human-readable form.
124
+func (d DNSSeed) String() string {
125
+	return d.Host
126
+}
127
+
128
+// Register registers the network parameters for a Bitcoin network.  This may
129
+// error with ErrDuplicateNet if the network is already registered (either
130
+// due to a previous Register call, or the network being one of the default
131
+// networks).
132
+//
133
+// Network parameters should be registered into this package by a main package
134
+// as early as possible.  Then, library packages may lookup networks or network
135
+// parameters based on inputs and work regardless of the network being standard
136
+// or not.
137
+func Register(params *Params) error {
138
+	if _, ok := registeredNets[params.Net]; ok {
139
+		return ErrDuplicateNet
140
+	}
141
+	registeredNets[params.Net] = struct{}{}
142
+	pubKeyHashAddrIDs[params.PubKeyHashAddrID] = struct{}{}
143
+	scriptHashAddrIDs[params.ScriptHashAddrID] = struct{}{}
144
+	hdPrivToPubKeyIDs[params.HDPrivateKeyID] = params.HDPublicKeyID[:]
145
+
146
+	// A valid Bech32 encoded segwit address always has as prefix the
147
+	// human-readable part for the given net followed by '1'.
148
+	bech32SegwitPrefixes[params.Bech32HRPSegwit+"1"] = struct{}{}
149
+	return nil
150
+}
151
+
152
+// mustRegister performs the same function as Register except it panics if there
153
+// is an error.  This should only be called from package init functions.
154
+func mustRegister(params *Params) {
155
+	if err := Register(params); err != nil {
156
+		panic("failed to register network: " + err.Error())
157
+	}
158
+}
159
+
160
+// IsPubKeyHashAddrID returns whether the id is an identifier known to prefix a
161
+// pay-to-pubkey-hash address on any default or registered network.  This is
162
+// used when decoding an address string into a specific address type.  It is up
163
+// to the caller to check both this and IsScriptHashAddrID and decide whether an
164
+// address is a pubkey hash address, script hash address, neither, or
165
+// undeterminable (if both return true).
166
+func IsPubKeyHashAddrID(id byte) bool {
167
+	_, ok := pubKeyHashAddrIDs[id]
168
+	return ok
169
+}
170
+
171
+// IsScriptHashAddrID returns whether the id is an identifier known to prefix a
172
+// pay-to-script-hash address on any default or registered network.  This is
173
+// used when decoding an address string into a specific address type.  It is up
174
+// to the caller to check both this and IsPubKeyHashAddrID and decide whether an
175
+// address is a pubkey hash address, script hash address, neither, or
176
+// undeterminable (if both return true).
177
+func IsScriptHashAddrID(id byte) bool {
178
+	_, ok := scriptHashAddrIDs[id]
179
+	return ok
180
+}
181
+
182
+// IsBech32SegwitPrefix returns whether the prefix is a known prefix for segwit
183
+// addresses on any default or registered network.  This is used when decoding
184
+// an address string into a specific address type.
185
+func IsBech32SegwitPrefix(prefix string) bool {
186
+	prefix = strings.ToLower(prefix)
187
+	_, ok := bech32SegwitPrefixes[prefix]
188
+	return ok
189
+}
190
+
191
+// HDPrivateKeyToPublicKeyID accepts a private hierarchical deterministic
192
+// extended key id and returns the associated public key id.  When the provided
193
+// id is not registered, the ErrUnknownHDKeyID error will be returned.
194
+func HDPrivateKeyToPublicKeyID(id []byte) ([]byte, error) {
195
+	if len(id) != 4 {
196
+		return nil, ErrUnknownHDKeyID
197
+	}
198
+
199
+	var key [4]byte
200
+	copy(key[:], id)
201
+	pubBytes, ok := hdPrivToPubKeyIDs[key]
202
+	if !ok {
203
+		return nil, ErrUnknownHDKeyID
204
+	}
205
+
206
+	return pubBytes, nil
207
+}
208
+
209
+// newHashFromStr converts the passed big-endian hex string into a
210
+// chainhash.Hash.  It only differs from the one available in chainhash in that
211
+// it panics on an error since it will only (and must only) be called with
212
+// hard-coded, and therefore known good, hashes.
213
+func newHashFromStr(hexStr string) *chainhash.Hash {
214
+	hash, err := chainhash.NewHashFromStr(hexStr)
215
+	if err != nil {
216
+		// Ordinarily I don't like panics in library code since it
217
+		// can take applications down without them having a chance to
218
+		// recover which is extremely annoying, however an exception is
219
+		// being made in this case because the only way this can panic
220
+		// is if there is an error in the hard-coded hashes.  Thus it
221
+		// will only ever potentially panic on init and therefore is
222
+		// 100% predictable.
223
+		panic(err)
224
+	}
225
+	return hash
226
+}
227
+
228
+func init() {
229
+	// Register all default networks when the package is initialized.
230
+	mustRegister(&MainNetParams)
231
+	mustRegister(&TestNet3Params)
232
+	mustRegister(&RegressionNetParams)
233
+	mustRegister(&SimNetParams)
198 234
 }

pkg/chain/config/params/params-mainnet.go → pkg/chain/config/params-mainnet.go View File

@@ -1,9 +1,11 @@
1
-package params
1
+package config
2
+
3
+import "git.parallelcoin.io/dev/9/pkg/chain/protocol"
2 4
 
3 5
 // MainNetParams defines the network parameters for the main Bitcoin network.
4 6
 var MainNetParams = Params{
5 7
 	Name:        "mainnet",
6
-	Net:         MainNet,
8
+	Net:         protocol.MainNet,
7 9
 	DefaultPort: "11047",
8 10
 	DNSSeeds: []DNSSeed{
9 11
 		{"seed1.parallelcoin.io", true},

pkg/chain/config/params/params-regtest.go → pkg/chain/config/params-regtest.go View File

@@ -1,15 +1,15 @@
1
-package params
1
+package config
2 2
 
3 3
 import (
4 4
 	"math"
5 5
 
6
-	"git.parallelcoin.io/dev/9/pkg/chain/wire"
6
+	"git.parallelcoin.io/dev/9/pkg/chain/protocol"
7 7
 )
8 8
 
9 9
 // RegressionNetParams defines the network parameters for the regression test Bitcoin network.  Not to be confused with the test Bitcoin network (version 3), this network is sometimes simply called "testnet".
10 10
 var RegressionNetParams = Params{
11 11
 	Name:        "regtest",
12
-	Net:         wire.TestNet,
12
+	Net:         protocol.TestNet,
13 13
 	DefaultPort: "31047",
14 14
 	DNSSeeds:    []DNSSeed{},
15 15
 	// Chain parameters

pkg/chain/config/params/params-simnet.go → pkg/chain/config/params-simnet.go View File

@@ -1,16 +1,16 @@
1
-package params
1
+package config
2 2
 
3 3
 import (
4 4
 	"math"
5 5
 	"time"
6 6
 
7
-	"git.parallelcoin.io/dev/9/pkg/chain/wire"
7
+	"git.parallelcoin.io/dev/9/pkg/chain/protocol"
8 8
 )
9 9
 
10 10
 // SimNetParams defines the network parameters for the simulation test Bitcoin network.  This network is similar to the normal test network except it is intended for private use within a group of individuals doing simulation testing.  The functionality is intended to differ in that the only nodes which are specifically specified are used to create the network rather than following normal discovery rules.  This is important as otherwise it would just turn into another public testnet.
11 11
 var SimNetParams = Params{
12 12
 	Name:        "simnet",
13
-	Net:         wire.SimNet,
13
+	Net:         protocol.SimNet,
14 14
 	DefaultPort: "41047",
15 15
 	DNSSeeds:    []DNSSeed{}, // NOTE: There must NOT be any seeds.
16 16
 	// Chain parameters

pkg/chain/config/params/params-testnet.go → pkg/chain/config/params-testnet.go View File

@@ -1,14 +1,14 @@
1
-package params
1
+package config
2 2
 
3 3
 import (
4 4
 	"git.parallelcoin.io/dev/9/pkg/chain/fork"
5
-	"git.parallelcoin.io/dev/9/pkg/chain/wire"
5
+	"git.parallelcoin.io/dev/9/pkg/chain/protocol"
6 6
 )
7 7
 
8 8
 // TestNet3Params defines the network parameters for the test Bitcoin network (version 3).  Not to be confused with the regression test network, this network is sometimes simply called "testnet".
9 9
 var TestNet3Params = Params{
10 10
 	Name:        "testnet",
11
-	Net:         wire.TestNet3,
11
+	Net:         protocol.TestNet3,
12 12
 	DefaultPort: "21047",
13 13
 	DNSSeeds:    []DNSSeed{
14 14
 		// {"testnet-seed.bitcoin.jonasschnelli.ch", true},

+ 89
- 0
pkg/chain/config/params.go View File

@@ -0,0 +1,89 @@
1
+package config
2
+
3
+import (
4
+	"math/big"
5
+	"time"
6
+
7
+	chainhash "git.parallelcoin.io/dev/9/pkg/chain/hash"
8
+	"git.parallelcoin.io/dev/9/pkg/chain/protocol"
9
+	"git.parallelcoin.io/dev/9/pkg/chain/wire"
10
+)
11
+
12
+// Params defines a Bitcoin network by its parameters.  These parameters may be used by Bitcoin applications to differentiate networks as well as addresses and keys for one network from those intended for use on another network.
13
+type Params struct {
14
+	// Name defines a human-readable identifier for the network.
15
+	Name string
16
+	// Net defines the magic bytes used to identify the network.
17
+	Net protocol.BitcoinNet
18
+	// DefaultPort defines the default peer-to-peer port for the network.
19
+	DefaultPort string
20
+	// DNSSeeds defines a list of DNS seeds for the network that are used
21
+	// as one method to discover peers.
22
+	DNSSeeds []DNSSeed
23
+	// GenesisBlock defines the first block of the chain.
24
+	GenesisBlock *wire.MsgBlock
25
+	// GenesisHash is the starting block hash.
26
+	GenesisHash *chainhash.Hash
27
+	// PowLimit defines the highest allowed proof of work value for a // as a uint256.
28
+	PowLimit *big.Int
29
+	// PowLimitBits defines the highest allowed proof of work value for a block in compact form.
30
+	PowLimitBits uint32
31
+	// These fields define the block heights at which the specified softfork BIP became active.
32
+	BIP0034Height int32
33
+	BIP0065Height int32
34
+	BIP0066Height int32
35
+	// CoinbaseMaturity is the number of blocks required before newly mined coins (coinbase transactions) can be spent.
36
+	CoinbaseMaturity uint16
37
+	// SubsidyReductionInterval is the interval of blocks before the subsidy is reduced.
38
+	SubsidyReductionInterval int32
39
+	// TargetTimespan is the desired amount of time that should elapse before the block difficulty requirement is examined to determine how it should be changed in order to maintain the desired block generation rate.
40
+	TargetTimespan int64
41
+	// TargetTimePerBlock is the desired amount of time to generate each block. Same as TargetSpacing in legacy client.
42
+	TargetTimePerBlock int64
43
+	// RetargetAdjustmentFactor is the adjustment factor used to limit the minimum and maximum amount of adjustment that can occur between difficulty retargets.
44
+	RetargetAdjustmentFactor int64
45
+	// ReduceMinDifficulty defines whether the network should reduce the minimum required difficulty after a long enough period of time has passed without finding a block.  This is really only useful for test networks and should not be set on a main network.
46
+	ReduceMinDifficulty bool
47
+	// MinDiffReductionTime is the amount of time after which the minimum required difficulty should be reduced when a block hasn't been found. NOTE: This only applies if ReduceMinDifficulty is true.
48
+	MinDiffReductionTime time.Duration
49
+	// GenerateSupported specifies whether or not CPU mining is allowed.
50
+	GenerateSupported bool
51
+	// Checkpoints ordered from oldest to newest.
52
+	Checkpoints []Checkpoint
53
+	// These fields are related to voting on consensus rule changes as defined by BIP0009.
54
+	//
55
+	// RuleChangeActivationThreshold is the number of blocks in a threshold state retarget window for which a positive vote for a rule change must be cast in order to lock in a rule change. It should typically be 95% for the main network and 75% for test networks.
56
+	RuleChangeActivationThreshold uint32
57
+	// MinerConfirmationWindow is the number of blocks in each threshold state retarget window.
58
+	MinerConfirmationWindow uint32
59
+	// Deployments define the specific consensus rule changes to be voted on.
60
+	Deployments [DefinedDeployments]ConsensusDeployment
61
+	// Mempool parameters
62
+	RelayNonStdTxs bool
63
+	// Human-readable part for Bech32 encoded segwit addresses, as defined in BIP 173.
64
+	Bech32HRPSegwit string
65
+	// Address encoding magics
66
+	PubKeyHashAddrID        byte // First byte of a P2PKH address
67
+	ScriptHashAddrID        byte // First byte of a P2SH address
68
+	PrivateKeyID            byte // First byte of a WIF private key
69
+	WitnessPubKeyHashAddrID byte // First byte of a P2WPKH address
70
+	WitnessScriptHashAddrID byte // First byte of a P2WSH address
71
+	// BIP32 hierarchical deterministic extended key magics
72
+	HDPrivateKeyID [4]byte
73
+	HDPublicKeyID  [4]byte
74
+	// BIP44 coin type used in the hierarchical deterministic path for address generation.
75
+	HDCoinType uint32
76
+	// Parallelcoin specific difficulty adjustment parameters
77
+	Interval                int64
78
+	AveragingInterval       int64
79
+	AveragingTargetTimespan int64
80
+	MaxAdjustDown           int64
81
+	MaxAdjustUp             int64
82
+	TargetTimespanAdjDown   int64
83
+	MinActualTimespan       int64
84
+	MaxActualTimespan       int64
85
+	// PowLimit defines the highest allowed proof of work value for a scrypt block as a uint256.
86
+	ScryptPowLimit     *big.Int
87
+	ScryptPowLimitBits uint32
88
+	RPCPort            string
89
+}

+ 0
- 41
pkg/chain/config/params/params.go View File

@@ -1,41 +0,0 @@
1
-package params
2
-
3
-import (
4
-	chaincfg "git.parallelcoin.io/dev/9/pkg/chain/config"
5
-)
6
-
7
-// Params is used to group parameters for various networks such as the main network and test networks.
8
-
9
-type Params struct {
10
-	*chaincfg.Params
11
-	RPCClientPort string
12
-	RPCServerPort string
13
-}
14
-
15
-// // MainNetParams contains parameters specific running btcwallet and pod on the main network (wire.MainNet).
16
-// var MainNetParams = Params{
17
-// 	Params:        &chaincfg.MainNetParams,
18
-// 	RPCClientPort: "11048",
19
-// 	RPCServerPort: "11046",
20
-// }
21
-
22
-// // SimNetParams contains parameters specific to the simulation test network (wire.SimNet).
23
-// var SimNetParams = Params{
24
-// 	Params:        &chaincfg.SimNetParams,
25
-// 	RPCClientPort: "41048",
26
-// 	RPCServerPort: "41046",
27
-// }
28
-
29
-// // TestNet3Params contains parameters specific running btcwallet and pod on the test network (version 3) (wire.TestNet3).
30
-// var TestNet3Params = Params{
31
-// 	Params:        &chaincfg.TestNet3Params,
32
-// 	RPCClientPort: "21048",
33
-// 	RPCServerPort: "21046",
34
-// }
35
-
36
-// // RegressionTestParams contains parameters specific to the simulation test network (wire.SimNet).
37
-// var RegressionTestParams = Params{
38
-// 	Params:        &chaincfg.RegressionNetParams,
39
-// 	RPCClientPort: "31048",
40
-// 	RPCServerPort: "31046",
41
-// }

+ 0
- 32
pkg/chain/config/params_test.go View File

@@ -1,32 +0,0 @@
1
-//+build test
2
-
3
-package chaincfg
4
-
5
-import "testing"
6
-
7
-// TestInvalidHashStr ensures the newShaHashFromStr function panics when used to with an invalid hash string.
8
-func TestInvalidHashStr(
9
-	t *testing.T) {
10
-	defer func() {
11
-		if r := recover(); r == nil {
12
-			t.Errorf("Expected panic for invalid hash, got nil")
13
-		}
14
-	}()
15
-	newHashFromStr("banana")
16
-}
17
-
18
-// TestMustRegisterPanic ensures the mustRegister function panics when used to
19
-// register an invalid network.
20
-func TestMustRegisterPanic(
21
-	t *testing.T) {
22
-	t.Parallel()
23
-	// Setup a defer to catch the expected panic to ensure it actually
24
-	// paniced.
25
-	defer func() {
26
-		if err := recover(); err == nil {
27
-			t.Error("mustRegister did not panic as expected")
28
-		}
29
-	}()
30
-	// Intentionally try to register duplicate params to force a panic.
31
-	mustRegister(&MainNetParams)
32
-}

+ 0
- 507
pkg/chain/config/register_test.go View File

@@ -1,507 +0,0 @@
1
-//+build test
2
-
3
-package chaincfg_test
4
-
5
-import (
6
-	"bytes"
7
-	"reflect"
8
-	"strings"
9
-	"testing"
10
-
11
-	. "git.parallelcoin.io/dev/9/pkg/chain/config"
12
-)
13
-
14
-// Define some of the required parameters for a user-registered network.  This is necessary to test the registration of and lookup of encoding magics from the network.
15
-var mockNetParams = Params{
16
-	Name:             "mocknet",
17
-	Net:              1<<32 - 1,
18
-	PubKeyHashAddrID: 0x9f,
19
-	ScriptHashAddrID: 0xf9,
20
-	Bech32HRPSegwit:  "tc",
21
-	HDPrivateKeyID:   [4]byte{0x01, 0x02, 0x03, 0x04},
22
-	HDPublicKeyID:    [4]byte{0x05, 0x06, 0x07, 0x08},
23
-}
24
-
25
-func TestRegister(
26
-	t *testing.T) {
27
-	type registerTest struct {
28
-		name   string
29
-		params *Params
30
-		err    error
31
-	}
32
-	type magicTest struct {
33
-		magic byte
34
-		valid bool
35
-	}
36
-	type prefixTest struct {
37
-		prefix string
38
-		valid  bool
39
-	}
40
-	type hdTest struct {
41
-		priv []byte
42
-		want []byte
43
-		err  error
44
-	}
45
-	tests := []struct {
46
-		name           string
47
-		register       []registerTest
48
-		p2pkhMagics    []magicTest
49
-		p2shMagics     []magicTest
50
-		segwitPrefixes []prefixTest
51
-		hdMagics       []hdTest
52
-	}{
53
-		{
54
-			name: "default networks",
55
-			register: []registerTest{
56
-				{
57
-					name:   "duplicate mainnet",
58
-					params: &MainNetParams,
59
-					err:    ErrDuplicateNet,
60
-				},
61
-				{
62
-					name:   "duplicate regtest",
63
-					params: &RegressionNetParams,
64
-					err:    ErrDuplicateNet,
65
-				},
66
-				{
67
-					name:   "duplicate testnet3",
68
-					params: &TestNet3Params,
69
-					err:    ErrDuplicateNet,
70
-				},
71
-				{
72
-					name:   "duplicate simnet",
73
-					params: &SimNetParams,
74
-					err:    ErrDuplicateNet,
75
-				},
76
-			},
77
-			p2pkhMagics: []magicTest{
78
-				{
79
-					magic: MainNetParams.PubKeyHashAddrID,
80
-					valid: true,
81
-				},
82
-				{
83
-					magic: TestNet3Params.PubKeyHashAddrID,
84
-					valid: true,
85
-				},
86
-				{
87
-					magic: RegressionNetParams.PubKeyHashAddrID,
88
-					valid: true,
89
-				},
90
-				{
91
-					magic: SimNetParams.PubKeyHashAddrID,
92
-					valid: true,
93
-				},
94
-				{
95
-					magic: mockNetParams.PubKeyHashAddrID,
96
-					valid: false,
97
-				},
98
-				{
99
-					magic: 0xFF,
100
-					valid: false,
101
-				},
102
-			},
103
-			p2shMagics: []magicTest{
104
-				{
105
-					magic: MainNetParams.ScriptHashAddrID,
106
-					valid: true,
107
-				},
108
-				{
109
-					magic: TestNet3Params.ScriptHashAddrID,
110
-					valid: true,
111
-				},
112
-				{
113
-					magic: RegressionNetParams.ScriptHashAddrID,
114
-					valid: true,
115
-				},
116
-				{
117
-					magic: SimNetParams.ScriptHashAddrID,
118
-					valid: true,
119
-				},
120
-				{
121
-					magic: mockNetParams.ScriptHashAddrID,
122
-					valid: false,
123
-				},
124
-				{
125
-					magic: 0xFF,
126
-					valid: false,
127
-				},
128
-			},
129
-			segwitPrefixes: []prefixTest{
130
-				{
131
-					prefix: MainNetParams.Bech32HRPSegwit + "1",
132
-					valid:  true,
133
-				},
134
-				{
135
-					prefix: TestNet3Params.Bech32HRPSegwit + "1",
136
-					valid:  true,
137
-				},
138
-				{
139
-					prefix: RegressionNetParams.Bech32HRPSegwit + "1",
140
-					valid:  true,
141
-				},
142
-				{
143
-					prefix: SimNetParams.Bech32HRPSegwit + "1",
144
-					valid:  true,
145
-				},
146
-				{
147
-					prefix: strings.ToUpper(MainNetParams.Bech32HRPSegwit + "1"),
148
-					valid:  true,
149
-				},
150
-				{
151
-					prefix: mockNetParams.Bech32HRPSegwit + "1",
152
-					valid:  false,
153
-				},
154
-				{
155
-					prefix: "abc1",
156
-					valid:  false,
157
-				},
158
-				{
159
-					prefix: "1",
160
-					valid:  false,
161
-				},
162
-				{
163
-					prefix: MainNetParams.Bech32HRPSegwit,
164
-					valid:  false,
165
-				},
166
-			},
167
-			hdMagics: []hdTest{
168
-				{
169
-					priv: MainNetParams.HDPrivateKeyID[:],
170
-					want: MainNetParams.HDPublicKeyID[:],
171
-					err:  nil,
172
-				},
173
-				{
174
-					priv: TestNet3Params.HDPrivateKeyID[:],
175
-					want: TestNet3Params.HDPublicKeyID[:],
176
-					err:  nil,
177
-				},
178
-				{
179
-					priv: RegressionNetParams.HDPrivateKeyID[:],
180
-					want: RegressionNetParams.HDPublicKeyID[:],
181
-					err:  nil,
182
-				},
183
-				{
184
-					priv: SimNetParams.HDPrivateKeyID[:],
185
-					want: SimNetParams.HDPublicKeyID[:],
186
-					err:  nil,
187
-				},
188
-				{
189
-					priv: mockNetParams.HDPrivateKeyID[:],
190
-					err:  ErrUnknownHDKeyID,
191
-				},
192
-				{
193
-					priv: []byte{0xff, 0xff, 0xff, 0xff},
194
-					err:  ErrUnknownHDKeyID,
195
-				},
196
-				{
197
-					priv: []byte{0xff},
198
-					err:  ErrUnknownHDKeyID,
199
-				},
200
-			},
201
-		},
202
-		{
203
-			name: "register mocknet",
204
-			register: []registerTest{
205
-				{
206
-					name:   "mocknet",
207
-					params: &mockNetParams,
208
-					err:    nil,
209
-				},
210
-			},
211
-			p2pkhMagics: []magicTest{
212
-				{
213
-					magic: MainNetParams.PubKeyHashAddrID,
214
-					valid: true,
215
-				},
216
-				{
217
-					magic: TestNet3Params.PubKeyHashAddrID,
218
-					valid: true,
219
-				},
220
-				{
221
-					magic: RegressionNetParams.PubKeyHashAddrID,
222
-					valid: true,
223
-				},
224
-				{
225
-					magic: SimNetParams.PubKeyHashAddrID,
226
-					valid: true,
227
-				},
228
-				{
229
-					magic: mockNetParams.PubKeyHashAddrID,
230
-					valid: true,
231
-				},
232
-				{
233
-					magic: 0xFF,
234
-					valid: false,
235
-				},
236
-			},
237
-			p2shMagics: []magicTest{
238
-				{
239
-					magic: MainNetParams.ScriptHashAddrID,
240
-					valid: true,
241
-				},
242
-				{
243
-					magic: TestNet3Params.ScriptHashAddrID,
244
-					valid: true,
245
-				},
246
-				{
247
-					magic: RegressionNetParams.ScriptHashAddrID,
248
-					valid: true,
249
-				},
250
-				{
251
-					magic: SimNetParams.ScriptHashAddrID,
252
-					valid: true,
253
-				},
254
-				{
255
-					magic: mockNetParams.ScriptHashAddrID,
256
-					valid: true,
257
-				},
258
-				{
259
-					magic: 0xFF,
260
-					valid: false,
261
-				},
262
-			},
263
-			segwitPrefixes: []prefixTest{
264
-				{
265
-					prefix: MainNetParams.Bech32HRPSegwit + "1",
266
-					valid:  true,
267
-				},
268
-				{
269
-					prefix: TestNet3Params.Bech32HRPSegwit + "1",
270
-					valid:  true,
271
-				},
272
-				{
273
-					prefix: RegressionNetParams.Bech32HRPSegwit + "1",
274
-					valid:  true,
275
-				},
276
-				{
277
-					prefix: SimNetParams.Bech32HRPSegwit + "1",
278
-					valid:  true,
279
-				},
280
-				{
281
-					prefix: strings.ToUpper(MainNetParams.Bech32HRPSegwit + "1"),
282
-					valid:  true,
283
-				},
284
-				{
285
-					prefix: mockNetParams.Bech32HRPSegwit + "1",
286
-					valid:  true,
287
-				},
288
-				{
289
-					prefix: "abc1",
290
-					valid:  false,
291
-				},
292
-				{
293
-					prefix: "1",
294
-					valid:  false,
295
-				},
296
-				{
297
-					prefix: MainNetParams.Bech32HRPSegwit,
298
-					valid:  false,
299
-				},
300
-			},
301
-			hdMagics: []hdTest{
302
-				{
303
-					priv: mockNetParams.HDPrivateKeyID[:],
304
-					want: mockNetParams.HDPublicKeyID[:],
305
-					err:  nil,
306
-				},
307
-			},
308
-		},
309
-		{
310
-			name: "more duplicates",
311
-			register: []registerTest{
312
-				{
313
-					name:   "duplicate mainnet",
314
-					params: &MainNetParams,
315
-					err:    ErrDuplicateNet,
316
-				},
317
-				{
318
-					name:   "duplicate regtest",
319
-					params: &RegressionNetParams,
320
-					err:    ErrDuplicateNet,
321
-				},
322
-				{
323
-					name:   "duplicate testnet3",
324
-					params: &TestNet3Params,
325
-					err:    ErrDuplicateNet,
326
-				},
327
-				{
328
-					name:   "duplicate simnet",
329
-					params: &SimNetParams,
330
-					err:    ErrDuplicateNet,
331
-				},
332
-				{
333
-					name:   "duplicate mocknet",
334
-					params: &mockNetParams,
335
-					err:    ErrDuplicateNet,
336
-				},
337
-			},
338
-			p2pkhMagics: []magicTest{
339
-				{
340
-					magic: MainNetParams.PubKeyHashAddrID,
341
-					valid: true,
342
-				},
343
-				{
344
-					magic: TestNet3Params.PubKeyHashAddrID,
345
-					valid: true,
346
-				},
347
-				{
348
-					magic: RegressionNetParams.PubKeyHashAddrID,
349
-					valid: true,
350
-				},
351
-				{
352
-					magic: SimNetParams.PubKeyHashAddrID,
353
-					valid: true,
354
-				},
355
-				{
356
-					magic: mockNetParams.PubKeyHashAddrID,
357
-					valid: true,
358
-				},
359
-				{
360
-					magic: 0xFF,
361
-					valid: false,
362
-				},
363
-			},
364
-			p2shMagics: []magicTest{
365
-				{
366
-					magic: MainNetParams.ScriptHashAddrID,
367
-					valid: true,
368
-				},
369
-				{
370
-					magic: TestNet3Params.ScriptHashAddrID,
371
-					valid: true,
372
-				},
373
-				{
374
-					magic: RegressionNetParams.ScriptHashAddrID,
375
-					valid: true,
376
-				},
377
-				{
378
-					magic: SimNetParams.ScriptHashAddrID,
379
-					valid: true,
380
-				},
381
-				{
382
-					magic: mockNetParams.ScriptHashAddrID,
383
-					valid: true,
384
-				},
385
-				{
386
-					magic: 0xFF,
387
-					valid: false,
388
-				},
389
-			},
390
-			segwitPrefixes: []prefixTest{
391
-				{
392
-					prefix: MainNetParams.Bech32HRPSegwit + "1",
393
-					valid:  true,
394
-				},
395
-				{
396
-					prefix: TestNet3Params.Bech32HRPSegwit + "1",
397
-					valid:  true,
398
-				},
399
-				{
400
-					prefix: RegressionNetParams.Bech32HRPSegwit + "1",
401
-					valid:  true,
402
-				},
403
-				{
404
-					prefix: SimNetParams.Bech32HRPSegwit + "1",
405
-					valid:  true,
406
-				},
407
-				{
408
-					prefix: strings.ToUpper(MainNetParams.Bech32HRPSegwit + "1"),
409
-					valid:  true,
410
-				},
411
-				{
412
-					prefix: mockNetParams.Bech32HRPSegwit + "1",
413
-					valid:  true,
414
-				},
415
-				{
416
-					prefix: "abc1",
417
-					valid:  false,
418
-				},
419
-				{
420
-					prefix: "1",
421
-					valid:  false,
422
-				},
423
-				{
424
-					prefix: MainNetParams.Bech32HRPSegwit,
425
-					valid:  false,
426
-				},
427
-			},
428
-			hdMagics: []hdTest{
429
-				{
430
-					priv: MainNetParams.HDPrivateKeyID[:],
431
-					want: MainNetParams.HDPublicKeyID[:],
432
-					err:  nil,
433
-				},
434
-				{
435
-					priv: TestNet3Params.HDPrivateKeyID[:],
436
-					want: TestNet3Params.HDPublicKeyID[:],
437
-					err:  nil,
438
-				},
439
-				{
440
-					priv: RegressionNetParams.HDPrivateKeyID[:],
441
-					want: RegressionNetParams.HDPublicKeyID[:],
442
-					err:  nil,
443
-				},
444
-				{
445
-					priv: SimNetParams.HDPrivateKeyID[:],
446
-					want: SimNetParams.HDPublicKeyID[:],
447
-					err:  nil,
448
-				},
449
-				{
450
-					priv: mockNetParams.HDPrivateKeyID[:],
451
-					want: mockNetParams.HDPublicKeyID[:],
452
-					err:  nil,
453
-				},
454
-				{
455
-					priv: []byte{0xff, 0xff, 0xff, 0xff},
456
-					err:  ErrUnknownHDKeyID,
457
-				},
458
-				{
459
-					priv: []byte{0xff},
460
-					err:  ErrUnknownHDKeyID,
461
-				},
462
-			},
463
-		},
464
-	}
465
-	for _, test := range tests {
466
-		for _, regTest := range test.register {
467
-			err := Register(regTest.params)
468
-			if err != regTest.err {
469
-				t.Errorf("%s:%s: Registered network with unexpected error: got %v expected %v",
470
-					test.name, regTest.name, err, regTest.err)
471
-			}
472
-		}
473
-		for i, magTest := range test.p2pkhMagics {
474
-			valid := IsPubKeyHashAddrID(magTest.magic)
475
-			if valid != magTest.valid {
476
-				t.Errorf("%s: P2PKH magic %d valid mismatch: got %v expected %v",
477
-					test.name, i, valid, magTest.valid)
478
-			}
479
-		}
480
-		for i, magTest := range test.p2shMagics {
481
-			valid := IsScriptHashAddrID(magTest.magic)
482
-			if valid != magTest.valid {
483
-				t.Errorf("%s: P2SH magic %d valid mismatch: got %v expected %v",
484
-					test.name, i, valid, magTest.valid)
485
-			}
486
-		}
487
-		for i, prxTest := range test.segwitPrefixes {
488
-			valid := IsBech32SegwitPrefix(prxTest.prefix)
489
-			if valid != prxTest.valid {
490
-				t.Errorf("%s: segwit prefix %s (%d) valid mismatch: got %v expected %v",
491
-					test.name, prxTest.prefix, i, valid, prxTest.valid)
492
-			}
493
-		}
494
-		for i, magTest := range test.hdMagics {
495
-			pubKey, err := HDPrivateKeyToPublicKeyID(magTest.priv[:])
496
-			if !reflect.DeepEqual(err, magTest.err) {
497
-				t.Errorf("%s: HD magic %d mismatched error: got %v expected %v ",
498
-					test.name, i, err, magTest.err)
499
-				continue
500
-			}
501
-			if magTest.err == nil && !bytes.Equal(pubKey, magTest.want[:]) {
502
-				t.Errorf("%s: HD magic %d private and public mismatch: got %v expected %v ",
503
-					test.name, i, pubKey, magTest.want[:])
504
-			}
505
-		}
506
-	}
507
-}

+ 0
- 38
pkg/chain/config/util.go View File

@@ -1,38 +0,0 @@
1
-package chaincfg
2
-
3
-import "math/big"
4
-
5
-// CompactToBig converts a compact representation of a whole number N to an unsigned 32-bit number.  The representation is similar to IEEE754 floating point numbers.
6
-// Like IEEE754 floating point, there are three basic components: the sign, the exponent, and the mantissa.  They are broken out as follows:
7
-//	* the most significant 8 bits represent the unsigned base 256 exponent
8
-// 	* bit 23 (the 24th bit) represents the sign bit
9
-//	* the least significant 23 bits represent the mantissa
10
-//	-------------------------------------------------
11
-//	|   Exponent     |    Sign    |    Mantissa     |
12
-//	-------------------------------------------------
13
-//	| 8 bits [31-24] | 1 bit [23] | 23 bits [22-00] |
14
-//	-------------------------------------------------
15
-// The formula to calculate N is:
16
-// 	N = (-1^sign) * mantissa * 256^(exponent-3)
17
-// This compact form is only used in bitcoin to encode unsigned 256-bit numbers which represent difficulty targets, thus there really is not a need for a sign bit, but it is implemented here to stay consistent with bitcoind.
18
-func compactToBig(
19
-	compact uint32) *big.Int {
20
-	// Extract the mantissa, sign bit, and exponent.
21
-	mantissa := compact & 0x007fffff
22
-	isNegative := compact&0x00800000 != 0
23
-	exponent := uint(compact >> 24)
24
-	// Since the base for the exponent is 256, the exponent can be treated as the number of bytes to represent the full 256-bit number.  So, treat the exponent as the number of bytes and shift the mantissa right or left accordingly.  This is equivalent to `N = mantissa * 256^(exponent-3)``
25
-	var bn *big.Int
26
-	if exponent <= 3 {
27
-		mantissa >>= 8 * (3 - exponent)
28
-		bn = big.NewInt(int64(mantissa))
29
-	} else {
30
-		bn = big.NewInt(int64(mantissa))
31
-		bn.Lsh(bn, 8*(exponent-3))
32
-	}
33
-	// Make it negative if the sign bit is set.
34
-	if isNegative {
35
-		bn = bn.Neg(bn)
36
-	}
37
-	return bn
38
-}

pkg/util/wif.go → pkg/chain/config/wif.go View File

@@ -1,10 +1,9 @@
1
-package util
1
+package config
2 2
 
3 3
 import (
4 4
 	"bytes"
5 5
 	"errors"
6 6
 
7
-	chaincfg "git.parallelcoin.io/dev/9/pkg/chain/config"
8 7
 	chainhash "git.parallelcoin.io/dev/9/pkg/chain/hash"
9 8
 	"git.parallelcoin.io/dev/9/pkg/util/base58"
10 9
 	ec "git.parallelcoin.io/dev/9/pkg/util/elliptic"
@@ -28,7 +27,7 @@ type WIF struct {
28 27
 
29 28
 // NewWIF creates a new WIF structure to export an address and its private key as a string encoded in the Wallet Import Format.  The compress argument specifies whether the address intended to be imported or exported was created by serializing the public key compressed rather than uncompressed.
30 29
 func NewWIF(
31
-	privKey *ec.PrivateKey, net *chaincfg.Params, compress bool) (*WIF, error) {
30
+	privKey *ec.PrivateKey, net *Params, compress bool) (*WIF, error) {
32 31
 	if net == nil {
33 32
 		return nil, errors.New("no network")
34 33
 	}
@@ -36,7 +35,7 @@ func NewWIF(
36 35
 }
37 36
 
38 37
 // IsForNet returns whether or not the decoded WIF structure is associated with the passed bitcoin network.
39
-func (w *WIF) IsForNet(net *chaincfg.Params) bool {
38
+func (w *WIF) IsForNet(net *Params) bool {
40 39
 	return w.netID == net.PrivateKeyID
41 40
 }
42 41
 

+ 1
- 1
pkg/chain/fork/fork.go View File

@@ -210,7 +210,7 @@ func GetMinBits(algoname string, height int32) (mb uint32) {
210 210
 
211 211
 // GetMinDiff returns the minimum difficulty in uint256 form
212 212
 func GetMinDiff(algoname string, height int32) (md *big.Int) {
213
-	return CompactToBig(GetMinBits(algoname, height))
213
+	return util.CompactToBig(GetMinBits(algoname, height))
214 214
 }
215 215
 
216 216
 // GetTargetTimePerBlock returns the active block interval target based on hard fork status

+ 18
- 18
pkg/chain/index/addrindex.go View File

@@ -6,6 +6,7 @@ import (
6 6
 	"sync"
7 7
 
8 8
 	blockchain "git.parallelcoin.io/dev/9/pkg/chain"
9
+	"git.parallelcoin.io/dev/9/pkg/chain/config"
9 10
 	chaincfg "git.parallelcoin.io/dev/9/pkg/chain/config"
10 11
 	chainhash "git.parallelcoin.io/dev/9/pkg/chain/hash"
11 12
 	txscript "git.parallelcoin.io/dev/9/pkg/chain/tx/script"
@@ -374,31 +375,30 @@ func dbRemoveAddrIndexEntries(
374 375
 }
375 376
 
376 377
 // addrToKey converts known address types to an addrindex key.  An error is returned for unsupported types.
377
-func addrToKey(
378
-	addr util.Address) ([addrKeySize]byte, error) {
378
+func addrToKey(addr config.Address) ([addrKeySize]byte, error) {
379 379
 	switch addr := addr.(type) {
380
-	case *util.AddressPubKeyHash:
380
+	case *config.AddressPubKeyHash:
381 381
 		var result [addrKeySize]byte
382 382
 		result[0] = addrKeyTypePubKeyHash
383 383
 		copy(result[1:], addr.Hash160()[:])
384 384
 		return result, nil
385
-	case *util.AddressScriptHash:
385
+	case *config.AddressScriptHash:
386 386
 		var result [addrKeySize]byte
387 387
 		result[0] = addrKeyTypeScriptHash
388 388
 		copy(result[1:], addr.Hash160()[:])
389 389
 		return result, nil
390
-	case *util.AddressPubKey:
390
+	case *config.AddressPubKey:
391 391
 		var result [addrKeySize]byte
392 392
 		result[0] = addrKeyTypePubKeyHash
393 393
 		copy(result[1:], addr.AddressPubKeyHash().Hash160()[:])
394 394
 		return result, nil
395
-	case *util.AddressWitnessScriptHash:
395
+	case *config.AddressWitnessScriptHash:
396 396
 		var result [addrKeySize]byte
397 397
 		result[0] = addrKeyTypeWitnessScriptHash
398 398
 		// P2WSH outputs utilize a 32-byte data push created by hashing the script with sha256 instead of hash160. In order to keep all address entries within the database uniform and compact, we use a hash160 here to reduce the size of the salient data push to 20-bytes.
399 399
 		copy(result[1:], util.Hash160(addr.ScriptAddress()))
400 400
 		return result, nil
401
-	case *util.AddressWitnessPubKeyHash:
401
+	case *config.AddressWitnessPubKeyHash:
402 402
 		var result [addrKeySize]byte
403 403
 		result[0] = addrKeyTypeWitnessPubKeyHash
404 404
 		copy(result[1:], addr.Hash160()[:])
@@ -416,7 +416,7 @@ type AddrIndex struct {
416 416
 	// The txnsByAddr field is used to keep an index of all transactions which either create an output to a given address or spend from a previous output to it keyed by the address.
417 417
 	// The addrsByTx field is essentially the reverse and is used to keep an index of all addresses which a given transaction involves. This allows fairly efficient updates when transactions are removed once they are included into a block.
418 418
 	unconfirmedLock sync.RWMutex
419
-	txnsByAddr      map[[addrKeySize]byte]map[chainhash.Hash]*util.Tx
419
+	txnsByAddr      map[[addrKeySize]byte]map[chainhash.Hash]*wire.Tx
420 420
 	addrsByTx       map[chainhash.Hash]map[[addrKeySize]byte]struct{}
421 421
 }
422 422
 
@@ -483,7 +483,7 @@ func (idx *AddrIndex) indexPkScript(data writeIndexData, pkScript []byte, txIdx
483 483
 }
484 484
 
485 485
 // indexBlock extract all of the standard addresses from all of the transactions in the passed block and maps each of them to the associated transaction using the passed map.
486
-func (idx *AddrIndex) indexBlock(data writeIndexData, block *util.Block,
486
+func (idx *AddrIndex) indexBlock(data writeIndexData, block *wire.Block,
487 487
 	stxos []blockchain.SpentTxOut) {
488 488
 	stxoIndex := 0
489 489
 	for txIdx, tx := range block.Transactions() {
@@ -504,7 +504,7 @@ func (idx *AddrIndex) indexBlock(data writeIndexData, block *util.Block,
504 504
 }
505 505
 
506 506
 // ConnectBlock is invoked by the index manager when a new block has been connected to the main chain.  This indexer adds a mapping for each address the transactions in the block involve. This is part of the Indexer interface.
507
-func (idx *AddrIndex) ConnectBlock(dbTx database.Tx, block *util.Block,
507
+func (idx *AddrIndex) ConnectBlock(dbTx database.Tx, block *wire.Block,
508 508
 	stxos []blockchain.SpentTxOut) error {
509 509
 	// The offset and length of the transactions within the serialized block.
510 510
 	txLocs, err := block.TxLoc()
@@ -534,7 +534,7 @@ func (idx *AddrIndex) ConnectBlock(dbTx database.Tx, block *util.Block,
534 534
 }
535 535
 
536 536
 // DisconnectBlock is invoked by the index manager when a block has been disconnected from the main chain.  This indexer removes the address mappings each transaction in the block involve. This is part of the Indexer interface.
537
-func (idx *AddrIndex) DisconnectBlock(dbTx database.Tx, block *util.Block,
537
+func (idx *AddrIndex) DisconnectBlock(dbTx database.Tx, block *wire.Block,
538 538
 	stxos []blockchain.SpentTxOut) error {
539 539
 	// Build all of the address to transaction mappings in a local map.
540 540
 	addrsToTxns := make(writeIndexData)
@@ -551,7 +551,7 @@ func (idx *AddrIndex) DisconnectBlock(dbTx database.Tx, block *util.Block,
551 551
 }
552 552
 
553 553
 // TxRegionsForAddress returns a slice of block regions which identify each transaction that involves the passed address according to the specified number to skip, number requested, and whether or not the results should be reversed.  It also returns the number actually skipped since it could be less in the case where there are not enough entries. NOTE: These results only include transactions confirmed in blocks.  See the UnconfirmedTxnsForAddress method for obtaining unconfirmed transactions that involve a given address. This function is safe for concurrent access.
554
-func (idx *AddrIndex) TxRegionsForAddress(dbTx database.Tx, addr util.Address, numToSkip, numRequested uint32, reverse bool) ([]database.BlockRegion, uint32, error) {
554
+func (idx *AddrIndex) TxRegionsForAddress(dbTx database.Tx, addr config.Address, numToSkip, numRequested uint32, reverse bool) ([]database.BlockRegion, uint32, error) {
555 555
 	addrKey, err := addrToKey(addr)
556 556
 	if err != nil {
557 557
 		return nil, 0, err
@@ -575,7 +575,7 @@ func (idx *AddrIndex) TxRegionsForAddress(dbTx database.Tx, addr util.Address, n
575 575
 }
576 576
 
577 577
 // indexUnconfirmedAddresses modifies the unconfirmed (memory-only) address index to include mappings for the addresses encoded by the passed public key script to the transaction. This function is safe for concurrent access.
578
-func (idx *AddrIndex) indexUnconfirmedAddresses(pkScript []byte, tx *util.Tx) {
578
+func (idx *AddrIndex) indexUnconfirmedAddresses(pkScript []byte, tx *wire.Tx) {
579 579
 	// The error is ignored here since the only reason it can fail is if the script fails to parse and it was already validated before being admitted to the mempool.
580 580
 	_, addresses, _, _ := txscript.ExtractPkScriptAddrs(pkScript,
581 581
 		idx.chainParams)
@@ -589,7 +589,7 @@ func (idx *AddrIndex) indexUnconfirmedAddresses(pkScript []byte, tx *util.Tx) {
589 589
 		idx.unconfirmedLock.Lock()
590 590
 		addrIndexEntry := idx.txnsByAddr[addrKey]
591 591
 		if addrIndexEntry == nil {
592
-			addrIndexEntry = make(map[chainhash.Hash]*util.Tx)
592
+			addrIndexEntry = make(map[chainhash.Hash]*wire.Tx)
593 593
 			idx.txnsByAddr[addrKey] = addrIndexEntry
594 594
 		}
595 595
 		addrIndexEntry[*tx.Hash()] = tx
@@ -605,7 +605,7 @@ func (idx *AddrIndex) indexUnconfirmedAddresses(pkScript []byte, tx *util.Tx) {
605 605
 }
606 606
 
607 607
 // AddUnconfirmedTx adds all addresses related to the transaction to the unconfirmed (memory-only) address index. NOTE: This transaction MUST have already been validated by the memory pool before calling this function with it and have all of the inputs available in the provided utxo view.  Failure to do so could result in some or all addresses not being indexed. This function is safe for concurrent access.
608
-func (idx *AddrIndex) AddUnconfirmedTx(tx *util.Tx, utxoView *blockchain.UtxoViewpoint) {
608
+func (idx *AddrIndex) AddUnconfirmedTx(tx *wire.Tx, utxoView *blockchain.UtxoViewpoint) {
609 609
 	// Index addresses of all referenced previous transaction outputs.
610 610
 	// The existence checks are elided since this is only called after the transaction has already been validated and thus all inputs are already known to exist.
611