Skip to content

Commit

Permalink
Rename global constants and prevent stalled mining
Browse files Browse the repository at this point in the history
  • Loading branch information
jstnryan committed Mar 27, 2022
1 parent 7b0df85 commit cf62527
Show file tree
Hide file tree
Showing 19 changed files with 174 additions and 173 deletions.
4 changes: 2 additions & 2 deletions block.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ func NewBlock(previous BlockID, height int64, target, chainWork BlockID, transac
*Block, error) {

// enforce the hard cap transaction limit
if len(transactions) > MAX_TRANSACTIONS_PER_BLOCK {
if len(transactions) > MaxTransactionsPerBlock {
return nil, fmt.Errorf("Transaction list size exceeds limit per block")
}

Expand All @@ -63,7 +63,7 @@ func NewBlock(previous BlockID, height int64, target, chainWork BlockID, transac
Time: time.Now().Unix(), // just use the system time
Target: target,
ChainWork: computeChainWork(target, chainWork),
Nonce: rand.Int63n(MAX_NUMBER),
Nonce: rand.Int63n(MaxNumber),
Height: height,
TransactionCount: int32(len(transactions)),
},
Expand Down
12 changes: 6 additions & 6 deletions block_header_hasher_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,11 @@ func makeTestBlock(n int) (*Block, error) {
privKey2 := ed25519.NewKeyFromSeed([]byte(seed2))
pubKey2 := privKey2.Public().(ed25519.PublicKey)

matures := MAX_NUMBER
expires := MAX_NUMBER
height := MAX_NUMBER
amount := int64(MAX_MONEY)
fee := int64(MAX_MONEY)
matures := MaxNumber
expires := MaxNumber
height := MaxNumber
amount := int64(MaxMoney)
fee := int64(MaxMoney)

tx := NewTransaction(pubKey, pubKey2, amount, fee, matures, height, expires, "こんにちは")
if len(tx.Memo) != 15 {
Expand All @@ -49,7 +49,7 @@ func makeTestBlock(n int) (*Block, error) {
}

// create the block
targetBytes, err := hex.DecodeString(INITIAL_TARGET)
targetBytes, err := hex.DecodeString(InitialTarget)
if err != nil {
return nil, err
}
Expand Down
4 changes: 2 additions & 2 deletions block_storage_disk_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@ func TestEncodeBlockHeader(t *testing.T) {
}

// create a coinbase
tx := NewTransaction(nil, pubKey, INITIAL_COINBASE_REWARD, 0, 0, 0, 0, "hello")
tx := NewTransaction(nil, pubKey, InitialCoinbaseReward, 0, 0, 0, 0, "hello")

// create a block
targetBytes, err := hex.DecodeString(INITIAL_TARGET)
targetBytes, err := hex.DecodeString(InitialTarget)
if err != nil {
t.Fatal(err)
}
Expand Down
6 changes: 3 additions & 3 deletions client/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ func main() {
pubKeyPtr := flag.String("pubkey", "", "A public key which receives newly mined block rewards")
dataDirPtr := flag.String("datadir", "", "Path to a directory to save block chain data")
memoPtr := flag.String("memo", "", "A memo to include in newly mined blocks")
portPtr := flag.Int("port", DEFAULT_CRUZBIT_PORT, "Port to listen for incoming peer connections")
portPtr := flag.Int("port", DefaultCruzbitPort, "Port to listen for incoming peer connections")
peerPtr := flag.String("peer", "", "Address of a peer to connect to")
upnpPtr := flag.Bool("upnp", false, "Attempt to forward the cruzbit port on your router with UPnP")
dnsSeedPtr := flag.Bool("dnsseed", false, "Run a DNS server to allow others to find peers")
Expand All @@ -42,7 +42,7 @@ func main() {
keyFilePtr := flag.String("keyfile", "", "Path to a file containing public keys to use when mining")
tlsCertPtr := flag.String("tlscert", "", "Path to a file containing a PEM-encoded X.509 certificate to use with TLS")
tlsKeyPtr := flag.String("tlskey", "", "Path to a file containing a PEM-encoded private key to use with TLS")
inLimitPtr := flag.Int("inlimit", MAX_INBOUND_PEER_CONNECTIONS, "Limit for the number of inbound peer connections.")
inLimitPtr := flag.Int("inlimit", MaxInboundPeerConnections, "Limit for the number of inbound peer connections.")
banListPtr := flag.String("banlist", "", "Path to a file containing a list of banned host addresses")
flag.Parse()

Expand All @@ -59,7 +59,7 @@ func main() {
if len(*peerPtr) != 0 {
// add default port, if one was not supplied
if i := strings.LastIndex(*peerPtr, ":"); i < 0 {
*peerPtr = *peerPtr + ":" + strconv.Itoa(DEFAULT_CRUZBIT_PORT)
*peerPtr = *peerPtr + ":" + strconv.Itoa(DefaultCruzbitPort)
}
}

Expand Down
61 changes: 31 additions & 30 deletions constants.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,73 +7,74 @@ package cruzbit
// we could have played with these but we're introducing significant enough changes
// already IMO, so let's keep the scope of this experiment as small as we can

const CRUZBITS_PER_CRUZ = 100000000
const CruzbitsPerCruz = 100000000

const INITIAL_COINBASE_REWARD = 50 * CRUZBITS_PER_CRUZ
const InitialCoinbaseReward = 50 * CruzbitsPerCruz

const COINBASE_MATURITY = 100 // blocks
const CoinbaseMaturity = 100 // blocks

const INITIAL_TARGET = "00000000ffff0000000000000000000000000000000000000000000000000000"
const InitialTarget = "00000000ffff0000000000000000000000000000000000000000000000000000"

const MAX_FUTURE_SECONDS = 2 * 60 * 60 // 2 hours
const MaxFutureSeconds = 2 * 60 * 60 // 2 hours

const MAX_MONEY = 21000000 * CRUZBITS_PER_CRUZ
const MaxMoney = 21000000 * CruzbitsPerCruz

const RETARGET_INTERVAL = 2016 // 2 weeks in blocks
const RetargetInterval = 2016 // 2 weeks in blocks

const RETARGET_TIME = 1209600 // 2 weeks in seconds
const RetargetTime = 1209600 // 2 weeks in seconds

const TARGET_SPACING = 600 // every 10 minutes
const TargetSpacing = 600 // every 10 minutes

const NUM_BLOCKS_FOR_MEDIAN_TMESTAMP = 11
const NumBlocksForMedianTmestamp = 11

const BLOCKS_UNTIL_REWARD_HALVING = 210000 // 4 years in blocks
const BlocksUntilRewardHalving = 210000 // 4 years in blocks

// the below value affects ledger consensus and comes from bitcoin cash

const RETARGET_SMA_WINDOW = 144 // 1 day in blocks
const RetargetSmaWindow = 144 // 1 day in blocks

// the below values affect ledger consensus and are new as of our ledger

const INITIAL_MAX_TRANSACTIONS_PER_BLOCK = 10000 // 16.666... tx/sec, ~4 MBish in JSON
const InitialMaxTransactionsPerBlock = 10000 // 16.666... tx/sec, ~4 MBish in JSON

const BLOCKS_UNTIL_TRANSACTIONS_PER_BLOCK_DOUBLING = 105000 // 2 years in blocks
const BlocksUntilTransactionsPerBlockDoubling = 105000 // 2 years in blocks

const MAX_TRANSACTIONS_PER_BLOCK = 1<<31 - 1
const MaxTransactionsPerBlock = 1<<31 - 1

const MAX_TRANSACTIONS_PER_BLOCK_EXCEEDED_AT_HEIGHT = 1852032 // pre-calculated
const MaxTransactionsPerBlockExceededAtHeight = 1852032 // pre-calculated

const BLOCKS_UNTIL_NEW_SERIES = 1008 // 1 week in blocks
const BlocksUntilNewSeries = 1008 // 1 week in blocks

const MAX_MEMO_LENGTH = 100 // bytes (ascii/utf8 only)
const MaxMemoLength = 100 // bytes (ascii/utf8 only)

// given our JSON protocol we should respect Javascript's Number.MAX_SAFE_INTEGER value
const MAX_NUMBER int64 = 1<<53 - 1
const MaxNumber int64 = 1<<53 - 1

// height at which we switch from bitcoin's difficulty adjustment algorithm to bitcoin cash's algorithm
const BITCOIN_CASH_RETARGET_ALGORITHM_HEIGHT = 28861
const BitcoinCashRetargetAlgorithmHeight = 28861

// the below values only affect peering behavior and do not affect ledger consensus

const DEFAULT_CRUZBIT_PORT = 8831
const DefaultCruzbitPort = 8831

const MAX_OUTBOUND_PEER_CONNECTIONS = 8
const MaxOutboundPeerConnections = 8

const MAX_INBOUND_PEER_CONNECTIONS = 128
const MaxInboundPeerConnections = 128

const MAX_INBOUND_PEER_CONNECTIONS_FROM_SAME_HOST = 4
const MaxInboundPeerConnectionsFromSameHost = 4

const MAX_TIP_AGE = 24 * 60 * 60
// MaxTipAge is originally 24 hours, but has been increased to 30 days to prevent deadlock caused by low mining volume
const MaxTipAge = 24 * 60 * 60 * 30

const MAX_PROTOCOL_MESSAGE_LENGTH = 2 * 1024 * 1024 // doesn't apply to blocks
const MaxProtocolMessageLength = 2 * 1024 * 1024 // doesn't apply to blocks

// the below values are mining policy and also do not affect ledger consensus

// if you change this it needs to be less than the maximum at the current height
const MAX_TRANSACTIONS_TO_INCLUDE_PER_BLOCK = INITIAL_MAX_TRANSACTIONS_PER_BLOCK
const MaxTransactionsToIncludePerBlock = InitialMaxTransactionsPerBlock

const MAX_TRANSACTION_QUEUE_LENGTH = MAX_TRANSACTIONS_TO_INCLUDE_PER_BLOCK * 10
const MaxTransactionQueueLength = MaxTransactionsToIncludePerBlock * 10

const MIN_FEE_CRUZBITS = 1000000 // 0.01 cruz
const MinFeeCruzbits = 1000000 // 0.01 cruz

const MIN_AMOUNT_CRUZBITS = 1000000 // 0.01 cruz
const MinAmountCruzbits = 1000000 // 0.01 cruz
4 changes: 2 additions & 2 deletions dns.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ func (d *DNSSeeder) handleQuery(m *dns.Msg, externalIP string) {
return
}
ip, port, _ := net.SplitHostPort(addr)
if port != strconv.Itoa(DEFAULT_CRUZBIT_PORT) {
if port != strconv.Itoa(DefaultCruzbitPort) {
continue
}
rr, err := dns.NewRR(fmt.Sprintf("%s A %s", q.Name, ip))
Expand Down Expand Up @@ -141,7 +141,7 @@ func dnsQueryForPeers() ([]string, error) {
for _, answer := range r.Answer {
a := answer.(*dns.A)
log.Printf("Seeder returned: %s\n", a.A.String())
peers = append(peers, a.A.String()+":"+strconv.Itoa(DEFAULT_CRUZBIT_PORT))
peers = append(peers, a.A.String()+":"+strconv.Itoa(DefaultCruzbitPort))
}
}
return peers, nil
Expand Down
18 changes: 9 additions & 9 deletions inspector/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ func main() {
if err != nil {
log.Fatal(err)
}
log.Printf("Current balance: %.8f\n", aurora.Bold(float64(balance)/CRUZBITS_PER_CRUZ))
log.Printf("Current balance: %.8f\n", aurora.Bold(float64(balance)/CruzbitsPerCruz))

case "balance_at":
if pubKey == nil {
Expand All @@ -120,7 +120,7 @@ func main() {
if err != nil {
log.Fatal(err)
}
log.Printf("Balance at height %d: %.8f\n", *heightPtr, aurora.Bold(float64(balance)/CRUZBITS_PER_CRUZ))
log.Printf("Balance at height %d: %.8f\n", *heightPtr, aurora.Bold(float64(balance)/CruzbitsPerCruz))

case "block_at":
id, err := ledger.GetBlockIDForHeight(int64(*heightPtr))
Expand Down Expand Up @@ -296,16 +296,16 @@ func verify(ledger Ledger, blockStore BlockStorage, pubKey ed25519.PublicKey, he

if pubKey == nil {
// compute expected total balance
if height-COINBASE_MATURITY >= 0 {
if height-CoinbaseMaturity >= 0 {
// sum all mature rewards per schedule
var i int64
for i = 0; i <= height-COINBASE_MATURITY; i++ {
for i = 0; i <= height-CoinbaseMaturity; i++ {
expect += BlockCreationReward(i)
}

// account for fees included in immature rewards
var immatureFees int64
for i = height - COINBASE_MATURITY + 1; i <= height; i++ {
for i = height - CoinbaseMaturity + 1; i <= height; i++ {
if i < 0 {
continue
}
Expand Down Expand Up @@ -352,13 +352,13 @@ func verify(ledger Ledger, blockStore BlockStorage, pubKey ed25519.PublicKey, he
log.Fatalf("%s: At height %d, we expected %.8f cruz but we found %.8f\n",
aurora.Bold(aurora.Red("FAILURE")),
aurora.Bold(height),
aurora.Bold(float64(expect)/CRUZBITS_PER_CRUZ),
aurora.Bold(float64(found)/CRUZBITS_PER_CRUZ))
aurora.Bold(float64(expect)/CruzbitsPerCruz),
aurora.Bold(float64(found)/CruzbitsPerCruz))
}

log.Printf("%s: At height %d, we expected %.8f cruz and we found %.8f\n",
aurora.Bold(aurora.Green("SUCCESS")),
aurora.Bold(height),
aurora.Bold(float64(expect)/CRUZBITS_PER_CRUZ),
aurora.Bold(float64(found)/CRUZBITS_PER_CRUZ))
aurora.Bold(float64(expect)/CruzbitsPerCruz),
aurora.Bold(float64(found)/CruzbitsPerCruz))
}
22 changes: 11 additions & 11 deletions ledger_disk.go
Original file line number Diff line number Diff line change
Expand Up @@ -177,15 +177,15 @@ func (l LedgerDisk) ConnectBlock(id BlockID, block *Block) ([]TransactionID, err
// depend on coinbases.
txToApply = nil

if block.Header.Height-COINBASE_MATURITY >= 0 {
if block.Header.Height-CoinbaseMaturity >= 0 {
// mature the coinbase from 100 blocks ago now
oldID, err := l.GetBlockIDForHeight(block.Header.Height - COINBASE_MATURITY)
oldID, err := l.GetBlockIDForHeight(block.Header.Height - CoinbaseMaturity)
if err != nil {
return nil, err
}
if oldID == nil {
return nil, fmt.Errorf("Missing block at height %d\n",
block.Header.Height-COINBASE_MATURITY)
block.Header.Height-CoinbaseMaturity)
}

// we could store the last 100 coinbases on our own in memory if we end up needing to
Expand Down Expand Up @@ -273,8 +273,8 @@ func (l LedgerDisk) ConnectBlock(id BlockID, block *Block) ([]TransactionID, err
batch.Put(key, ctBytes)

// prune historic transaction and public key transaction indices now
if l.prune && block.Header.Height >= 2*BLOCKS_UNTIL_NEW_SERIES {
if err := l.pruneIndices(block.Header.Height-2*BLOCKS_UNTIL_NEW_SERIES, batch); err != nil {
if l.prune && block.Header.Height >= 2*BlocksUntilNewSeries {
if err := l.pruneIndices(block.Header.Height-2*BlocksUntilNewSeries, batch); err != nil {
return nil, err
}
}
Expand Down Expand Up @@ -332,15 +332,15 @@ func (l LedgerDisk) DisconnectBlock(id BlockID, block *Block) ([]TransactionID,
// coinbase doesn't affect recipient balance for 100 more blocks
txToUndo = nil

if block.Header.Height-COINBASE_MATURITY >= 0 {
if block.Header.Height-CoinbaseMaturity >= 0 {
// undo the effect of the coinbase from 100 blocks ago now
oldID, err := l.GetBlockIDForHeight(block.Header.Height - COINBASE_MATURITY)
oldID, err := l.GetBlockIDForHeight(block.Header.Height - CoinbaseMaturity)
if err != nil {
return nil, err
}
if oldID == nil {
return nil, fmt.Errorf("Missing block at height %d\n",
block.Header.Height-COINBASE_MATURITY)
block.Header.Height-CoinbaseMaturity)
}
oldTx, _, err := l.blockStore.GetTransaction(*oldID, 0)
if err != nil {
Expand Down Expand Up @@ -422,8 +422,8 @@ func (l LedgerDisk) DisconnectBlock(id BlockID, block *Block) ([]TransactionID,
batch.Put(key, ctBytes)

// restore historic indices now
if l.prune && block.Header.Height >= 2*BLOCKS_UNTIL_NEW_SERIES {
if err := l.restoreIndices(block.Header.Height-2*BLOCKS_UNTIL_NEW_SERIES, batch); err != nil {
if l.prune && block.Header.Height >= 2*BlocksUntilNewSeries {
if err := l.restoreIndices(block.Header.Height-2*BlocksUntilNewSeries, batch); err != nil {
return nil, err
}
}
Expand Down Expand Up @@ -853,7 +853,7 @@ func (l LedgerDisk) GetPublicKeyBalanceAt(pubKey ed25519.PublicKey, height int64
return 0, err
}

if index == 0 && height > currentHeight-COINBASE_MATURITY {
if index == 0 && height > currentHeight-CoinbaseMaturity {
// coinbase isn't mature
continue
}
Expand Down
8 changes: 4 additions & 4 deletions miner.go
Original file line number Diff line number Diff line change
Expand Up @@ -154,8 +154,8 @@ func (m *Miner) run() {
continue
}

if MAX_TRANSACTIONS_TO_INCLUDE_PER_BLOCK != 0 &&
len(block.Transactions) >= MAX_TRANSACTIONS_TO_INCLUDE_PER_BLOCK {
if MaxTransactionsToIncludePerBlock != 0 &&
len(block.Transactions) >= MaxTransactionsToIncludePerBlock {
log.Printf("Per-block transaction limit hit (%d)\n", len(block.Transactions))
continue
}
Expand Down Expand Up @@ -229,7 +229,7 @@ func (m *Miner) run() {
} else {
// no solution yet
block.Header.Nonce += attempts
if block.Header.Nonce > MAX_NUMBER {
if block.Header.Nonce > MaxNumber {
block.Header.Nonce = 0
}
}
Expand All @@ -256,7 +256,7 @@ func createNextBlock(tipID BlockID, tipHeader *BlockHeader, txQueue TransactionQ
blockStore BlockStorage, ledger Ledger, pubKey ed25519.PublicKey, memo string) (*Block, error) {

// fetch transactions to confirm from the queue
txs := txQueue.Get(MAX_TRANSACTIONS_TO_INCLUDE_PER_BLOCK - 1)
txs := txQueue.Get(MaxTransactionsToIncludePerBlock - 1)

// calculate total fees
var fees int64 = 0
Expand Down
Loading

0 comments on commit cf62527

Please sign in to comment.