diff --git a/account/account.go b/account/account.go index 4105588f..26f2668f 100644 --- a/account/account.go +++ b/account/account.go @@ -38,8 +38,8 @@ func HashSignBytes(chainID string, o Signable) []byte { type Account struct { Address []byte `json:"address"` PubKey PubKey `json:"pub_key"` - Sequence uint `json:"sequence"` - Balance uint64 `json:"balance"` + Sequence int `json:"sequence"` + Balance int64 `json:"balance"` Code []byte `json:"code"` // VM code StorageRoot []byte `json:"storage_root"` // VM storage merkle root. } diff --git a/binary/byteslice.go b/binary/byteslice.go index 87a42785..2e93ab93 100644 --- a/binary/byteslice.go +++ b/binary/byteslice.go @@ -10,12 +10,12 @@ const ( ) func WriteByteSlice(bz []byte, w io.Writer, n *int64, err *error) { - WriteUvarint(uint(len(bz)), w, n, err) + WriteVarint(len(bz), w, n, err) WriteTo(bz, w, n, err) } func ReadByteSlice(r io.Reader, n *int64, err *error) []byte { - length := int(ReadUvarint(r, n, err)) + length := ReadVarint(r, n, err) if *err != nil { return nil } @@ -36,7 +36,7 @@ func ReadByteSlice(r io.Reader, n *int64, err *error) []byte { //----------------------------------------------------------------------------- func WriteByteSlices(bzz [][]byte, w io.Writer, n *int64, err *error) { - WriteUvarint(uint(len(bzz)), w, n, err) + WriteVarint(len(bzz), w, n, err) for _, bz := range bzz { WriteByteSlice(bz, w, n, err) if *err != nil { @@ -46,7 +46,7 @@ func WriteByteSlices(bzz [][]byte, w io.Writer, n *int64, err *error) { } func ReadByteSlices(r io.Reader, n *int64, err *error) [][]byte { - length := int(ReadUvarint(r, n, err)) + length := ReadVarint(r, n, err) if *err != nil { return nil } diff --git a/binary/int.go b/binary/int.go index d35c82bf..3be5f224 100644 --- a/binary/int.go +++ b/binary/int.go @@ -219,6 +219,9 @@ func ReadVarint(r io.Reader, n *int64, err *error) int { return 0 } if size == 0 { + if negate { + setFirstErr(err, errors.New("Varint does not allow negative zero")) + } return 0 } buf := make([]byte, 8) diff --git a/binary/reflect.go b/binary/reflect.go index f23acb38..6eac5a46 100644 --- a/binary/reflect.go +++ b/binary/reflect.go @@ -432,7 +432,7 @@ func writeReflectBinary(rv reflect.Value, rt reflect.Type, opts Options, w io.Wr } else { // Write length length := rv.Len() - WriteUvarint(uint(length), w, n, err) + WriteVarint(length, w, n, err) // Write elems for i := 0; i < length; i++ { elemRv := rv.Index(i) diff --git a/blockchain/pool.go b/blockchain/pool.go index 5c8b280b..1d82136e 100644 --- a/blockchain/pool.go +++ b/blockchain/pool.go @@ -36,8 +36,8 @@ var ( type BlockPool struct { // block requests requestsMtx sync.Mutex - requests map[uint]*bpRequest - height uint // the lowest key in requests. + requests map[int]*bpRequest + height int // the lowest key in requests. numUnassigned int32 // number of requests not yet assigned to a peer numPending int32 // number of requests pending assignment or block response @@ -52,11 +52,11 @@ type BlockPool struct { running int32 // atomic } -func NewBlockPool(start uint, requestsCh chan<- BlockRequest, timeoutsCh chan<- string) *BlockPool { +func NewBlockPool(start int, requestsCh chan<- BlockRequest, timeoutsCh chan<- string) *BlockPool { return &BlockPool{ peers: make(map[string]*bpPeer), - requests: make(map[uint]*bpRequest), + requests: make(map[int]*bpRequest), height: start, numUnassigned: 0, numPending: 0, @@ -108,7 +108,7 @@ RUN_LOOP: } } -func (pool *BlockPool) GetStatus() (uint, int32) { +func (pool *BlockPool) GetStatus() (int, int32) { pool.requestsMtx.Lock() // Lock defer pool.requestsMtx.Unlock() @@ -146,7 +146,7 @@ func (pool *BlockPool) PopRequest() { // Invalidates the block at pool.height. // Remove the peer and request from others. -func (pool *BlockPool) RedoRequest(height uint) { +func (pool *BlockPool) RedoRequest(height int) { pool.requestsMtx.Lock() // Lock defer pool.requestsMtx.Unlock() @@ -165,7 +165,7 @@ func (pool *BlockPool) RedoRequest(height uint) { go requestRoutine(pool, height) } -func (pool *BlockPool) hasBlock(height uint) bool { +func (pool *BlockPool) hasBlock(height int) bool { pool.requestsMtx.Lock() // Lock defer pool.requestsMtx.Unlock() @@ -173,7 +173,7 @@ func (pool *BlockPool) hasBlock(height uint) bool { return request != nil && request.block != nil } -func (pool *BlockPool) setPeerForRequest(height uint, peerId string) { +func (pool *BlockPool) setPeerForRequest(height int, peerId string) { pool.requestsMtx.Lock() // Lock defer pool.requestsMtx.Unlock() @@ -185,7 +185,7 @@ func (pool *BlockPool) setPeerForRequest(height uint, peerId string) { request.peerId = peerId } -func (pool *BlockPool) removePeerForRequest(height uint, peerId string) { +func (pool *BlockPool) removePeerForRequest(height int, peerId string) { pool.requestsMtx.Lock() // Lock defer pool.requestsMtx.Unlock() @@ -224,7 +224,7 @@ func (pool *BlockPool) getPeer(peerId string) *bpPeer { } // Sets the peer's alleged blockchain height. -func (pool *BlockPool) SetPeerHeight(peerId string, height uint) { +func (pool *BlockPool) SetPeerHeight(peerId string, height int) { pool.peersMtx.Lock() // Lock defer pool.peersMtx.Unlock() @@ -250,7 +250,7 @@ func (pool *BlockPool) RemovePeer(peerId string) { // Pick an available peer with at least the given minHeight. // If no peers are available, returns nil. -func (pool *BlockPool) pickIncrAvailablePeer(minHeight uint) *bpPeer { +func (pool *BlockPool) pickIncrAvailablePeer(minHeight int) *bpPeer { pool.peersMtx.Lock() defer pool.peersMtx.Unlock() @@ -282,7 +282,7 @@ func (pool *BlockPool) makeNextRequest() { pool.requestsMtx.Lock() // Lock defer pool.requestsMtx.Unlock() - nextHeight := pool.height + uint(len(pool.requests)) + nextHeight := pool.height + len(pool.requests) request := &bpRequest{ height: nextHeight, peerId: "", @@ -296,7 +296,7 @@ func (pool *BlockPool) makeNextRequest() { go requestRoutine(pool, nextHeight) } -func (pool *BlockPool) sendRequest(height uint, peerId string) { +func (pool *BlockPool) sendRequest(height int, peerId string) { if atomic.LoadInt32(&pool.running) == 0 { return } @@ -315,7 +315,7 @@ func (pool *BlockPool) debug() string { defer pool.requestsMtx.Unlock() str := "" - for h := pool.height; h < pool.height+uint(len(pool.requests)); h++ { + for h := pool.height; h < pool.height+len(pool.requests); h++ { if pool.requests[h] == nil { str += Fmt("H(%v):X ", h) } else { @@ -330,12 +330,12 @@ func (pool *BlockPool) debug() string { type bpPeer struct { id string - height uint + height int numRequests int32 } type bpRequest struct { - height uint + height int peerId string block *types.Block } @@ -344,7 +344,7 @@ type bpRequest struct { // Responsible for making more requests as necessary // Returns only when a block is found (e.g. AddBlock() is called) -func requestRoutine(pool *BlockPool, height uint) { +func requestRoutine(pool *BlockPool, height int) { for { var peer *bpPeer = nil PICK_LOOP: @@ -393,6 +393,6 @@ func requestRoutine(pool *BlockPool, height uint) { //------------------------------------- type BlockRequest struct { - Height uint + Height int PeerId string } diff --git a/blockchain/pool_test.go b/blockchain/pool_test.go index c07a11d8..e6ff3be4 100644 --- a/blockchain/pool_test.go +++ b/blockchain/pool_test.go @@ -11,14 +11,14 @@ import ( type testPeer struct { id string - height uint + height int } -func makePeers(numPeers int, minHeight, maxHeight uint) map[string]testPeer { +func makePeers(numPeers int, minHeight, maxHeight int) map[string]testPeer { peers := make(map[string]testPeer, numPeers) for i := 0; i < numPeers; i++ { peerId := RandStr(12) - height := minHeight + uint(rand.Intn(int(maxHeight-minHeight))) + height := minHeight + rand.Intn(maxHeight-minHeight) peers[peerId] = testPeer{peerId, height} } return peers @@ -26,7 +26,7 @@ func makePeers(numPeers int, minHeight, maxHeight uint) map[string]testPeer { func TestBasic(t *testing.T) { peers := makePeers(10, 0, 1000) - start := uint(42) + start := 42 timeoutsCh := make(chan string, 100) requestsCh := make(chan BlockRequest, 100) pool := NewBlockPool(start, requestsCh, timeoutsCh) @@ -78,7 +78,7 @@ func TestBasic(t *testing.T) { func TestTimeout(t *testing.T) { peers := makePeers(10, 0, 1000) - start := uint(42) + start := 42 timeoutsCh := make(chan string, 100) requestsCh := make(chan BlockRequest, 100) pool := NewBlockPool(start, requestsCh, timeoutsCh) diff --git a/blockchain/reactor.go b/blockchain/reactor.go index 01d0865d..fa7ff693 100644 --- a/blockchain/reactor.go +++ b/blockchain/reactor.go @@ -301,7 +301,7 @@ func DecodeMessage(bz []byte) (msgType byte, msg BlockchainMessage, err error) { //------------------------------------- type bcBlockRequestMessage struct { - Height uint + Height int } func (m *bcBlockRequestMessage) String() string { @@ -321,7 +321,7 @@ func (m *bcBlockResponseMessage) String() string { //------------------------------------- type bcStatusRequestMessage struct { - Height uint + Height int } func (m *bcStatusRequestMessage) String() string { @@ -331,7 +331,7 @@ func (m *bcStatusRequestMessage) String() string { //------------------------------------- type bcStatusResponseMessage struct { - Height uint + Height int } func (m *bcStatusResponseMessage) String() string { diff --git a/blockchain/store.go b/blockchain/store.go index d0618a23..fa7e696e 100644 --- a/blockchain/store.go +++ b/blockchain/store.go @@ -25,7 +25,7 @@ well as the Validation. In the future this may change, perhaps by moving the Validation data outside the Block. */ type BlockStore struct { - height uint + height int db dbm.DB } @@ -38,7 +38,7 @@ func NewBlockStore(db dbm.DB) *BlockStore { } // Height() returns the last known contiguous block height. -func (bs *BlockStore) Height() uint { +func (bs *BlockStore) Height() int { return bs.height } @@ -50,7 +50,7 @@ func (bs *BlockStore) GetReader(key []byte) io.Reader { return bytes.NewReader(bytez) } -func (bs *BlockStore) LoadBlock(height uint) *types.Block { +func (bs *BlockStore) LoadBlock(height int) *types.Block { var n int64 var err error r := bs.GetReader(calcBlockMetaKey(height)) @@ -62,7 +62,7 @@ func (bs *BlockStore) LoadBlock(height uint) *types.Block { panic(Fmt("Error reading block meta: %v", err)) } bytez := []byte{} - for i := uint(0); i < meta.PartsHeader.Total; i++ { + for i := 0; i < meta.PartsHeader.Total; i++ { part := bs.LoadBlockPart(height, i) bytez = append(bytez, part.Bytes...) } @@ -73,7 +73,7 @@ func (bs *BlockStore) LoadBlock(height uint) *types.Block { return block } -func (bs *BlockStore) LoadBlockPart(height uint, index uint) *types.Part { +func (bs *BlockStore) LoadBlockPart(height int, index int) *types.Part { var n int64 var err error r := bs.GetReader(calcBlockPartKey(height, index)) @@ -87,7 +87,7 @@ func (bs *BlockStore) LoadBlockPart(height uint, index uint) *types.Part { return part } -func (bs *BlockStore) LoadBlockMeta(height uint) *types.BlockMeta { +func (bs *BlockStore) LoadBlockMeta(height int) *types.BlockMeta { var n int64 var err error r := bs.GetReader(calcBlockMetaKey(height)) @@ -103,7 +103,7 @@ func (bs *BlockStore) LoadBlockMeta(height uint) *types.BlockMeta { // The +2/3 and other Precommit-votes for block at `height`. // This Validation comes from block.LastValidation for `height+1`. -func (bs *BlockStore) LoadBlockValidation(height uint) *types.Validation { +func (bs *BlockStore) LoadBlockValidation(height int) *types.Validation { var n int64 var err error r := bs.GetReader(calcBlockValidationKey(height)) @@ -118,7 +118,7 @@ func (bs *BlockStore) LoadBlockValidation(height uint) *types.Validation { } // NOTE: the Precommit-vote heights are for the block at `height` -func (bs *BlockStore) LoadSeenValidation(height uint) *types.Validation { +func (bs *BlockStore) LoadSeenValidation(height int) *types.Validation { var n int64 var err error r := bs.GetReader(calcSeenValidationKey(height)) @@ -152,7 +152,7 @@ func (bs *BlockStore) SaveBlock(block *types.Block, blockParts *types.PartSet, s bs.db.Set(calcBlockMetaKey(height), metaBytes) // Save block parts - for i := uint(0); i < blockParts.Total(); i++ { + for i := 0; i < blockParts.Total(); i++ { bs.saveBlockPart(height, i, blockParts.GetPart(i)) } @@ -171,7 +171,7 @@ func (bs *BlockStore) SaveBlock(block *types.Block, blockParts *types.PartSet, s bs.height = height } -func (bs *BlockStore) saveBlockPart(height uint, index uint, part *types.Part) { +func (bs *BlockStore) saveBlockPart(height int, index int, part *types.Part) { if height != bs.height+1 { panic(Fmt("BlockStore can only save contiguous blocks. Wanted %v, got %v", bs.height+1, height)) } @@ -181,19 +181,19 @@ func (bs *BlockStore) saveBlockPart(height uint, index uint, part *types.Part) { //----------------------------------------------------------------------------- -func calcBlockMetaKey(height uint) []byte { +func calcBlockMetaKey(height int) []byte { return []byte(fmt.Sprintf("H:%v", height)) } -func calcBlockPartKey(height uint, partIndex uint) []byte { +func calcBlockPartKey(height int, partIndex int) []byte { return []byte(fmt.Sprintf("P:%v:%v", height, partIndex)) } -func calcBlockValidationKey(height uint) []byte { +func calcBlockValidationKey(height int) []byte { return []byte(fmt.Sprintf("V:%v", height)) } -func calcSeenValidationKey(height uint) []byte { +func calcSeenValidationKey(height int) []byte { return []byte(fmt.Sprintf("SV:%v", height)) } @@ -202,7 +202,7 @@ func calcSeenValidationKey(height uint) []byte { var blockStoreKey = []byte("blockStore") type BlockStoreStateJSON struct { - Height uint + Height int } func (bsj BlockStoreStateJSON) Save(db dbm.DB) { diff --git a/cmd/barak/barak.go b/cmd/barak/barak.go index de0a9c62..affe1693 100644 --- a/cmd/barak/barak.go +++ b/cmd/barak/barak.go @@ -20,7 +20,7 @@ import ( type BarakOptions struct { Validators []Validator ListenAddress string - StartNonce uint64 + StartNonce int64 Registries []string } @@ -74,7 +74,7 @@ func NewBarakFromOptions(opt *BarakOptions) *Barak { type Barak struct { mtx sync.Mutex pid int - nonce uint64 + nonce int64 processes map[string]*pcm.Process validators []Validator listeners []net.Listener @@ -82,7 +82,7 @@ type Barak struct { registries []string } -func NewBarak(rootDir string, nonce uint64, validators []Validator) *Barak { +func NewBarak(rootDir string, nonce int64, validators []Validator) *Barak { return &Barak{ pid: os.Getpid(), nonce: nonce, @@ -243,7 +243,7 @@ func (brk *Barak) WritePidFile() { } } -func (brk *Barak) CheckIncrNonce(newNonce uint64) error { +func (brk *Barak) CheckIncrNonce(newNonce int64) error { brk.mtx.Lock() defer brk.mtx.Unlock() if brk.nonce+1 != newNonce { diff --git a/cmd/barak/types/command.go b/cmd/barak/types/command.go index 92df4691..074502e0 100644 --- a/cmd/barak/types/command.go +++ b/cmd/barak/types/command.go @@ -11,7 +11,7 @@ type AuthCommand struct { } type NoncedCommand struct { - Nonce uint64 + Nonce int64 Command } diff --git a/cmd/barak/types/responses.go b/cmd/barak/types/responses.go index 85fc77bc..f8b138d8 100644 --- a/cmd/barak/types/responses.go +++ b/cmd/barak/types/responses.go @@ -6,7 +6,7 @@ import ( type ResponseStatus struct { Pid int - Nonce uint64 + Nonce int64 Validators []Validator } diff --git a/cmd/barak/types/validator.go b/cmd/barak/types/validator.go index 252f3dc5..2db48609 100644 --- a/cmd/barak/types/validator.go +++ b/cmd/barak/types/validator.go @@ -5,6 +5,6 @@ import ( ) type Validator struct { - VotingPower uint64 + VotingPower int64 PubKey acm.PubKey } diff --git a/cmd/barak/validate.go b/cmd/barak/validate.go index df7b420b..9653f732 100644 --- a/cmd/barak/validate.go +++ b/cmd/barak/validate.go @@ -6,8 +6,8 @@ import ( ) func validate(signBytes []byte, validators []Validator, signatures []acm.Signature) bool { - var signedPower uint64 - var totalPower uint64 + var signedPower int64 + var totalPower int64 for i, val := range validators { if val.PubKey.VerifyBytes(signBytes, signatures[i]) { signedPower += val.VotingPower diff --git a/cmd/debora/commands.go b/cmd/debora/commands.go index 316e48ee..dfca0737 100644 --- a/cmd/debora/commands.go +++ b/cmd/debora/commands.go @@ -104,7 +104,7 @@ func DownloadFile(privKey acm.PrivKey, remote string, command btypes.CommandServ // Utility method to get nonce from the remote. // The next command should include the returned nonce+1 as nonce. -func GetNonce(remote string) (uint64, error) { +func GetNonce(remote string) (int64, error) { response, err := GetStatus(remote) return response.Nonce, err } @@ -118,7 +118,7 @@ func GetStatus(remote string) (response btypes.ResponseStatus, err error) { } // Each developer runs this -func SignCommand(privKey acm.PrivKey, nonce uint64, command btypes.Command) ([]byte, acm.Signature) { +func SignCommand(privKey acm.PrivKey, nonce int64, command btypes.Command) ([]byte, acm.Signature) { noncedCommand := btypes.NoncedCommand{ Nonce: nonce, Command: command, diff --git a/cmd/tendermint/gen_tx.go b/cmd/tendermint/gen_tx.go index d499fad8..4a04e272 100644 --- a/cmd/tendermint/gen_tx.go +++ b/cmd/tendermint/gen_tx.go @@ -32,13 +32,17 @@ func getByteSliceFromHex(prompt string) []byte { return bytes } -func getUint64(prompt string) uint64 { +func getInt(prompt string) int { input := getString(prompt) i, err := strconv.Atoi(input) if err != nil { - Exit(Fmt("Not a valid uint64 amount: %v\nError: %v\n", input, err)) + Exit(Fmt("Not a valid int64 amount: %v\nError: %v\n", input, err)) } - return uint64(i) + return i +} + +func getInt64(prompt string) int64 { + return int64(getInt(prompt)) } func gen_tx() { @@ -68,16 +72,16 @@ func gen_tx() { } // Get the amount to send from src account - srcSendAmount := getUint64(Fmt("Enter amount to send from %X (total: %v): ", srcAccountAddress, srcAccountBalanceStr)) + srcSendAmount := getInt64(Fmt("Enter amount to send from %X (total: %v): ", srcAccountAddress, srcAccountBalanceStr)) // Get the next sequence of src account - srcSendSequence := uint(getUint64(Fmt("Enter next sequence for %X (guess: %v): ", srcAccountAddress, srcAccountSequenceStr))) + srcSendSequence := getInt(Fmt("Enter next sequence for %X (guess: %v): ", srcAccountAddress, srcAccountSequenceStr)) // Get dest address dstAddress := getByteSliceFromHex("Enter destination address: ") // Get the amount to send to dst account - dstSendAmount := getUint64(Fmt("Enter amount to send to %X: ", dstAddress)) + dstSendAmount := getInt64(Fmt("Enter amount to send to %X: ", dstAddress)) // Construct SendTx tx := &types.SendTx{ diff --git a/common/bit_array.go b/common/bit_array.go index 034beb0f..d478d02e 100644 --- a/common/bit_array.go +++ b/common/bit_array.go @@ -9,12 +9,12 @@ import ( type BitArray struct { mtx sync.Mutex - Bits uint `json:"bits"` // NOTE: persisted via reflect, must be exported + Bits int `json:"bits"` // NOTE: persisted via reflect, must be exported Elems []uint64 `json:"elems"` // NOTE: persisted via reflect, must be exported } // There is no BitArray whose Size is 0. Use nil instead. -func NewBitArray(bits uint) *BitArray { +func NewBitArray(bits int) *BitArray { if bits == 0 { return nil } @@ -24,7 +24,7 @@ func NewBitArray(bits uint) *BitArray { } } -func (bA *BitArray) Size() uint { +func (bA *BitArray) Size() int { if bA == nil { return 0 } @@ -32,7 +32,7 @@ func (bA *BitArray) Size() uint { } // NOTE: behavior is undefined if i >= bA.Bits -func (bA *BitArray) GetIndex(i uint) bool { +func (bA *BitArray) GetIndex(i int) bool { if bA == nil { return false } @@ -41,15 +41,15 @@ func (bA *BitArray) GetIndex(i uint) bool { return bA.getIndex(i) } -func (bA *BitArray) getIndex(i uint) bool { +func (bA *BitArray) getIndex(i int) bool { if i >= bA.Bits { return false } - return bA.Elems[i/64]&(uint64(1)<<(i%64)) > 0 + return bA.Elems[i/64]&(uint64(1)< 0 } // NOTE: behavior is undefined if i >= bA.Bits -func (bA *BitArray) SetIndex(i uint, v bool) bool { +func (bA *BitArray) SetIndex(i int, v bool) bool { if bA == nil { return false } @@ -58,14 +58,14 @@ func (bA *BitArray) SetIndex(i uint, v bool) bool { return bA.setIndex(i, v) } -func (bA *BitArray) setIndex(i uint, v bool) bool { +func (bA *BitArray) setIndex(i int, v bool) bool { if i >= bA.Bits { return false } if v { - bA.Elems[i/64] |= (uint64(1) << (i % 64)) + bA.Elems[i/64] |= (uint64(1) << uint(i%64)) } else { - bA.Elems[i/64] &= ^(uint64(1) << (i % 64)) + bA.Elems[i/64] &= ^(uint64(1) << uint(i%64)) } return true } @@ -88,7 +88,7 @@ func (bA *BitArray) copy() *BitArray { } } -func (bA *BitArray) copyBits(bits uint) *BitArray { +func (bA *BitArray) copyBits(bits int) *BitArray { c := make([]uint64, (bits+63)/64) copy(c, bA.Elems) return &BitArray{ @@ -104,7 +104,7 @@ func (bA *BitArray) Or(o *BitArray) *BitArray { } bA.mtx.Lock() defer bA.mtx.Unlock() - c := bA.copyBits(MaxUint(bA.Bits, o.Bits)) + c := bA.copyBits(MaxInt(bA.Bits, o.Bits)) for i := 0; i < len(c.Elems); i++ { c.Elems[i] |= o.Elems[i] } @@ -122,7 +122,7 @@ func (bA *BitArray) And(o *BitArray) *BitArray { } func (bA *BitArray) and(o *BitArray) *BitArray { - c := bA.copyBits(MinUint(bA.Bits, o.Bits)) + c := bA.copyBits(MinInt(bA.Bits, o.Bits)) for i := 0; i < len(c.Elems); i++ { c.Elems[i] &= o.Elems[i] } @@ -153,7 +153,7 @@ func (bA *BitArray) Sub(o *BitArray) *BitArray { for i := 0; i < len(o.Elems)-1; i++ { c.Elems[i] &= ^c.Elems[i] } - i := uint(len(o.Elems) - 1) + i := len(o.Elems) - 1 if i >= 0 { for idx := i * 64; idx < o.Bits; idx++ { c.setIndex(idx, c.getIndex(idx) && !o.GetIndex(idx)) @@ -182,10 +182,10 @@ func (bA *BitArray) IsFull() bool { // Check that the last element has (lastElemBits) 1's lastElemBits := (bA.Bits+63)%64 + 1 lastElem := bA.Elems[len(bA.Elems)-1] - return (lastElem+1)&((uint64(1)< 0 { - return 64*uint(elemIdx) + uint(bitIdx), true + return 64*elemIdx + bitIdx, true } } panic("should not happen") } } else { // Special case for last elem, to ignore straggler bits - elemBits := int(bA.Bits) % 64 + elemBits := bA.Bits % 64 if elemBits == 0 { elemBits = 64 } @@ -220,7 +220,7 @@ func (bA *BitArray) PickRandom() (uint, bool) { for j := 0; j < elemBits; j++ { bitIdx := ((j + randBitStart) % elemBits) if (bA.Elems[elemIdx] & (uint64(1) << uint(bitIdx))) > 0 { - return 64*uint(elemIdx) + uint(bitIdx), true + return 64*elemIdx + bitIdx, true } } } @@ -250,7 +250,7 @@ func (bA *BitArray) stringIndented(indent string) string { lines := []string{} bits := "" - for i := uint(0); i < bA.Bits; i++ { + for i := 0; i < bA.Bits; i++ { if bA.getIndex(i) { bits += "X" } else { diff --git a/common/bit_array_test.go b/common/bit_array_test.go index a0a1f397..93274aab 100644 --- a/common/bit_array_test.go +++ b/common/bit_array_test.go @@ -4,15 +4,15 @@ import ( "testing" ) -func randBitArray(bits uint) (*BitArray, []byte) { - src := RandBytes(int((bits + 7) / 8)) +func randBitArray(bits int) (*BitArray, []byte) { + src := RandBytes((bits + 7) / 8) bA := NewBitArray(bits) - for i := uint(0); i < uint(len(src)); i++ { - for j := uint(0); j < 8; j++ { + for i := 0; i < len(src); i++ { + for j := 0; j < 8; j++ { if i*8+j >= bits { return bA, src } - setBit := src[i]&(1< 0 + setBit := src[i]&(1< 0 bA.SetIndex(i*8+j, setBit) } } @@ -31,7 +31,7 @@ func TestAnd(t *testing.T) { if len(bA3.Elems) != len(bA2.Elems) { t.Error("Expected min elems length") } - for i := uint(0); i < bA3.Bits; i++ { + for i := 0; i < bA3.Bits; i++ { expected := bA1.GetIndex(i) && bA2.GetIndex(i) if bA3.GetIndex(i) != expected { t.Error("Wrong bit from bA3", i, bA1.GetIndex(i), bA2.GetIndex(i), bA3.GetIndex(i)) @@ -51,7 +51,7 @@ func TestOr(t *testing.T) { if len(bA3.Elems) != len(bA1.Elems) { t.Error("Expected max elems length") } - for i := uint(0); i < bA3.Bits; i++ { + for i := 0; i < bA3.Bits; i++ { expected := bA1.GetIndex(i) || bA2.GetIndex(i) if bA3.GetIndex(i) != expected { t.Error("Wrong bit from bA3", i, bA1.GetIndex(i), bA2.GetIndex(i), bA3.GetIndex(i)) @@ -71,7 +71,7 @@ func TestSub1(t *testing.T) { if len(bA3.Elems) != len(bA1.Elems) { t.Error("Expected bA1 elems length") } - for i := uint(0); i < bA3.Bits; i++ { + for i := 0; i < bA3.Bits; i++ { expected := bA1.GetIndex(i) if bA2.GetIndex(i) { expected = false @@ -94,7 +94,7 @@ func TestSub2(t *testing.T) { if len(bA3.Elems) != len(bA1.Elems) { t.Error("Expected bA1 elems length") } - for i := uint(0); i < bA3.Bits; i++ { + for i := 0; i < bA3.Bits; i++ { expected := bA1.GetIndex(i) if i < bA2.Bits && bA2.GetIndex(i) { expected = false @@ -108,12 +108,12 @@ func TestSub2(t *testing.T) { func TestPickRandom(t *testing.T) { for idx := 0; idx < 123; idx++ { bA1 := NewBitArray(123) - bA1.SetIndex(uint(idx), true) + bA1.SetIndex(idx, true) index, ok := bA1.PickRandom() if !ok { t.Fatal("Expected to pick element but got none") } - if index != uint(idx) { + if index != idx { t.Fatalf("Expected to pick element at %v but got wrong index", idx) } } diff --git a/common/int.go b/common/int.go index c6e85dc6..50e86a07 100644 --- a/common/int.go +++ b/common/int.go @@ -37,3 +37,19 @@ func PutUint64BE(dest []byte, i uint64) { func GetUint64BE(src []byte) uint64 { return binary.BigEndian.Uint64(src) } + +func PutInt64LE(dest []byte, i int64) { + binary.LittleEndian.PutUint64(dest, uint64(i)) +} + +func GetInt64LE(src []byte) int64 { + return int64(binary.LittleEndian.Uint64(src)) +} + +func PutInt64BE(dest []byte, i int64) { + binary.BigEndian.PutUint64(dest, uint64(i)) +} + +func GetInt64BE(src []byte) int64 { + return int64(binary.BigEndian.Uint64(src)) +} diff --git a/common/random.go b/common/random.go index 62a50922..e1d6046d 100644 --- a/common/random.go +++ b/common/random.go @@ -62,6 +62,18 @@ func RandUint() uint { return uint(rand.Int()) } +func RandInt16() int16 { + return int16(rand.Uint32() & (1<<16 - 1)) +} + +func RandInt32() int32 { + return int32(rand.Uint32()) +} + +func RandInt64() int64 { + return int64(rand.Uint32())<<32 + int64(rand.Uint32()) +} + func RandInt() int { return rand.Int() } diff --git a/common/word.go b/common/word.go index 264a7dcc..893b136e 100644 --- a/common/word.go +++ b/common/word.go @@ -28,9 +28,9 @@ func (w Word256) Compare(other Word256) int { return bytes.Compare(w[:], other[:]) } -func Uint64ToWord256(i uint64) Word256 { +func Int64ToWord256(i int64) Word256 { buf := [8]byte{} - PutUint64BE(buf[:], i) + PutInt64BE(buf[:], i) return LeftPadWord256(buf[:]) } @@ -44,9 +44,9 @@ func LeftPadWord256(bz []byte) (word Word256) { return } -func Uint64FromWord256(word Word256) uint64 { +func Int64FromWord256(word Word256) int64 { buf := word.Postfix(8) - return GetUint64BE(buf) + return GetInt64BE(buf) } //------------------------------------- diff --git a/consensus/height_vote_set.go b/consensus/height_vote_set.go index 1377c67d..0dce526d 100644 --- a/consensus/height_vote_set.go +++ b/consensus/height_vote_set.go @@ -27,39 +27,39 @@ we create a new entry in roundVoteSets but also remember the peer to prevent abuse. */ type HeightVoteSet struct { - height uint + height int valSet *sm.ValidatorSet mtx sync.Mutex - round uint // max tracked round - roundVoteSets map[uint]RoundVoteSet // keys: [0...round] - peerCatchupRounds map[string]uint // keys: peer.Key; values: round + round int // max tracked round + roundVoteSets map[int]RoundVoteSet // keys: [0...round] + peerCatchupRounds map[string]int // keys: peer.Key; values: round } -func NewHeightVoteSet(height uint, valSet *sm.ValidatorSet) *HeightVoteSet { +func NewHeightVoteSet(height int, valSet *sm.ValidatorSet) *HeightVoteSet { hvs := &HeightVoteSet{ height: height, valSet: valSet, - roundVoteSets: make(map[uint]RoundVoteSet), - peerCatchupRounds: make(map[string]uint), + roundVoteSets: make(map[int]RoundVoteSet), + peerCatchupRounds: make(map[string]int), } hvs.addRound(0) hvs.round = 0 return hvs } -func (hvs *HeightVoteSet) Height() uint { +func (hvs *HeightVoteSet) Height() int { return hvs.height } -func (hvs *HeightVoteSet) Round() uint { +func (hvs *HeightVoteSet) Round() int { hvs.mtx.Lock() defer hvs.mtx.Unlock() return hvs.round } // Create more RoundVoteSets up to round. -func (hvs *HeightVoteSet) SetRound(round uint) { +func (hvs *HeightVoteSet) SetRound(round int) { hvs.mtx.Lock() defer hvs.mtx.Unlock() if hvs.round != 0 && (round < hvs.round+1) { @@ -74,7 +74,7 @@ func (hvs *HeightVoteSet) SetRound(round uint) { hvs.round = round } -func (hvs *HeightVoteSet) addRound(round uint) { +func (hvs *HeightVoteSet) addRound(round int) { if _, ok := hvs.roundVoteSets[round]; ok { panic("addRound() for an existing round") } @@ -88,7 +88,7 @@ func (hvs *HeightVoteSet) addRound(round uint) { // Duplicate votes return added=false, err=nil. // By convention, peerKey is "" if origin is self. -func (hvs *HeightVoteSet) AddByAddress(address []byte, vote *types.Vote, peerKey string) (added bool, index uint, err error) { +func (hvs *HeightVoteSet) AddByAddress(address []byte, vote *types.Vote, peerKey string) (added bool, index int, err error) { hvs.mtx.Lock() defer hvs.mtx.Unlock() voteSet := hvs.getVoteSet(vote.Round, vote.Type) @@ -108,13 +108,13 @@ func (hvs *HeightVoteSet) AddByAddress(address []byte, vote *types.Vote, peerKey return } -func (hvs *HeightVoteSet) Prevotes(round uint) *VoteSet { +func (hvs *HeightVoteSet) Prevotes(round int) *VoteSet { hvs.mtx.Lock() defer hvs.mtx.Unlock() return hvs.getVoteSet(round, types.VoteTypePrevote) } -func (hvs *HeightVoteSet) Precommits(round uint) *VoteSet { +func (hvs *HeightVoteSet) Precommits(round int) *VoteSet { hvs.mtx.Lock() defer hvs.mtx.Unlock() return hvs.getVoteSet(round, types.VoteTypePrecommit) @@ -125,15 +125,15 @@ func (hvs *HeightVoteSet) Precommits(round uint) *VoteSet { func (hvs *HeightVoteSet) POLRound() int { hvs.mtx.Lock() defer hvs.mtx.Unlock() - for r := int(hvs.round); r >= 0; r-- { - if hvs.getVoteSet(uint(r), types.VoteTypePrevote).HasTwoThirdsMajority() { - return int(r) + for r := hvs.round; r >= 0; r-- { + if hvs.getVoteSet(r, types.VoteTypePrevote).HasTwoThirdsMajority() { + return r } } return -1 } -func (hvs *HeightVoteSet) getVoteSet(round uint, type_ byte) *VoteSet { +func (hvs *HeightVoteSet) getVoteSet(round int, type_ byte) *VoteSet { rvs, ok := hvs.roundVoteSets[round] if !ok { return nil @@ -155,7 +155,7 @@ func (hvs *HeightVoteSet) String() string { func (hvs *HeightVoteSet) StringIndented(indent string) string { vsStrings := make([]string, 0, (len(hvs.roundVoteSets)+1)*2) // rounds 0 ~ hvs.round inclusive - for round := uint(0); round <= hvs.round; round++ { + for round := 0; round <= hvs.round; round++ { voteSetString := hvs.roundVoteSets[round].Prevotes.StringShort() vsStrings = append(vsStrings, voteSetString) voteSetString = hvs.roundVoteSets[round].Precommits.StringShort() diff --git a/consensus/reactor.go b/consensus/reactor.go index 22c4182c..56a873d3 100644 --- a/consensus/reactor.go +++ b/consensus/reactor.go @@ -227,7 +227,7 @@ func (conR *ConsensusReactor) Receive(chId byte, peer *p2p.Peer, msgBytes []byte } // Broadcasts HasVoteMessage to peers that care. -func (conR *ConsensusReactor) broadcastHasVoteMessage(vote *types.Vote, index uint) { +func (conR *ConsensusReactor) broadcastHasVoteMessage(vote *types.Vote, index int) { msg := &HasVoteMessage{ Height: vote.Height, Round: vote.Round, @@ -278,7 +278,7 @@ func makeRoundStepMessages(rs *RoundState) (nrsMsg *NewRoundStepMessage, csMsg * Height: rs.Height, Round: rs.Round, Step: rs.Step, - SecondsSinceStartTime: uint(time.Now().Sub(rs.StartTime).Seconds()), + SecondsSinceStartTime: int(time.Now().Sub(rs.StartTime).Seconds()), LastCommitRound: rs.LastCommit.Round(), } if rs.Step == RoundStepCommit { @@ -415,8 +415,8 @@ OUTER_LOOP: if 0 <= rs.Proposal.POLRound { msg := &ProposalPOLMessage{ Height: rs.Height, - ProposalPOLRound: uint(rs.Proposal.POLRound), - ProposalPOL: rs.Votes.Prevotes(uint(rs.Proposal.POLRound)).BitArray(), + ProposalPOLRound: rs.Proposal.POLRound, + ProposalPOL: rs.Votes.Prevotes(rs.Proposal.POLRound).BitArray(), } peer.Send(DataChannel, msg) } @@ -482,7 +482,7 @@ OUTER_LOOP: if validation == nil { return false } else if *prsVoteSet == nil { - ps.EnsureVoteBitArrays(validation.Height(), uint(len(validation.Precommits)), prs) + ps.EnsureVoteBitArrays(validation.Height(), len(validation.Precommits), prs) // We could return true here (useful work was done) // or, we can continue since prsVoteSet is no longer nil. if *prsVoteSet == nil { @@ -522,7 +522,7 @@ OUTER_LOOP: } // If there are POLPrevotes to send... if 0 <= prs.ProposalPOLRound { - if polPrevotes := rs.Votes.Prevotes(uint(prs.ProposalPOLRound)); polPrevotes != nil { + if polPrevotes := rs.Votes.Prevotes(prs.ProposalPOLRound); polPrevotes != nil { if trySendVote(polPrevotes, &prs.ProposalPOL) { continue OUTER_LOOP } @@ -580,8 +580,8 @@ OUTER_LOOP: // Read only when returned by PeerState.GetRoundState(). type PeerRoundState struct { - Height uint // Height peer is at - Round uint // Round peer is at + Height int // Height peer is at + Round int // Round peer is at Step RoundStepType // Step peer is at StartTime time.Time // Estimated start of round 0 at this height Proposal bool // True if peer has proposal for this round @@ -591,7 +591,7 @@ type PeerRoundState struct { ProposalPOL *BitArray // nil until ProposalPOLMessage received. Prevotes *BitArray // All votes peer has for this round Precommits *BitArray // All precommits peer has for this round - LastCommitRound uint // Round of commit for last height. + LastCommitRound int // Round of commit for last height. LastCommit *BitArray // All commit precommits of commit for last height. CatchupCommitRound int // Round that we believe commit round is. CatchupCommit *BitArray // All commit precommits peer has for this height @@ -638,12 +638,12 @@ func (ps *PeerState) SetHasProposal(proposal *Proposal) { ps.Proposal = true ps.ProposalBlockPartsHeader = proposal.BlockPartsHeader - ps.ProposalBlockParts = NewBitArray(uint(proposal.BlockPartsHeader.Total)) + ps.ProposalBlockParts = NewBitArray(proposal.BlockPartsHeader.Total) ps.ProposalPOLRound = proposal.POLRound ps.ProposalPOL = nil // Nil until ProposalPOLMessage received. } -func (ps *PeerState) SetHasProposalBlockPart(height uint, round uint, index uint) { +func (ps *PeerState) SetHasProposalBlockPart(height int, round int, index int) { ps.mtx.Lock() defer ps.mtx.Unlock() @@ -651,13 +651,13 @@ func (ps *PeerState) SetHasProposalBlockPart(height uint, round uint, index uint return } - ps.ProposalBlockParts.SetIndex(uint(index), true) + ps.ProposalBlockParts.SetIndex(index, true) } // prs: If given, will also update this PeerRoundState copy. // NOTE: It's important to make sure that numValidators actually matches // what the node sees as the number of validators for height. -func (ps *PeerState) EnsureVoteBitArrays(height uint, numValidators uint, prs *PeerRoundState) { +func (ps *PeerState) EnsureVoteBitArrays(height int, numValidators int, prs *PeerRoundState) { ps.mtx.Lock() defer ps.mtx.Unlock() @@ -690,14 +690,14 @@ func (ps *PeerState) EnsureVoteBitArrays(height uint, numValidators uint, prs *P } } -func (ps *PeerState) SetHasVote(vote *types.Vote, index uint) { +func (ps *PeerState) SetHasVote(vote *types.Vote, index int) { ps.mtx.Lock() defer ps.mtx.Unlock() ps.setHasVote(vote.Height, vote.Round, vote.Type, index) } -func (ps *PeerState) setHasVote(height uint, round uint, type_ byte, index uint) { +func (ps *PeerState) setHasVote(height int, round int, type_ byte, index int) { if ps.Height == height+1 && ps.LastCommitRound == round && type_ == types.VoteTypePrecommit { // Special case for LastCommit. ps.LastCommit.SetIndex(index, true) @@ -711,13 +711,13 @@ func (ps *PeerState) setHasVote(height uint, round uint, type_ byte, index uint) // By here, ps.Height is height. switch type_ { case types.VoteTypePrevote: - if ps.ProposalPOLRound == int(round) { + if ps.ProposalPOLRound == round { ps.ProposalPOL.SetIndex(index, true) } ps.Prevotes.SetIndex(index, true) log.Debug("SetHasVote", "peer", ps.Key, "prevotes", ps.Prevotes, "index", index) case types.VoteTypePrecommit: - if ps.CatchupCommitRound == int(round) { + if ps.CatchupCommitRound == round { ps.CatchupCommit.SetIndex(index, true) } ps.Precommits.SetIndex(index, true) @@ -728,20 +728,20 @@ func (ps *PeerState) setHasVote(height uint, round uint, type_ byte, index uint) } // NOTE: 'round' is what we know to be the commit round for height. -func (ps *PeerState) EnsureCatchupCommitRound(height, round uint) { +func (ps *PeerState) EnsureCatchupCommitRound(height, round int) { ps.mtx.Lock() defer ps.mtx.Unlock() if ps.Height != height { return } - if ps.CatchupCommitRound != -1 && ps.CatchupCommitRound != int(round) { + if ps.CatchupCommitRound != -1 && ps.CatchupCommitRound != round { panic(Fmt("Conflicting CatchupCommitRound. Height: %v, Orig: %v, New: %v", height, ps.CatchupCommitRound, round)) } - if ps.CatchupCommitRound == int(round) { + if ps.CatchupCommitRound == round { return // Nothing to do! } - ps.CatchupCommitRound = int(round) + ps.CatchupCommitRound = round ps.CatchupCommit = nil } @@ -771,7 +771,7 @@ func (ps *PeerState) ApplyNewRoundStepMessage(msg *NewRoundStepMessage, rs *Roun ps.Prevotes = nil ps.Precommits = nil } - if psHeight == msg.Height && psRound != msg.Round && int(msg.Round) == psCatchupCommitRound { + if psHeight == msg.Height && psRound != msg.Round && msg.Round == psCatchupCommitRound { // Peer caught up to CatchupCommitRound. // Preserve psCatchupCommit! // NOTE: We prefer to use prs.Precommits if @@ -823,7 +823,7 @@ func (ps *PeerState) ApplyProposalPOLMessage(msg *ProposalPOLMessage) { if ps.Height != msg.Height { return } - if ps.ProposalPOLRound != int(msg.ProposalPOLRound) { + if ps.ProposalPOLRound != msg.ProposalPOLRound { return } @@ -871,11 +871,11 @@ func DecodeMessage(bz []byte) (msgType byte, msg ConsensusMessage, err error) { // For every height/round/step transition type NewRoundStepMessage struct { - Height uint - Round uint + Height int + Round int Step RoundStepType - SecondsSinceStartTime uint - LastCommitRound uint + SecondsSinceStartTime int + LastCommitRound int } func (m *NewRoundStepMessage) String() string { @@ -886,7 +886,7 @@ func (m *NewRoundStepMessage) String() string { //------------------------------------- type CommitStepMessage struct { - Height uint + Height int BlockPartsHeader types.PartSetHeader BlockParts *BitArray } @@ -908,8 +908,8 @@ func (m *ProposalMessage) String() string { //------------------------------------- type ProposalPOLMessage struct { - Height uint - ProposalPOLRound uint + Height int + ProposalPOLRound int ProposalPOL *BitArray } @@ -920,8 +920,8 @@ func (m *ProposalPOLMessage) String() string { //------------------------------------- type BlockPartMessage struct { - Height uint - Round uint + Height int + Round int Part *types.Part } @@ -932,7 +932,7 @@ func (m *BlockPartMessage) String() string { //------------------------------------- type VoteMessage struct { - ValidatorIndex uint + ValidatorIndex int Vote *types.Vote } @@ -943,10 +943,10 @@ func (m *VoteMessage) String() string { //------------------------------------- type HasVoteMessage struct { - Height uint - Round uint + Height int + Round int Type byte - Index uint + Index int } func (m *HasVoteMessage) String() string { diff --git a/consensus/state.go b/consensus/state.go index 1811c117..b74e9a0d 100644 --- a/consensus/state.go +++ b/consensus/state.go @@ -201,8 +201,8 @@ func (rs RoundStepType) String() string { // Immutable when returned from ConsensusState.GetRoundState() type RoundState struct { - Height uint // Height we are working on - Round uint + Height int // Height we are working on + Round int Step RoundStepType StartTime time.Time CommitTime time.Time // Subjective time when +2/3 precommits for Block at Round were found @@ -210,7 +210,7 @@ type RoundState struct { Proposal *Proposal ProposalBlock *types.Block ProposalBlockParts *types.PartSet - LockedRound uint + LockedRound int LockedBlock *types.Block LockedBlockParts *types.PartSet Votes *HeightVoteSet @@ -299,7 +299,7 @@ func (cs *ConsensusState) reconstructLastCommit(state *sm.State) { lastPrecommits := NewVoteSet(state.LastBlockHeight, 0, types.VoteTypePrecommit, state.LastBondedValidators) seenValidation := cs.blockStore.LoadSeenValidation(state.LastBlockHeight) for idx, precommit := range seenValidation.Precommits { - added, _, err := lastPrecommits.AddByIndex(uint(idx), precommit) + added, _, err := lastPrecommits.AddByIndex(idx, precommit) if !added || err != nil { panic(Fmt("Failed to reconstruct LastCommit: %v", err)) } @@ -339,7 +339,7 @@ func (cs *ConsensusState) Start() { } // EnterNewRound(height, 0) at cs.StartTime. -func (cs *ConsensusState) scheduleRound0(height uint) { +func (cs *ConsensusState) scheduleRound0(height int) { //log.Debug("scheduleRound0", "now", time.Now(), "startTime", cs.StartTime) sleepDuration := cs.StartTime.Sub(time.Now()) go func() { @@ -451,7 +451,7 @@ func (cs *ConsensusState) SetPrivValidator(priv *sm.PrivValidator) { // Enter: `timeoutPrecommits` after any +2/3 precommits from (height,round-1) // Enter: `startTime = commitTime+timeoutCommit` from NewHeight(height) // NOTE: cs.StartTime was already set for height. -func (cs *ConsensusState) EnterNewRound(height uint, round uint) { +func (cs *ConsensusState) EnterNewRound(height int, round int) { cs.mtx.Lock() defer cs.mtx.Unlock() if cs.Height != height || round < cs.Round || (cs.Round == round && cs.Step != RoundStepNewHeight) { @@ -483,7 +483,7 @@ func (cs *ConsensusState) EnterNewRound(height uint, round uint) { } // Enter: from NewRound(height,round). -func (cs *ConsensusState) EnterPropose(height uint, round uint) { +func (cs *ConsensusState) EnterPropose(height int, round int) { cs.mtx.Lock() defer cs.mtx.Unlock() if cs.Height != height || round < cs.Round || (cs.Round == round && RoundStepPropose <= cs.Step) { @@ -523,7 +523,7 @@ func (cs *ConsensusState) EnterPropose(height uint, round uint) { } // Decides on the next proposal and sets them onto cs.Proposal* -func (cs *ConsensusState) decideProposal(height uint, round uint) { +func (cs *ConsensusState) decideProposal(height int, round int) { var block *types.Block var blockParts *types.PartSet @@ -561,7 +561,7 @@ func (cs *ConsensusState) isProposalComplete() bool { if cs.Proposal.POLRound < 0 { return true } else { - return cs.Votes.Prevotes(uint(cs.Proposal.POLRound)).HasTwoThirdsMajority() + return cs.Votes.Prevotes(cs.Proposal.POLRound).HasTwoThirdsMajority() } } @@ -588,7 +588,7 @@ func (cs *ConsensusState) createProposalBlock() (block *types.Block, blockParts Height: cs.Height, Time: time.Now(), Fees: 0, // TODO fees - NumTxs: uint(len(txs)), + NumTxs: len(txs), LastBlockHash: cs.state.LastBlockHash, LastBlockParts: cs.state.LastBlockParts, StateHash: nil, // Will set afterwards. @@ -615,7 +615,7 @@ func (cs *ConsensusState) createProposalBlock() (block *types.Block, blockParts // Enter: any +2/3 prevotes for future round. // Prevote for LockedBlock if we're locked, or ProposalBlock if valid. // Otherwise vote nil. -func (cs *ConsensusState) EnterPrevote(height uint, round uint) { +func (cs *ConsensusState) EnterPrevote(height int, round int) { cs.mtx.Lock() defer cs.mtx.Unlock() if cs.Height != height || round < cs.Round || (cs.Round == round && RoundStepPrevote <= cs.Step) { @@ -636,7 +636,7 @@ func (cs *ConsensusState) EnterPrevote(height uint, round uint) { }*/ } -func (cs *ConsensusState) doPrevote(height uint, round uint) { +func (cs *ConsensusState) doPrevote(height int, round int) { // If a block is locked, prevote that. if cs.LockedBlock != nil { log.Debug("EnterPrevote: Block was locked") @@ -666,7 +666,7 @@ func (cs *ConsensusState) doPrevote(height uint, round uint) { } // Enter: any +2/3 prevotes at next round. -func (cs *ConsensusState) EnterPrevoteWait(height uint, round uint) { +func (cs *ConsensusState) EnterPrevoteWait(height int, round int) { cs.mtx.Lock() defer cs.mtx.Unlock() if cs.Height != height || round < cs.Round || (cs.Round == round && RoundStepPrevoteWait <= cs.Step) { @@ -695,7 +695,7 @@ func (cs *ConsensusState) EnterPrevoteWait(height uint, round uint) { // Lock & precommit the ProposalBlock if we have enough prevotes for it, // else, unlock an existing lock and precommit nil if +2/3 of prevotes were nil, // else, precommit locked block or nil otherwise. -func (cs *ConsensusState) EnterPrecommit(height uint, round uint) { +func (cs *ConsensusState) EnterPrecommit(height int, round int) { cs.mtx.Lock() defer cs.mtx.Unlock() if cs.Height != height || round < cs.Round || (cs.Round == round && RoundStepPrecommit <= cs.Step) { @@ -768,7 +768,7 @@ func (cs *ConsensusState) EnterPrecommit(height uint, round uint) { // Otherwise, we need to fetch the +2/3 prevoted block. // Unlock and precommit nil. // The +2/3 prevotes for this round is the POL for our unlock. - if cs.Votes.POLRound() < int(round) { + if cs.Votes.POLRound() < round { panic(Fmt("This POLRound shold be %v but got %", round, cs.Votes.POLRound())) } cs.LockedRound = 0 @@ -783,7 +783,7 @@ func (cs *ConsensusState) EnterPrecommit(height uint, round uint) { } // Enter: any +2/3 precommits for next round. -func (cs *ConsensusState) EnterPrecommitWait(height uint, round uint) { +func (cs *ConsensusState) EnterPrecommitWait(height int, round int) { cs.mtx.Lock() defer cs.mtx.Unlock() if cs.Height != height || round < cs.Round || (cs.Round == round && RoundStepPrecommitWait <= cs.Step) { @@ -811,7 +811,7 @@ func (cs *ConsensusState) EnterPrecommitWait(height uint, round uint) { } // Enter: +2/3 precommits for block -func (cs *ConsensusState) EnterCommit(height uint) { +func (cs *ConsensusState) EnterCommit(height int) { cs.mtx.Lock() defer cs.mtx.Unlock() if cs.Height != height || RoundStepCommit <= cs.Step { @@ -865,7 +865,7 @@ func (cs *ConsensusState) EnterCommit(height uint) { } // If we have the block AND +2/3 commits for it, finalize. -func (cs *ConsensusState) tryFinalizeCommit(height uint) { +func (cs *ConsensusState) tryFinalizeCommit(height int) { // SANITY CHECK if cs.Height != height { panic(Fmt("tryFinalizeCommit() cs.Height: %v vs height: %v", cs.Height, height)) @@ -883,7 +883,7 @@ func (cs *ConsensusState) tryFinalizeCommit(height uint) { } // Increment height and goto RoundStepNewHeight -func (cs *ConsensusState) FinalizeCommit(height uint) { +func (cs *ConsensusState) FinalizeCommit(height int) { cs.mtx.Lock() defer cs.mtx.Unlock() @@ -950,7 +950,7 @@ func (cs *ConsensusState) SetProposal(proposal *Proposal) error { // Verify POLRound, which must be -1 or between 0 and proposal.Round exclusive. if proposal.POLRound != -1 && - (proposal.POLRound < 0 || proposal.Round <= uint(proposal.POLRound)) { + (proposal.POLRound < 0 || proposal.Round <= proposal.POLRound) { return ErrInvalidProposalPOLRound } @@ -965,7 +965,7 @@ func (cs *ConsensusState) SetProposal(proposal *Proposal) error { } // NOTE: block is not necessarily valid. -func (cs *ConsensusState) AddProposalBlockPart(height uint, part *types.Part) (added bool, err error) { +func (cs *ConsensusState) AddProposalBlockPart(height int, part *types.Part) (added bool, err error) { cs.mtx.Lock() defer cs.mtx.Unlock() @@ -1001,7 +1001,7 @@ func (cs *ConsensusState) AddProposalBlockPart(height uint, part *types.Part) (a return added, nil } -func (cs *ConsensusState) AddVote(address []byte, vote *types.Vote, peerKey string) (added bool, index uint, err error) { +func (cs *ConsensusState) AddVote(address []byte, vote *types.Vote, peerKey string) (added bool, index int, err error) { cs.mtx.Lock() defer cs.mtx.Unlock() @@ -1010,7 +1010,7 @@ func (cs *ConsensusState) AddVote(address []byte, vote *types.Vote, peerKey stri //----------------------------------------------------------------------------- -func (cs *ConsensusState) addVote(address []byte, vote *types.Vote, peerKey string) (added bool, index uint, err error) { +func (cs *ConsensusState) addVote(address []byte, vote *types.Vote, peerKey string) (added bool, index int, err error) { // A precommit for the previous height? if vote.Height+1 == cs.Height && vote.Type == types.VoteTypePrecommit { added, index, err = cs.LastCommit.AddByAddress(address, vote) @@ -1056,8 +1056,7 @@ func (cs *ConsensusState) addVote(address []byte, vote *types.Vote, peerKey stri cs.EnterPrevoteWait(height, vote.Round) } }() - } else if cs.Proposal != nil && - 0 <= cs.Proposal.POLRound && uint(cs.Proposal.POLRound) == vote.Round { + } else if cs.Proposal != nil && 0 <= cs.Proposal.POLRound && cs.Proposal.POLRound == vote.Round { // If the proposal is now complete, enter prevote of cs.Round. if cs.isProposalComplete() { go cs.EnterPrevote(height, cs.Round) diff --git a/consensus/test.go b/consensus/test.go index 397befa0..c105f156 100644 --- a/consensus/test.go +++ b/consensus/test.go @@ -18,7 +18,7 @@ func randConsensusState() (*ConsensusState, []*sm.PrivValidator) { return cs, privValidators } -func randVoteSet(height uint, round uint, type_ byte, numValidators int, votingPower uint64) (*VoteSet, *sm.ValidatorSet, []*sm.PrivValidator) { +func randVoteSet(height int, round int, type_ byte, numValidators int, votingPower int64) (*VoteSet, *sm.ValidatorSet, []*sm.PrivValidator) { vals := make([]*sm.Validator, numValidators) privValidators := make([]*sm.PrivValidator, numValidators) for i := 0; i < numValidators; i++ { diff --git a/consensus/types/proposal.go b/consensus/types/proposal.go index a3a9f546..1c7d0d70 100644 --- a/consensus/types/proposal.go +++ b/consensus/types/proposal.go @@ -17,14 +17,14 @@ var ( ) type Proposal struct { - Height uint `json:"height"` - Round uint `json:"round"` + Height int `json:"height"` + Round int `json:"round"` BlockPartsHeader types.PartSetHeader `json:"block_parts_header"` POLRound int `json:"pol_round"` // -1 if null. Signature account.SignatureEd25519 `json:"signature"` } -func NewProposal(height uint, round uint, blockPartsHeader types.PartSetHeader, polRound int) *Proposal { +func NewProposal(height int, round int, blockPartsHeader types.PartSetHeader, polRound int) *Proposal { return &Proposal{ Height: height, Round: round, diff --git a/consensus/vote_set.go b/consensus/vote_set.go index 2227cfe9..c5c0ae0c 100644 --- a/consensus/vote_set.go +++ b/consensus/vote_set.go @@ -19,23 +19,23 @@ import ( // A commit of prior rounds can be added added in lieu of votes/precommits. // NOTE: Assumes that the sum total of voting power does not exceed MaxUInt64. type VoteSet struct { - height uint - round uint + height int + round int type_ byte mtx sync.Mutex valSet *sm.ValidatorSet - votes []*types.Vote // validator index -> vote - votesBitArray *BitArray // validator index -> has vote? - votesByBlock map[string]uint64 // string(blockHash)+string(blockParts) -> vote sum. - totalVotes uint64 + votes []*types.Vote // validator index -> vote + votesBitArray *BitArray // validator index -> has vote? + votesByBlock map[string]int64 // string(blockHash)+string(blockParts) -> vote sum. + totalVotes int64 maj23Hash []byte maj23Parts types.PartSetHeader maj23Exists bool } // Constructs a new VoteSet struct used to accumulate votes for given height/round. -func NewVoteSet(height uint, round uint, type_ byte, valSet *sm.ValidatorSet) *VoteSet { +func NewVoteSet(height int, round int, type_ byte, valSet *sm.ValidatorSet) *VoteSet { if height == 0 { panic("Cannot make VoteSet for height == 0, doesn't make sense.") } @@ -46,12 +46,12 @@ func NewVoteSet(height uint, round uint, type_ byte, valSet *sm.ValidatorSet) *V valSet: valSet, votes: make([]*types.Vote, valSet.Size()), votesBitArray: NewBitArray(valSet.Size()), - votesByBlock: make(map[string]uint64), + votesByBlock: make(map[string]int64), totalVotes: 0, } } -func (voteSet *VoteSet) Height() uint { +func (voteSet *VoteSet) Height() int { if voteSet == nil { return 0 } else { @@ -59,7 +59,7 @@ func (voteSet *VoteSet) Height() uint { } } -func (voteSet *VoteSet) Round() uint { +func (voteSet *VoteSet) Round() int { if voteSet == nil { return 0 } else { @@ -67,7 +67,7 @@ func (voteSet *VoteSet) Round() uint { } } -func (voteSet *VoteSet) Size() uint { +func (voteSet *VoteSet) Size() int { if voteSet == nil { return 0 } else { @@ -79,7 +79,7 @@ func (voteSet *VoteSet) Size() uint { // Otherwise returns err=ErrVote[UnexpectedStep|InvalidAccount|InvalidSignature|InvalidBlockHash|ConflictingSignature] // Duplicate votes return added=false, err=nil. // NOTE: vote should not be mutated after adding. -func (voteSet *VoteSet) AddByIndex(valIndex uint, vote *types.Vote) (added bool, index uint, err error) { +func (voteSet *VoteSet) AddByIndex(valIndex int, vote *types.Vote) (added bool, index int, err error) { voteSet.mtx.Lock() defer voteSet.mtx.Unlock() @@ -90,7 +90,7 @@ func (voteSet *VoteSet) AddByIndex(valIndex uint, vote *types.Vote) (added bool, // Otherwise returns err=ErrVote[UnexpectedStep|InvalidAccount|InvalidSignature|InvalidBlockHash|ConflictingSignature] // Duplicate votes return added=false, err=nil. // NOTE: vote should not be mutated after adding. -func (voteSet *VoteSet) AddByAddress(address []byte, vote *types.Vote) (added bool, index uint, err error) { +func (voteSet *VoteSet) AddByAddress(address []byte, vote *types.Vote) (added bool, index int, err error) { voteSet.mtx.Lock() defer voteSet.mtx.Unlock() @@ -103,7 +103,7 @@ func (voteSet *VoteSet) AddByAddress(address []byte, vote *types.Vote) (added bo return voteSet.addVote(val, valIndex, vote) } -func (voteSet *VoteSet) addByIndex(valIndex uint, vote *types.Vote) (bool, uint, error) { +func (voteSet *VoteSet) addByIndex(valIndex int, vote *types.Vote) (bool, int, error) { // Ensure that signer is a validator. _, val := voteSet.valSet.GetByIndex(valIndex) if val == nil { @@ -113,7 +113,7 @@ func (voteSet *VoteSet) addByIndex(valIndex uint, vote *types.Vote) (bool, uint, return voteSet.addVote(val, valIndex, vote) } -func (voteSet *VoteSet) addVote(val *sm.Validator, valIndex uint, vote *types.Vote) (bool, uint, error) { +func (voteSet *VoteSet) addVote(val *sm.Validator, valIndex int, vote *types.Vote) (bool, int, error) { // Make sure the step matches. (or that vote is commit && round < voteSet.round) if (vote.Height != voteSet.height) || @@ -168,7 +168,7 @@ func (voteSet *VoteSet) BitArray() *BitArray { return voteSet.votesBitArray.Copy() } -func (voteSet *VoteSet) GetByIndex(valIndex uint) *types.Vote { +func (voteSet *VoteSet) GetByIndex(valIndex int) *types.Vote { voteSet.mtx.Lock() defer voteSet.mtx.Unlock() return voteSet.votes[valIndex] @@ -264,7 +264,7 @@ func (voteSet *VoteSet) MakeValidation() *types.Validation { panic("Cannot MakeValidation() unless a blockhash has +2/3") } precommits := make([]*types.Vote, voteSet.valSet.Size()) - voteSet.valSet.Iterate(func(valIndex uint, val *sm.Validator) bool { + voteSet.valSet.Iterate(func(valIndex int, val *sm.Validator) bool { vote := voteSet.votes[valIndex] if vote == nil { return false diff --git a/consensus/vote_set_test.go b/consensus/vote_set_test.go index 46bafed6..d6daab19 100644 --- a/consensus/vote_set_test.go +++ b/consensus/vote_set_test.go @@ -15,14 +15,14 @@ import ( // NOTE: see consensus/test.go for common test methods. // Convenience: Return new vote with different height -func withHeight(vote *types.Vote, height uint) *types.Vote { +func withHeight(vote *types.Vote, height int) *types.Vote { vote = vote.Copy() vote.Height = height return vote } // Convenience: Return new vote with different round -func withRound(vote *types.Vote, round uint) *types.Vote { +func withRound(vote *types.Vote, round int) *types.Vote { vote = vote.Copy() vote.Round = round return vote @@ -56,7 +56,7 @@ func signAddVote(privVal *sm.PrivValidator, vote *types.Vote, voteSet *VoteSet) } func TestAddVote(t *testing.T) { - height, round := uint(1), uint(0) + height, round := 1, 0 voteSet, _, privValidators := randVoteSet(height, round, types.VoteTypePrevote, 10, 1) val0 := privValidators[0] @@ -89,7 +89,7 @@ func TestAddVote(t *testing.T) { } func Test2_3Majority(t *testing.T) { - height, round := uint(1), uint(0) + height, round := 1, 0 voteSet, _, privValidators := randVoteSet(height, round, types.VoteTypePrevote, 10, 1) vote := &types.Vote{Height: height, Round: round, Type: types.VoteTypePrevote, BlockHash: nil} @@ -123,11 +123,11 @@ func Test2_3Majority(t *testing.T) { } func Test2_3MajorityRedux(t *testing.T) { - height, round := uint(1), uint(0) + height, round := 1, 0 voteSet, _, privValidators := randVoteSet(height, round, types.VoteTypePrevote, 100, 1) blockHash := CRandBytes(32) - blockPartsTotal := uint(123) + blockPartsTotal := 123 blockParts := types.PartSetHeader{blockPartsTotal, CRandBytes(32)} vote := &types.Vote{Height: height, Round: round, Type: types.VoteTypePrevote, BlockHash: blockHash, BlockParts: blockParts} @@ -190,7 +190,7 @@ func Test2_3MajorityRedux(t *testing.T) { } func TestBadVotes(t *testing.T) { - height, round := uint(1), uint(0) + height, round := 1, 0 voteSet, _, privValidators := randVoteSet(height, round, types.VoteTypePrevote, 10, 1) // val0 votes for nil. @@ -226,7 +226,7 @@ func TestBadVotes(t *testing.T) { } func TestMakeValidation(t *testing.T) { - height, round := uint(1), uint(0) + height, round := 1, 0 voteSet, _, privValidators := randVoteSet(height, round, types.VoteTypePrecommit, 10, 1) blockHash, blockParts := CRandBytes(32), types.PartSetHeader{123, CRandBytes(32)} diff --git a/crawler/crawl.go b/crawler/crawl.go index b337d320..973b27ee 100644 --- a/crawler/crawl.go +++ b/crawler/crawl.go @@ -33,8 +33,8 @@ type Node struct { LastSeen time.Time ChainID string - BlockHeight uint - BlockHistory map[uint]time.Time // when we saw each block + BlockHeight int + BlockHistory map[int]time.Time // when we saw each block NetInfo *rpctypes.ResponseNetInfo Validator bool diff --git a/merkle/iavl_node.go b/merkle/iavl_node.go index 086283a5..6786e9d2 100644 --- a/merkle/iavl_node.go +++ b/merkle/iavl_node.go @@ -13,8 +13,8 @@ import ( type IAVLNode struct { key interface{} value interface{} - height uint8 - size uint + height int8 + size int hash []byte leftHash []byte leftNode *IAVLNode @@ -38,8 +38,8 @@ func ReadIAVLNode(t *IAVLTree, r io.Reader, n *int64, err *error) *IAVLNode { node := &IAVLNode{} // node header - node.height = binary.ReadUint8(r, n, err) - node.size = binary.ReadUvarint(r, n, err) + node.height = binary.ReadInt8(r, n, err) + node.size = binary.ReadVarint(r, n, err) node.key = decodeByteSlice(t.keyCodec, r, n, err) if node.height == 0 { @@ -88,7 +88,7 @@ func (node *IAVLNode) has(t *IAVLTree, key interface{}) (has bool) { } } -func (node *IAVLNode) get(t *IAVLTree, key interface{}) (index uint, value interface{}) { +func (node *IAVLNode) get(t *IAVLTree, key interface{}) (index int, value interface{}) { if node.height == 0 { if t.keyCodec.Compare(node.key, key) == 0 { return 0, node.value @@ -107,7 +107,7 @@ func (node *IAVLNode) get(t *IAVLTree, key interface{}) (index uint, value inter } } -func (node *IAVLNode) getByIndex(t *IAVLTree, index uint) (key interface{}, value interface{}) { +func (node *IAVLNode) getByIndex(t *IAVLTree, index int) (key interface{}, value interface{}) { if node.height == 0 { if index == 0 { return node.key, node.value @@ -127,7 +127,7 @@ func (node *IAVLNode) getByIndex(t *IAVLTree, index uint) (key interface{}, valu } // NOTE: sets hashes recursively -func (node *IAVLNode) hashWithCount(t *IAVLTree) ([]byte, uint) { +func (node *IAVLNode) hashWithCount(t *IAVLTree) ([]byte, int) { if node.hash != nil { return node.hash, 0 } @@ -147,10 +147,10 @@ func (node *IAVLNode) hashWithCount(t *IAVLTree) ([]byte, uint) { } // NOTE: sets hashes recursively -func (node *IAVLNode) writeHashBytes(t *IAVLTree, w io.Writer) (n int64, hashCount uint, err error) { +func (node *IAVLNode) writeHashBytes(t *IAVLTree, w io.Writer) (n int64, hashCount int, err error) { // height & size - binary.WriteUint8(node.height, w, &n, &err) - binary.WriteUvarint(node.size, w, &n, &err) + binary.WriteInt8(node.height, w, &n, &err) + binary.WriteVarint(node.size, w, &n, &err) // key is not written for inner nodes, unlike writePersistBytes if node.height == 0 { @@ -210,8 +210,8 @@ func (node *IAVLNode) save(t *IAVLTree) []byte { // NOTE: sets hashes recursively func (node *IAVLNode) writePersistBytes(t *IAVLTree, w io.Writer) (n int64, err error) { // node header - binary.WriteUint8(node.height, w, &n, &err) - binary.WriteUvarint(node.size, w, &n, &err) + binary.WriteInt8(node.height, w, &n, &err) + binary.WriteVarint(node.size, w, &n, &err) // key (unlike writeHashBytes, key is written for inner nodes) encodeByteSlice(node.key, t.keyCodec, w, &n, &err) @@ -365,7 +365,7 @@ func (node *IAVLNode) rotateLeft(t *IAVLTree) *IAVLNode { // NOTE: mutates height and size func (node *IAVLNode) calcHeightAndSize(t *IAVLTree) { - node.height = maxUint8(node.getLeftNode(t).height, node.getRightNode(t).height) + 1 + node.height = maxInt8(node.getLeftNode(t).height, node.getRightNode(t).height) + 1 node.size = node.getLeftNode(t).size + node.getRightNode(t).size } diff --git a/merkle/iavl_proof.go b/merkle/iavl_proof.go index b3e3b2a0..4d1b11ab 100644 --- a/merkle/iavl_proof.go +++ b/merkle/iavl_proof.go @@ -35,8 +35,8 @@ func (proof *IAVLProof) Verify(keyBytes, valueBytes, rootHash []byte) bool { } type IAVLProofInnerNode struct { - Height uint8 - Size uint + Height int8 + Size int Left []byte Right []byte } @@ -45,8 +45,8 @@ func (branch IAVLProofInnerNode) Hash(childHash []byte) []byte { hasher := sha256.New() buf := new(bytes.Buffer) n, err := int64(0), error(nil) - binary.WriteUint8(branch.Height, buf, &n, &err) - binary.WriteUvarint(branch.Size, buf, &n, &err) + binary.WriteInt8(branch.Height, buf, &n, &err) + binary.WriteVarint(branch.Size, buf, &n, &err) if branch.Left == nil { binary.WriteByteSlice(childHash, buf, &n, &err) binary.WriteByteSlice(branch.Right, buf, &n, &err) @@ -71,8 +71,8 @@ func (leaf IAVLProofLeafNode) Hash() []byte { hasher := sha256.New() buf := new(bytes.Buffer) n, err := int64(0), error(nil) - binary.WriteUint8(0, buf, &n, &err) - binary.WriteUvarint(1, buf, &n, &err) + binary.WriteInt8(0, buf, &n, &err) + binary.WriteVarint(1, buf, &n, &err) binary.WriteByteSlice(leaf.KeyBytes, buf, &n, &err) binary.WriteByteSlice(leaf.ValueBytes, buf, &n, &err) if err != nil { diff --git a/merkle/iavl_test.go b/merkle/iavl_test.go index e92bf4dd..ae374773 100644 --- a/merkle/iavl_test.go +++ b/merkle/iavl_test.go @@ -60,7 +60,7 @@ func P(n *IAVLNode) string { func TestUnit(t *testing.T) { - expectHash := func(tree *IAVLTree, hashCount uint) { + expectHash := func(tree *IAVLTree, hashCount int) { // ensure number of new hash calculations is as expected. hash, count := tree.HashWithCount() if count != hashCount { @@ -78,7 +78,7 @@ func TestUnit(t *testing.T) { } } - expectSet := func(tree *IAVLTree, i int, repr string, hashCount uint) { + expectSet := func(tree *IAVLTree, i int, repr string, hashCount int) { origNode := tree.root updated := tree.Set(i, "") // ensure node was added & structure is as expected. @@ -91,7 +91,7 @@ func TestUnit(t *testing.T) { tree.root = origNode } - expectRemove := func(tree *IAVLTree, i int, repr string, hashCount uint) { + expectRemove := func(tree *IAVLTree, i int, repr string, hashCount int) { origNode := tree.root value, removed := tree.Remove(i) // ensure node was added & structure is as expected. @@ -168,7 +168,7 @@ func TestIntegration(t *testing.T) { if !updated { t.Error("should have been updated") } - if tree.Size() != uint(i+1) { + if tree.Size() != i+1 { t.Error("size was wrong", tree.Size(), i+1) } } @@ -203,7 +203,7 @@ func TestIntegration(t *testing.T) { t.Error("wrong value") } } - if tree.Size() != uint(len(records)-(i+1)) { + if tree.Size() != len(records)-(i+1) { t.Error("size was wrong", tree.Size(), (len(records) - (i + 1))) } } @@ -318,7 +318,7 @@ func BenchmarkImmutableAvlTree(b *testing.B) { // 23000ns/op, 43000ops/s // for i := 0; i < 10000000; i++ { for i := 0; i < 1000000; i++ { - t.Set(RandUint64(), "") + t.Set(RandInt64(), "") } fmt.Println("ok, starting") @@ -327,7 +327,7 @@ func BenchmarkImmutableAvlTree(b *testing.B) { b.StartTimer() for i := 0; i < b.N; i++ { - ri := RandUint64() + ri := RandInt64() t.Set(ri, "") t.Remove(ri) } diff --git a/merkle/iavl_tree.go b/merkle/iavl_tree.go index 66c2ea91..144ae9b6 100644 --- a/merkle/iavl_tree.go +++ b/merkle/iavl_tree.go @@ -68,14 +68,14 @@ func (t *IAVLTree) Copy() Tree { } } -func (t *IAVLTree) Size() uint { +func (t *IAVLTree) Size() int { if t.root == nil { return 0 } return t.root.size } -func (t *IAVLTree) Height() uint8 { +func (t *IAVLTree) Height() int8 { if t.root == nil { return 0 } @@ -106,7 +106,7 @@ func (t *IAVLTree) Hash() []byte { return hash } -func (t *IAVLTree) HashWithCount() ([]byte, uint) { +func (t *IAVLTree) HashWithCount() ([]byte, int) { if t.root == nil { return nil, 0 } @@ -130,14 +130,14 @@ func (t *IAVLTree) Load(hash []byte) { } } -func (t *IAVLTree) Get(key interface{}) (index uint, value interface{}) { +func (t *IAVLTree) Get(key interface{}) (index int, value interface{}) { if t.root == nil { return 0, nil } return t.root.get(t, key) } -func (t *IAVLTree) GetByIndex(index uint) (key interface{}, value interface{}) { +func (t *IAVLTree) GetByIndex(index int) (key interface{}, value interface{}) { if t.root == nil { return nil, nil } diff --git a/merkle/simple_tree.go b/merkle/simple_tree.go index 73465008..941ddb5c 100644 --- a/merkle/simple_tree.go +++ b/merkle/simple_tree.go @@ -90,8 +90,8 @@ func SimpleHashFromHashables(items []Hashable) []byte { //-------------------------------------------------------------------------------- type SimpleProof struct { - Index uint `json:"index"` - Total uint `json:"total"` + Index int `json:"index"` + Total int `json:"total"` LeafHash []byte `json:"leaf_hash"` InnerHashes [][]byte `json:"inner_hashes"` // Hashes from leaf's sibling to a root's child. RootHash []byte `json:"root_hash"` @@ -103,8 +103,8 @@ func SimpleProofsFromHashables(items []Hashable) (proofs []*SimpleProof) { proofs = make([]*SimpleProof, len(items)) for i, trail := range trails { proofs[i] = &SimpleProof{ - Index: uint(i), - Total: uint(len(items)), + Index: i, + Total: len(items), LeafHash: trail.Hash, InnerHashes: trail.FlattenInnerHashes(), RootHash: root.Hash, @@ -154,7 +154,7 @@ func (sp *SimpleProof) StringIndented(indent string) string { // Use the leafHash and innerHashes to get the root merkle hash. // If the length of the innerHashes slice isn't exactly correct, the result is nil. -func computeHashFromInnerHashes(index uint, total uint, leafHash []byte, innerHashes [][]byte) []byte { +func computeHashFromInnerHashes(index int, total int, leafHash []byte, innerHashes [][]byte) []byte { // Recursive impl. if index >= total { return nil diff --git a/merkle/simple_tree_test.go b/merkle/simple_tree_test.go index eabf8f32..5cbf732e 100644 --- a/merkle/simple_tree_test.go +++ b/merkle/simple_tree_test.go @@ -15,10 +15,10 @@ func (tI testItem) Hash() []byte { func TestSimpleProof(t *testing.T) { - numItems := uint(100) + numItems := 100 items := make([]Hashable, numItems) - for i := uint(0); i < numItems; i++ { + for i := 0; i < numItems; i++ { items[i] = testItem(RandBytes(32)) } diff --git a/merkle/types.go b/merkle/types.go index 68a46131..87f716c7 100644 --- a/merkle/types.go +++ b/merkle/types.go @@ -1,14 +1,14 @@ package merkle type Tree interface { - Size() (size uint) - Height() (height uint8) + Size() (size int) + Height() (height int8) Has(key interface{}) (has bool) - Get(key interface{}) (index uint, value interface{}) - GetByIndex(index uint) (key interface{}, value interface{}) + Get(key interface{}) (index int, value interface{}) + GetByIndex(index int) (key interface{}, value interface{}) Set(key interface{}, value interface{}) (updated bool) Remove(key interface{}) (value interface{}, removed bool) - HashWithCount() (hash []byte, count uint) + HashWithCount() (hash []byte, count int) Hash() (hash []byte) Save() (hash []byte) Load(hash []byte) diff --git a/merkle/util.go b/merkle/util.go index edc3fbf7..89fd2741 100644 --- a/merkle/util.go +++ b/merkle/util.go @@ -35,7 +35,7 @@ func printIAVLNode(node *IAVLNode, indent int) { } -func maxUint8(a, b uint8) uint8 { +func maxInt8(a, b int8) int8 { if a > b { return a } diff --git a/p2p/addrbook.go b/p2p/addrbook.go index e558c83b..99aa5cef 100644 --- a/p2p/addrbook.go +++ b/p2p/addrbook.go @@ -715,7 +715,7 @@ func groupKey(na *NetAddress) string { type knownAddress struct { Addr *NetAddress Src *NetAddress - Attempts uint32 + Attempts int32 LastAttempt time.Time LastSuccess time.Time BucketType byte diff --git a/p2p/connection.go b/p2p/connection.go index 17912925..856f40f3 100644 --- a/p2p/connection.go +++ b/p2p/connection.go @@ -441,9 +441,9 @@ FOR_LOOP: type ChannelDescriptor struct { Id byte - Priority uint - SendQueueCapacity uint - RecvBufferCapacity uint + Priority int + SendQueueCapacity int + RecvBufferCapacity int } func (chDesc *ChannelDescriptor) FillDefaults() { @@ -462,10 +462,10 @@ type Channel struct { desc *ChannelDescriptor id byte sendQueue chan []byte - sendQueueSize uint32 // atomic. + sendQueueSize int32 // atomic. recving []byte sending []byte - priority uint + priority int recentlySent int64 // exponential moving average } @@ -494,7 +494,7 @@ func (ch *Channel) sendBytes(bytes []byte) bool { // timeout return false case ch.sendQueue <- bytes: - atomic.AddUint32(&ch.sendQueueSize, 1) + atomic.AddInt32(&ch.sendQueueSize, 1) return true } } @@ -505,7 +505,7 @@ func (ch *Channel) sendBytes(bytes []byte) bool { func (ch *Channel) trySendBytes(bytes []byte) bool { select { case ch.sendQueue <- bytes: - atomic.AddUint32(&ch.sendQueueSize, 1) + atomic.AddInt32(&ch.sendQueueSize, 1) return true default: return false @@ -514,7 +514,7 @@ func (ch *Channel) trySendBytes(bytes []byte) bool { // Goroutine-safe func (ch *Channel) loadSendQueueSize() (size int) { - return int(atomic.LoadUint32(&ch.sendQueueSize)) + return int(atomic.LoadInt32(&ch.sendQueueSize)) } // Goroutine-safe @@ -545,7 +545,7 @@ func (ch *Channel) nextMsgPacket() msgPacket { if len(ch.sending) <= maxMsgPacketSize { packet.EOF = byte(0x01) ch.sending = nil - atomic.AddUint32(&ch.sendQueueSize, ^uint32(0)) // decrement sendQueueSize + atomic.AddInt32(&ch.sendQueueSize, -1) // decrement sendQueueSize } else { packet.EOF = byte(0x00) ch.sending = ch.sending[MinInt(maxMsgPacketSize, len(ch.sending)):] diff --git a/rpc/core/accounts.go b/rpc/core/accounts.go index e102e1b7..167f0ca5 100644 --- a/rpc/core/accounts.go +++ b/rpc/core/accounts.go @@ -44,7 +44,7 @@ func GetStorage(address, key []byte) (*ctypes.ResponseGetStorage, error) { } func ListAccounts() (*ctypes.ResponseListAccounts, error) { - var blockHeight uint + var blockHeight int var accounts []*acm.Account state := consensusState.GetState() blockHeight = state.LastBlockHeight diff --git a/rpc/core/blocks.go b/rpc/core/blocks.go index 4479e926..3a5bbdfb 100644 --- a/rpc/core/blocks.go +++ b/rpc/core/blocks.go @@ -9,14 +9,14 @@ import ( //----------------------------------------------------------------------------- -func BlockchainInfo(minHeight, maxHeight uint) (*ctypes.ResponseBlockchainInfo, error) { +func BlockchainInfo(minHeight, maxHeight int) (*ctypes.ResponseBlockchainInfo, error) { if maxHeight == 0 { maxHeight = blockStore.Height() } else { - maxHeight = MinUint(blockStore.Height(), maxHeight) + maxHeight = MinInt(blockStore.Height(), maxHeight) } if minHeight == 0 { - minHeight = uint(MaxInt(1, int(maxHeight)-20)) + minHeight = MaxInt(1, maxHeight-20) } log.Debug("BlockchainInfoHandler", "maxHeight", maxHeight, "minHeight", minHeight) @@ -31,7 +31,7 @@ func BlockchainInfo(minHeight, maxHeight uint) (*ctypes.ResponseBlockchainInfo, //----------------------------------------------------------------------------- -func GetBlock(height uint) (*ctypes.ResponseGetBlock, error) { +func GetBlock(height int) (*ctypes.ResponseGetBlock, error) { if height == 0 { return nil, fmt.Errorf("height must be greater than 0") } diff --git a/rpc/core/consensus.go b/rpc/core/consensus.go index 059bc64a..b97c6155 100644 --- a/rpc/core/consensus.go +++ b/rpc/core/consensus.go @@ -8,17 +8,17 @@ import ( ) func ListValidators() (*ctypes.ResponseListValidators, error) { - var blockHeight uint + var blockHeight int var bondedValidators []*sm.Validator var unbondingValidators []*sm.Validator state := consensusState.GetState() blockHeight = state.LastBlockHeight - state.BondedValidators.Iterate(func(index uint, val *sm.Validator) bool { + state.BondedValidators.Iterate(func(index int, val *sm.Validator) bool { bondedValidators = append(bondedValidators, val) return false }) - state.UnbondingValidators.Iterate(func(index uint, val *sm.Validator) bool { + state.UnbondingValidators.Iterate(func(index int, val *sm.Validator) bool { unbondingValidators = append(unbondingValidators, val) return false }) diff --git a/rpc/core/mempool.go b/rpc/core/mempool.go index c9e83b3d..140cf099 100644 --- a/rpc/core/mempool.go +++ b/rpc/core/mempool.go @@ -23,7 +23,7 @@ func BroadcastTx(tx types.Tx) (*ctypes.Receipt, error) { if callTx, ok := tx.(*types.CallTx); ok { if len(callTx.Address) == 0 { createsContract = 1 - contractAddr = state.NewContractAddress(callTx.Input.Address, uint64(callTx.Input.Sequence)) + contractAddr = state.NewContractAddress(callTx.Input.Address, callTx.Input.Sequence) } } return &ctypes.Receipt{txHash, createsContract, contractAddr}, nil diff --git a/rpc/core/names.go b/rpc/core/names.go index 7f0d872e..01c7cef1 100644 --- a/rpc/core/names.go +++ b/rpc/core/names.go @@ -17,7 +17,7 @@ func GetName(name string) (*types.NameRegEntry, error) { } func ListNames() (*ctypes.ResponseListNames, error) { - var blockHeight uint + var blockHeight int var names []*types.NameRegEntry state := consensusState.GetState() blockHeight = state.LastBlockHeight diff --git a/rpc/core/txs.go b/rpc/core/txs.go index be269f47..8a80cd4e 100644 --- a/rpc/core/txs.go +++ b/rpc/core/txs.go @@ -15,7 +15,7 @@ func toVMAccount(acc *account.Account) *vm.Account { Address: LeftPadWord256(acc.Address), Balance: acc.Balance, Code: acc.Code, // This is crazy. - Nonce: uint64(acc.Sequence), + Nonce: int64(acc.Sequence), StorageRoot: LeftPadWord256(acc.StorageRoot), Other: acc.PubKey, } @@ -36,14 +36,14 @@ func Call(address, data []byte) (*ctypes.ResponseCall, error) { caller := &vm.Account{Address: Zero256} txCache := state.NewTxCache(cache) params := vm.Params{ - BlockHeight: uint64(st.LastBlockHeight), + BlockHeight: int64(st.LastBlockHeight), BlockHash: LeftPadWord256(st.LastBlockHash), BlockTime: st.LastBlockTime.Unix(), GasLimit: 10000000, } vmach := vm.NewVM(txCache, params, caller.Address, nil) - gas := uint64(1000000000) + gas := int64(1000000000) ret, err := vmach.Call(caller, callee, callee.Code, data, 0, &gas) if err != nil { return nil, err @@ -61,14 +61,14 @@ func CallCode(code, data []byte) (*ctypes.ResponseCall, error) { caller := &vm.Account{Address: Zero256} txCache := state.NewTxCache(cache) params := vm.Params{ - BlockHeight: uint64(st.LastBlockHeight), + BlockHeight: int64(st.LastBlockHeight), BlockHash: LeftPadWord256(st.LastBlockHash), BlockTime: st.LastBlockTime.Unix(), GasLimit: 10000000, } vmach := vm.NewVM(txCache, params, caller.Address, nil) - gas := uint64(1000000000) + gas := int64(1000000000) ret, err := vmach.Call(caller, callee, code, data, 0, &gas) if err != nil { return nil, err diff --git a/rpc/core/types/responses.go b/rpc/core/types/responses.go index 221b9562..02dc267d 100644 --- a/rpc/core/types/responses.go +++ b/rpc/core/types/responses.go @@ -13,12 +13,12 @@ type ResponseGetStorage struct { type ResponseCall struct { Return []byte `json:"return"` - GasUsed uint64 `json:"gas_used"` + GasUsed int64 `json:"gas_used"` // TODO ... } type ResponseListAccounts struct { - BlockHeight uint `json:"block_height"` + BlockHeight int `json:"block_height"` Accounts []*account.Account `json:"accounts"` } @@ -33,7 +33,7 @@ type ResponseDumpStorage struct { } type ResponseBlockchainInfo struct { - LastHeight uint `json:"last_height"` + LastHeight int `json:"last_height"` BlockMetas []*types.BlockMeta `json:"block_metas"` } @@ -55,7 +55,7 @@ type ResponseStatus struct { GenesisHash []byte `json:"genesis_hash"` PubKey account.PubKey `json:"pub_key"` LatestBlockHash []byte `json:"latest_block_hash"` - LatestBlockHeight uint `json:"latest_block_height"` + LatestBlockHeight int `json:"latest_block_height"` LatestBlockTime int64 `json:"latest_block_time"` // nano } @@ -71,7 +71,7 @@ type Peer struct { } type ResponseListValidators struct { - BlockHeight uint `json:"block_height"` + BlockHeight int `json:"block_height"` BondedValidators []*sm.Validator `json:"bonded_validators"` UnbondingValidators []*sm.Validator `json:"unbonding_validators"` } @@ -82,6 +82,6 @@ type ResponseDumpConsensusState struct { } type ResponseListNames struct { - BlockHeight uint `json:"block_height"` + BlockHeight int `json:"block_height"` Names []*types.NameRegEntry `json:"names"` } diff --git a/rpc/server/handlers.go b/rpc/server/handlers.go index 2180a06b..77ecc5c9 100644 --- a/rpc/server/handlers.go +++ b/rpc/server/handlers.go @@ -224,7 +224,7 @@ type WSConnection struct { wsConn *websocket.Conn writeChan chan WSResponse quitChan chan struct{} - failedSends uint + failedSends int started uint32 stopped uint32 diff --git a/rpc/test/client_ws_test.go b/rpc/test/client_ws_test.go index a310871b..2ea16c95 100644 --- a/rpc/test/client_ws_test.go +++ b/rpc/test/client_ws_test.go @@ -51,7 +51,7 @@ func TestWSBlockchainGrowth(t *testing.T) { // send a transaction and validate the events from listening for both sender and receiver func TestWSSend(t *testing.T) { toAddr := user[1].Address - amt := uint64(100) + amt := int64(100) con := newWSCon(t) eidInput := types.EventStringAccInput(user[0].Address) @@ -79,7 +79,7 @@ func TestWSDoubleFire(t *testing.T) { unsubscribe(t, con, eid) con.Close() }() - amt := uint64(100) + amt := int64(100) toAddr := user[1].Address // broadcast the transaction, wait to hear about it waitForEvent(t, con, eid, true, func() { @@ -104,7 +104,7 @@ func TestWSCallWait(t *testing.T) { unsubscribe(t, con, eid1) con.Close() }() - amt, gasLim, fee := uint64(10000), uint64(1000), uint64(1000) + amt, gasLim, fee := int64(10000), int64(1000), int64(1000) code, returnCode, returnVal := simpleContract() var contractAddr []byte // wait for the contract to be created @@ -115,7 +115,7 @@ func TestWSCallWait(t *testing.T) { }, unmarshalValidateCall(amt, returnCode)) // susbscribe to the new contract - amt = uint64(10001) + amt = int64(10001) eid2 := types.EventStringAccOutput(contractAddr) subscribe(t, con, eid2) defer func() { @@ -134,7 +134,7 @@ func TestWSCallWait(t *testing.T) { // and validate return func TestWSCallNoWait(t *testing.T) { con := newWSCon(t) - amt, gasLim, fee := uint64(10000), uint64(1000), uint64(1000) + amt, gasLim, fee := int64(10000), int64(1000), int64(1000) code, _, returnVal := simpleContract() tx := makeDefaultCallTx(t, wsTyp, nil, code, amt, gasLim, fee) @@ -142,7 +142,7 @@ func TestWSCallNoWait(t *testing.T) { contractAddr := receipt.ContractAddr // susbscribe to the new contract - amt = uint64(10001) + amt = int64(10001) eid := types.EventStringAccOutput(contractAddr) subscribe(t, con, eid) defer func() { @@ -160,7 +160,7 @@ func TestWSCallNoWait(t *testing.T) { // create two contracts, one of which calls the other func TestWSCallCall(t *testing.T) { con := newWSCon(t) - amt, gasLim, fee := uint64(10000), uint64(1000), uint64(1000) + amt, gasLim, fee := int64(10000), int64(1000), int64(1000) code, _, returnVal := simpleContract() txid := new([]byte) @@ -175,7 +175,7 @@ func TestWSCallCall(t *testing.T) { contractAddr2 := receipt.ContractAddr // susbscribe to the new contracts - amt = uint64(10001) + amt = int64(10001) eid1 := types.EventStringAccReceive(contractAddr1) subscribe(t, con, eid1) defer func() { diff --git a/rpc/test/helpers.go b/rpc/test/helpers.go index e794ef29..87f905f4 100644 --- a/rpc/test/helpers.go +++ b/rpc/test/helpers.go @@ -88,7 +88,7 @@ func init() { //------------------------------------------------------------------------------- // some default transaction functions -func makeDefaultSendTx(t *testing.T, typ string, addr []byte, amt uint64) *types.SendTx { +func makeDefaultSendTx(t *testing.T, typ string, addr []byte, amt int64) *types.SendTx { nonce := getNonce(t, typ, user[0].Address) tx := types.NewSendTx() tx.AddInputWithNonce(user[0].PubKey, amt, nonce+1) @@ -96,20 +96,20 @@ func makeDefaultSendTx(t *testing.T, typ string, addr []byte, amt uint64) *types return tx } -func makeDefaultSendTxSigned(t *testing.T, typ string, addr []byte, amt uint64) *types.SendTx { +func makeDefaultSendTxSigned(t *testing.T, typ string, addr []byte, amt int64) *types.SendTx { tx := makeDefaultSendTx(t, typ, addr, amt) tx.SignInput(chainID, 0, user[0]) return tx } -func makeDefaultCallTx(t *testing.T, typ string, addr, code []byte, amt, gasLim, fee uint64) *types.CallTx { +func makeDefaultCallTx(t *testing.T, typ string, addr, code []byte, amt, gasLim, fee int64) *types.CallTx { nonce := getNonce(t, typ, user[0].Address) tx := types.NewCallTxWithNonce(user[0].PubKey, addr, code, amt, gasLim, fee, nonce+1) tx.Sign(chainID, user[0]) return tx } -func makeDefaultNameTx(t *testing.T, typ string, name, value string, amt, fee uint64) *types.NameTx { +func makeDefaultNameTx(t *testing.T, typ string, name, value string, amt, fee int64) *types.NameTx { nonce := getNonce(t, typ, user[0].Address) tx := types.NewNameTxWithNonce(user[0].PubKey, name, value, amt, fee, nonce+1) tx.Sign(chainID, user[0]) @@ -120,7 +120,7 @@ func makeDefaultNameTx(t *testing.T, typ string, name, value string, amt, fee ui // rpc call wrappers (fail on err) // get an account's nonce -func getNonce(t *testing.T, typ string, addr []byte) uint { +func getNonce(t *testing.T, typ string, addr []byte) int { client := clients[typ] ac, err := client.GetAccount(addr) if err != nil { diff --git a/rpc/test/tests.go b/rpc/test/tests.go index b98914cb..215eb9b3 100644 --- a/rpc/test/tests.go +++ b/rpc/test/tests.go @@ -45,7 +45,7 @@ func testGetAccount(t *testing.T, typ string) { } func testSignedTx(t *testing.T, typ string) { - amt := uint64(100) + amt := int64(100) toAddr := user[1].Address testOneSignTx(t, typ, toAddr, amt) @@ -56,7 +56,7 @@ func testSignedTx(t *testing.T, typ string) { testOneSignTx(t, typ, toAddr, amt) } -func testOneSignTx(t *testing.T, typ string, addr []byte, amt uint64) { +func testOneSignTx(t *testing.T, typ string, addr []byte, amt int64) { tx := makeDefaultSendTx(t, typ, addr, amt) tx2 := signTx(t, typ, tx, user[0]) tx2hash := account.HashSignBytes(chainID, tx2) @@ -72,7 +72,7 @@ func testOneSignTx(t *testing.T, typ string, addr []byte, amt uint64) { } func testBroadcastTx(t *testing.T, typ string) { - amt := uint64(100) + amt := int64(100) toAddr := user[1].Address tx := makeDefaultSendTxSigned(t, typ, toAddr, amt) receipt := broadcastTx(t, typ, tx) @@ -106,7 +106,7 @@ func testGetStorage(t *testing.T, typ string) { con.Close() }() - amt, gasLim, fee := uint64(1100), uint64(1000), uint64(1000) + amt, gasLim, fee := int64(1100), int64(1000), int64(1000) code := []byte{0x60, 0x5, 0x60, 0x1, 0x55} tx := makeDefaultCallTx(t, typ, nil, code, amt, gasLim, fee) receipt := broadcastTx(t, typ, tx) @@ -161,7 +161,7 @@ func testCall(t *testing.T, typ string) { client := clients[typ] // create the contract - amt, gasLim, fee := uint64(6969), uint64(1000), uint64(1000) + amt, gasLim, fee := int64(6969), int64(1000), int64(1000) code, _, _ := simpleContract() tx := makeDefaultCallTx(t, typ, nil, code, amt, gasLim, fee) receipt := broadcastTx(t, typ, tx) @@ -203,8 +203,8 @@ func testNameReg(t *testing.T, typ string) { // since entries ought to be unique and these run against different clients, we append the typ name := "ye_old_domain_name_" + typ data := "if not now, when" - fee := uint64(1000) - numDesiredBlocks := uint64(2) + fee := int64(1000) + numDesiredBlocks := int64(2) amt := fee + numDesiredBlocks*types.NameCostPerByte*types.NameCostPerBlock*types.BaseEntryCost(name, data) tx := makeDefaultNameTx(t, typ, name, data, amt, fee) @@ -221,7 +221,7 @@ func testNameReg(t *testing.T, typ string) { } // update the data as the owner, make sure still there - numDesiredBlocks = uint64(2) + numDesiredBlocks = int64(2) data = "these are amongst the things I wish to bestow upon the youth of generations come: a safe supply of honey, and a better money. For what else shall they need" amt = fee + numDesiredBlocks*types.NameCostPerByte*types.NameCostPerBlock*types.BaseEntryCost(name, data) tx = makeDefaultNameTx(t, typ, name, data, amt, fee) diff --git a/rpc/test/ws_helpers.go b/rpc/test/ws_helpers.go index 55d074ae..211493d1 100644 --- a/rpc/test/ws_helpers.go +++ b/rpc/test/ws_helpers.go @@ -133,7 +133,7 @@ func unmarshalResponseNewBlock(b []byte) (*types.Block, error) { } func unmarshalValidateBlockchain(t *testing.T, con *websocket.Conn, eid string) { - var initBlockN uint + var initBlockN int for i := 0; i < 2; i++ { waitForEvent(t, con, eid, true, func() {}, func(eid string, b []byte) error { block, err := unmarshalResponseNewBlock(b) @@ -143,7 +143,7 @@ func unmarshalValidateBlockchain(t *testing.T, con *websocket.Conn, eid string) if i == 0 { initBlockN = block.Header.Height } else { - if block.Header.Height != initBlockN+uint(i) { + if block.Header.Height != initBlockN+i { return fmt.Errorf("Expected block %d, got block %d", i, block.Header.Height) } } @@ -153,7 +153,7 @@ func unmarshalValidateBlockchain(t *testing.T, con *websocket.Conn, eid string) } } -func unmarshalValidateSend(amt uint64, toAddr []byte) func(string, []byte) error { +func unmarshalValidateSend(amt int64, toAddr []byte) func(string, []byte) error { return func(eid string, b []byte) error { // unmarshal and assert correctness var response struct { @@ -186,7 +186,7 @@ func unmarshalValidateSend(amt uint64, toAddr []byte) func(string, []byte) error } } -func unmarshalValidateCall(amt uint64, returnCode []byte) func(string, []byte) error { +func unmarshalValidateCall(amt int64, returnCode []byte) func(string, []byte) error { return func(eid string, b []byte) error { // unmarshall and assert somethings var response struct { diff --git a/state/execution.go b/state/execution.go index c68bf4ea..16b051ba 100644 --- a/state/execution.go +++ b/state/execution.go @@ -44,7 +44,7 @@ func execBlock(s *State, block *types.Block, blockPartsHeader types.PartSetHeade return errors.New("Block at height 1 (first block) should have no LastValidation precommits") } } else { - if uint(len(block.LastValidation.Precommits)) != s.LastBondedValidators.Size() { + if len(block.LastValidation.Precommits) != s.LastBondedValidators.Size() { return errors.New(Fmt("Invalid block validation size. Expected %v, got %v", s.LastBondedValidators.Size(), len(block.LastValidation.Precommits))) } @@ -60,7 +60,7 @@ func execBlock(s *State, block *types.Block, blockPartsHeader types.PartSetHeade if precommit == nil { continue } - _, val := s.LastBondedValidators.GetByIndex(uint(i)) + _, val := s.LastBondedValidators.GetByIndex(i) if val == nil { panic(Fmt("Failed to fetch validator at index %v", i)) } @@ -101,7 +101,7 @@ func execBlock(s *State, block *types.Block, blockPartsHeader types.PartSetHeade // If any unbonding periods are over, // reward account with bonded coins. toRelease := []*Validator{} - s.UnbondingValidators.Iterate(func(index uint, val *Validator) bool { + s.UnbondingValidators.Iterate(func(index int, val *Validator) bool { if val.UnbondHeight+unbondingPeriodBlocks < block.Height { toRelease = append(toRelease, val) } @@ -114,8 +114,8 @@ func execBlock(s *State, block *types.Block, blockPartsHeader types.PartSetHeade // If any validators haven't signed in a while, // unbond them, they have timed out. toTimeout := []*Validator{} - s.BondedValidators.Iterate(func(index uint, val *Validator) bool { - lastActivityHeight := MaxUint(val.BondHeight, val.LastCommitHeight) + s.BondedValidators.Iterate(func(index int, val *Validator) bool { + lastActivityHeight := MaxInt(val.BondHeight, val.LastCommitHeight) if lastActivityHeight+validatorTimeoutBlocks < block.Height { log.Info("Validator timeout", "validator", val, "height", block.Height) toTimeout = append(toTimeout, val) @@ -191,7 +191,7 @@ func checkInputPubKey(acc *account.Account, in *types.TxInput) error { return nil } -func validateInputs(accounts map[string]*account.Account, signBytes []byte, ins []*types.TxInput) (total uint64, err error) { +func validateInputs(accounts map[string]*account.Account, signBytes []byte, ins []*types.TxInput) (total int64, err error) { for _, in := range ins { acc := accounts[string(in.Address)] if acc == nil { @@ -219,8 +219,8 @@ func validateInput(acc *account.Account, signBytes []byte, in *types.TxInput) (e // Check sequences if acc.Sequence+1 != in.Sequence { return types.ErrTxInvalidSequence{ - Got: uint64(in.Sequence), - Expected: uint64(acc.Sequence + 1), + Got: in.Sequence, + Expected: acc.Sequence + 1, } } // Check amount @@ -230,7 +230,7 @@ func validateInput(acc *account.Account, signBytes []byte, in *types.TxInput) (e return nil } -func validateOutputs(outs []*types.TxOutput) (total uint64, err error) { +func validateOutputs(outs []*types.TxOutput) (total int64, err error) { for _, out := range outs { // Check TxOutput basic if err := out.ValidateBasic(); err != nil { @@ -271,7 +271,7 @@ func adjustByOutputs(accounts map[string]*account.Account, outs []*types.TxOutpu func ExecTx(blockCache *BlockCache, tx_ types.Tx, runCall bool, evc events.Fireable) error { // TODO: do something with fees - fees := uint64(0) + fees := int64(0) _s := blockCache.State() // hack to access validators and block height // Exec tx @@ -362,14 +362,14 @@ func ExecTx(blockCache *BlockCache, tx_ types.Tx, runCall bool, evc events.Firea if runCall { var ( - gas uint64 = tx.GasLimit + gas int64 = tx.GasLimit err error = nil caller *vm.Account = toVMAccount(inAcc) callee *vm.Account = nil code []byte = nil txCache = NewTxCache(blockCache) params = vm.Params{ - BlockHeight: uint64(_s.LastBlockHeight), + BlockHeight: int64(_s.LastBlockHeight), BlockHash: LeftPadWord256(_s.LastBlockHash), BlockTime: _s.LastBlockTime.Unix(), GasLimit: 10000000, @@ -490,8 +490,8 @@ func ExecTx(blockCache *BlockCache, tx_ types.Tx, runCall bool, evc events.Firea // let's say cost of a name for one block is len(data) + 32 costPerBlock := types.NameCostPerBlock * types.NameCostPerByte * tx.BaseEntryCost() - expiresIn := value / uint64(costPerBlock) - lastBlockHeight := uint64(_s.LastBlockHeight) + expiresIn := int(value / costPerBlock) + lastBlockHeight := _s.LastBlockHeight log.Debug("New NameTx", "value", value, "costPerBlock", costPerBlock, "expiresIn", expiresIn, "lastBlock", lastBlockHeight) @@ -530,9 +530,9 @@ func ExecTx(blockCache *BlockCache, tx_ types.Tx, runCall bool, evc events.Firea } else { // since the size of the data may have changed // we use the total amount of "credit" - oldCredit := (entry.Expires - lastBlockHeight) * types.BaseEntryCost(entry.Name, entry.Data) + oldCredit := int64(entry.Expires-lastBlockHeight) * types.BaseEntryCost(entry.Name, entry.Data) credit := oldCredit + value - expiresIn = credit / costPerBlock + expiresIn = int(credit / costPerBlock) if expiresIn < types.MinNameRegistrationPeriod { return fmt.Errorf("Names must be registered for at least %d blocks", types.MinNameRegistrationPeriod) } diff --git a/state/genesis.go b/state/genesis.go index 2024e211..47576d1e 100644 --- a/state/genesis.go +++ b/state/genesis.go @@ -14,12 +14,12 @@ import ( type GenesisAccount struct { Address []byte `json:"address"` - Amount uint64 `json:"amount"` + Amount int64 `json:"amount"` } type GenesisValidator struct { PubKey account.PubKeyEd25519 `json:"pub_key"` - Amount uint64 `json:"amount"` + Amount int64 `json:"amount"` UnbondTo []GenesisAccount `json:"unbond_to"` } diff --git a/state/priv_validator.go b/state/priv_validator.go index 41c8b913..d88f17b8 100644 --- a/state/priv_validator.go +++ b/state/priv_validator.go @@ -23,7 +23,7 @@ const ( stepPrecommit = 3 ) -func voteToStep(vote *types.Vote) uint8 { +func voteToStep(vote *types.Vote) int8 { switch vote.Type { case types.VoteTypePrevote: return stepPrevote @@ -38,9 +38,9 @@ type PrivValidator struct { Address []byte `json:"address"` PubKey account.PubKeyEd25519 `json:"pub_key"` PrivKey account.PrivKeyEd25519 `json:"priv_key"` - LastHeight uint `json:"last_height"` - LastRound uint `json:"last_round"` - LastStep uint8 `json:"last_step"` + LastHeight int `json:"last_height"` + LastRound int `json:"last_round"` + LastStep int8 `json:"last_step"` // For persistence. // Overloaded for testing. @@ -166,8 +166,8 @@ func (privVal *PrivValidator) SignRebondTx(chainID string, rebondTx *types.Rebon // Persist height/round/step privVal.LastHeight = rebondTx.Height - privVal.LastRound = math.MaxUint64 // We can't do anything else for this rebondTx.Height. - privVal.LastStep = math.MaxUint8 + privVal.LastRound = math.MaxInt64 // We can't do anything else for this rebondTx.Height. + privVal.LastStep = math.MaxInt8 privVal.save() // Sign diff --git a/state/state.go b/state/state.go index e7486b27..c8d5d512 100644 --- a/state/state.go +++ b/state/state.go @@ -16,10 +16,10 @@ import ( var ( stateKey = []byte("stateKey") - minBondAmount = uint64(1) // TODO adjust - defaultAccountsCacheCapacity = 1000 // TODO adjust - unbondingPeriodBlocks = uint(60 * 24 * 365) // TODO probably better to make it time based. - validatorTimeoutBlocks = uint(10) // TODO adjust + minBondAmount = int64(1) // TODO adjust + defaultAccountsCacheCapacity = 1000 // TODO adjust + unbondingPeriodBlocks = int(60 * 24 * 365) // TODO probably better to make it time based. + validatorTimeoutBlocks = int(10) // TODO adjust ) //----------------------------------------------------------------------------- @@ -28,7 +28,7 @@ var ( type State struct { DB dbm.DB ChainID string - LastBlockHeight uint + LastBlockHeight int LastBlockHash []byte LastBlockParts types.PartSetHeader LastBlockTime time.Time @@ -50,7 +50,7 @@ func LoadState(db dbm.DB) *State { } else { r, n, err := bytes.NewReader(buf), new(int64), new(error) s.ChainID = binary.ReadString(r, n, err) - s.LastBlockHeight = binary.ReadUvarint(r, n, err) + s.LastBlockHeight = binary.ReadVarint(r, n, err) s.LastBlockHash = binary.ReadByteSlice(r, n, err) s.LastBlockParts = binary.ReadBinary(types.PartSetHeader{}, r, n, err).(types.PartSetHeader) s.LastBlockTime = binary.ReadTime(r, n, err) @@ -80,7 +80,7 @@ func (s *State) Save() { s.nameReg.Save() buf, n, err := new(bytes.Buffer), new(int64), new(error) binary.WriteString(s.ChainID, buf, n, err) - binary.WriteUvarint(s.LastBlockHeight, buf, n, err) + binary.WriteVarint(s.LastBlockHeight, buf, n, err) binary.WriteByteSlice(s.LastBlockHash, buf, n, err) binary.WriteBinary(s.LastBlockParts, buf, n, err) binary.WriteTime(s.LastBlockTime, buf, n, err) diff --git a/state/state_test.go b/state/state_test.go index 6a221977..7078cea0 100644 --- a/state/state_test.go +++ b/state/state_test.go @@ -81,7 +81,7 @@ func makeBlock(t *testing.T, state *State, validation *types.Validation, txs []t Height: state.LastBlockHeight + 1, Time: state.LastBlockTime.Add(time.Minute), Fees: 0, - NumTxs: uint(len(txs)), + NumTxs: len(txs), LastBlockHash: state.LastBlockHash, LastBlockParts: state.LastBlockParts, StateHash: nil, @@ -179,7 +179,7 @@ func TestTxSequence(t *testing.T) { // Test a variety of sequence numbers for the tx. // The tx should only pass when i == 1. for i := -1; i < 3; i++ { - sequence := acc0.Sequence + uint(i) + sequence := acc0.Sequence + i tx := types.NewSendTx() tx.AddInputWithNonce(acc0PubKey, 1, sequence) tx.AddOutput(acc1.Address, 1) @@ -216,15 +216,15 @@ func TestNameTxs(t *testing.T) { state, privAccounts, _ := RandGenesisState(3, true, 1000, 1, true, 1000) types.MinNameRegistrationPeriod = 5 - startingBlock := uint64(state.LastBlockHeight) + startingBlock := state.LastBlockHeight // try some bad names. these should all fail names := []string{"", "\n", "123#$%", "\x00", string([]byte{20, 40, 60, 80}), "baffledbythespectacleinallofthisyouseeehesaidwithouteyes", "no spaces please"} data := "something about all this just doesn't feel right." - fee := uint64(1000) - numDesiredBlocks := uint64(5) + fee := int64(1000) + numDesiredBlocks := 5 for _, name := range names { - amt := fee + numDesiredBlocks*types.NameCostPerByte*types.NameCostPerBlock*types.BaseEntryCost(name, data) + amt := fee + int64(numDesiredBlocks)*types.NameCostPerByte*types.NameCostPerBlock*types.BaseEntryCost(name, data) tx, _ := types.NewNameTx(state, privAccounts[0].PubKey, name, data, amt, fee) tx.Sign(state.ChainID, privAccounts[0]) @@ -237,7 +237,7 @@ func TestNameTxs(t *testing.T) { name := "hold_it_chum" datas := []string{"cold&warm", "!@#$%^&*()", "<<<>>>>", "because why would you ever need a ~ or a & or even a % in a json file? make your case and we'll talk"} for _, data := range datas { - amt := fee + numDesiredBlocks*types.NameCostPerByte*types.NameCostPerBlock*types.BaseEntryCost(name, data) + amt := fee + int64(numDesiredBlocks)*types.NameCostPerByte*types.NameCostPerBlock*types.BaseEntryCost(name, data) tx, _ := types.NewNameTx(state, privAccounts[0].PubKey, name, data, amt, fee) tx.Sign(state.ChainID, privAccounts[0]) @@ -246,7 +246,7 @@ func TestNameTxs(t *testing.T) { } } - validateEntry := func(t *testing.T, entry *types.NameRegEntry, name, data string, addr []byte, expires uint64) { + validateEntry := func(t *testing.T, entry *types.NameRegEntry, name, data string, addr []byte, expires int) { if entry == nil { t.Fatalf("Could not find name %s", name) @@ -268,7 +268,7 @@ func TestNameTxs(t *testing.T) { // try a good one, check data, owner, expiry name = "looking_good/karaoke_bar" data = "on this side of neptune there are 1234567890 people: first is OMNIVORE. Or is it. Ok this is pretty restrictive. No exclamations :(. Faces tho :')" - amt := fee + numDesiredBlocks*types.NameCostPerByte*types.NameCostPerBlock*types.BaseEntryCost(name, data) + amt := fee + int64(numDesiredBlocks)*types.NameCostPerByte*types.NameCostPerBlock*types.BaseEntryCost(name, data) tx, _ := types.NewNameTx(state, privAccounts[0].PubKey, name, data, amt, fee) tx.Sign(state.ChainID, privAccounts[0]) if err := execTxWithState(state, tx, true); err != nil { @@ -304,7 +304,7 @@ func TestNameTxs(t *testing.T) { validateEntry(t, entry, name, data, privAccounts[0].Address, startingBlock+numDesiredBlocks*3) // fail to update it as non-owner - state.LastBlockHeight = uint(entry.Expires - 1) + state.LastBlockHeight = entry.Expires - 1 tx, _ = types.NewNameTx(state, privAccounts[1].PubKey, name, data, amt, fee) tx.Sign(state.ChainID, privAccounts[1]) if err := execTxWithState(state, tx, true); err == nil { @@ -312,27 +312,27 @@ func TestNameTxs(t *testing.T) { } // once expires, non-owner succeeds - state.LastBlockHeight = uint(entry.Expires) + state.LastBlockHeight = entry.Expires tx, _ = types.NewNameTx(state, privAccounts[1].PubKey, name, data, amt, fee) tx.Sign(state.ChainID, privAccounts[1]) if err := execTxWithState(state, tx, true); err != nil { t.Fatal(err) } entry = state.GetNameRegEntry(name) - validateEntry(t, entry, name, data, privAccounts[1].Address, uint64(state.LastBlockHeight)+numDesiredBlocks) + validateEntry(t, entry, name, data, privAccounts[1].Address, state.LastBlockHeight+numDesiredBlocks) // update it as new owner, with new data (longer), but keep the expiry! data = "In the beginning there was no thing, not even the beginning. It hadn't been here, no there, nor for that matter anywhere, not especially because it had not to even exist, let alone to not. Nothing especially odd about that." oldCredit := amt - fee numDesiredBlocks = 10 - amt = fee + (numDesiredBlocks*types.NameCostPerByte*types.NameCostPerBlock*types.BaseEntryCost(name, data) - oldCredit) + amt = fee + (int64(numDesiredBlocks)*types.NameCostPerByte*types.NameCostPerBlock*types.BaseEntryCost(name, data) - oldCredit) tx, _ = types.NewNameTx(state, privAccounts[1].PubKey, name, data, amt, fee) tx.Sign(state.ChainID, privAccounts[1]) if err := execTxWithState(state, tx, true); err != nil { t.Fatal(err) } entry = state.GetNameRegEntry(name) - validateEntry(t, entry, name, data, privAccounts[1].Address, uint64(state.LastBlockHeight)+numDesiredBlocks) + validateEntry(t, entry, name, data, privAccounts[1].Address, state.LastBlockHeight+numDesiredBlocks) // test removal amt = fee @@ -351,15 +351,15 @@ func TestNameTxs(t *testing.T) { // test removal by key1 after expiry name = "looking_good/karaoke_bar" data = "some data" - amt = fee + numDesiredBlocks*types.NameCostPerByte*types.NameCostPerBlock*types.BaseEntryCost(name, data) + amt = fee + int64(numDesiredBlocks)*types.NameCostPerByte*types.NameCostPerBlock*types.BaseEntryCost(name, data) tx, _ = types.NewNameTx(state, privAccounts[0].PubKey, name, data, amt, fee) tx.Sign(state.ChainID, privAccounts[0]) if err := execTxWithState(state, tx, true); err != nil { t.Fatal(err) } entry = state.GetNameRegEntry(name) - validateEntry(t, entry, name, data, privAccounts[0].Address, uint64(state.LastBlockHeight)+numDesiredBlocks) - state.LastBlockHeight = uint(entry.Expires) + validateEntry(t, entry, name, data, privAccounts[0].Address, state.LastBlockHeight+numDesiredBlocks) + state.LastBlockHeight = entry.Expires amt = fee data = "" @@ -474,7 +474,7 @@ attack the network, they'll generate the longest chain and outpace attackers. network itself requires minimal structure. Messages are broadcast on a best effort basis, and nodes can leave and rejoin the network at will, accepting the longest proof-of-work chain as proof of what happened while they were gone ` - entryAmount := uint64(10000) + entryAmount := int64(10000) state := state.Copy() tx := &types.NameTx{ diff --git a/state/test.go b/state/test.go index 8e0f3520..a235e762 100644 --- a/state/test.go +++ b/state/test.go @@ -22,27 +22,27 @@ func Tempfile(prefix string) (*os.File, string) { return file, file.Name() } -func RandAccount(randBalance bool, minBalance uint64) (*account.Account, *account.PrivAccount) { +func RandAccount(randBalance bool, minBalance int64) (*account.Account, *account.PrivAccount) { privAccount := account.GenPrivAccount() acc := &account.Account{ Address: privAccount.PubKey.Address(), PubKey: privAccount.PubKey, - Sequence: RandUint(), + Sequence: RandInt(), Balance: minBalance, } if randBalance { - acc.Balance += uint64(RandUint32()) + acc.Balance += int64(RandUint32()) } return acc, privAccount } -func RandValidator(randBonded bool, minBonded uint64) (*ValidatorInfo, *Validator, *PrivValidator) { +func RandValidator(randBonded bool, minBonded int64) (*ValidatorInfo, *Validator, *PrivValidator) { privVal := GenPrivValidator() _, tempFilePath := Tempfile("priv_validator_") privVal.SetFile(tempFilePath) bonded := minBonded if randBonded { - bonded += uint64(RandUint32()) + bonded += int64(RandUint32()) } valInfo := &ValidatorInfo{ Address: privVal.Address, @@ -66,7 +66,7 @@ func RandValidator(randBonded bool, minBonded uint64) (*ValidatorInfo, *Validato return valInfo, val, privVal } -func RandGenesisState(numAccounts int, randBalance bool, minBalance uint64, numValidators int, randBonded bool, minBonded uint64) (*State, []*account.PrivAccount, []*PrivValidator) { +func RandGenesisState(numAccounts int, randBalance bool, minBalance int64, numValidators int, randBonded bool, minBonded int64) (*State, []*account.PrivAccount, []*PrivValidator) { db := dbm.NewMemDB() accounts := make([]GenesisAccount, numAccounts) privAccounts := make([]*account.PrivAccount, numAccounts) diff --git a/state/tx_cache.go b/state/tx_cache.go index 428959bc..718d6178 100644 --- a/state/tx_cache.go +++ b/state/tx_cache.go @@ -68,7 +68,7 @@ func (cache *TxCache) CreateAccount(creator *vm.Account) *vm.Account { nonce := creator.Nonce creator.Nonce += 1 - addr := LeftPadWord256(NewContractAddress(creator.Address.Postfix(20), nonce)) + addr := LeftPadWord256(NewContractAddress(creator.Address.Postfix(20), int(nonce))) // Create account from address. account, removed := vmUnpack(cache.accounts[addr]) @@ -144,10 +144,10 @@ func (cache *TxCache) AddLog(log *vm.Log) { //----------------------------------------------------------------------------- // Convenience function to return address of new contract -func NewContractAddress(caller []byte, nonce uint64) []byte { +func NewContractAddress(caller []byte, nonce int) []byte { temp := make([]byte, 32+8) copy(temp, caller) - PutUint64BE(temp[32:], nonce) + PutInt64BE(temp[32:], int64(nonce)) return sha3.Sha3(temp)[:20] } @@ -157,7 +157,7 @@ func toVMAccount(acc *ac.Account) *vm.Account { Address: LeftPadWord256(acc.Address), Balance: acc.Balance, Code: acc.Code, // This is crazy. - Nonce: uint64(acc.Sequence), + Nonce: int64(acc.Sequence), StorageRoot: LeftPadWord256(acc.StorageRoot), Other: acc.PubKey, } @@ -180,7 +180,7 @@ func toStateAccount(acc *vm.Account) *ac.Account { PubKey: pubKey, Balance: acc.Balance, Code: acc.Code, - Sequence: uint(acc.Nonce), + Sequence: int(acc.Nonce), StorageRoot: storageRoot, } } diff --git a/state/validator.go b/state/validator.go index 28046d18..46483b59 100644 --- a/state/validator.go +++ b/state/validator.go @@ -15,11 +15,11 @@ type ValidatorInfo struct { Address []byte `json:"address"` PubKey account.PubKeyEd25519 `json:"pub_key"` UnbondTo []*types.TxOutput `json:"unbond_to"` - FirstBondHeight uint `json:"first_bond_height"` - FirstBondAmount uint64 `json:"first_bond_amount"` - DestroyedHeight uint `json:"destroyed_height"` // If destroyed - DestroyedAmount uint64 `json:"destroyed_amount"` // If destroyed - ReleasedHeight uint `json:"released_height"` // If released + FirstBondHeight int `json:"first_bond_height"` + FirstBondAmount int64 `json:"first_bond_amount"` + DestroyedHeight int `json:"destroyed_height"` // If destroyed + DestroyedAmount int64 `json:"destroyed_amount"` // If destroyed + ReleasedHeight int `json:"released_height"` // If released } func (valInfo *ValidatorInfo) Copy() *ValidatorInfo { @@ -48,10 +48,10 @@ var ValidatorInfoCodec = binary.Codec{ type Validator struct { Address []byte `json:"address"` PubKey account.PubKeyEd25519 `json:"pub_key"` - BondHeight uint `json:"bond_height"` - UnbondHeight uint `json:"unbond_height"` - LastCommitHeight uint `json:"last_commit_height"` - VotingPower uint64 `json:"voting_power"` + BondHeight int `json:"bond_height"` + UnbondHeight int `json:"unbond_height"` + LastCommitHeight int `json:"last_commit_height"` + VotingPower int64 `json:"voting_power"` Accum int64 `json:"accum"` } diff --git a/state/validator_set.go b/state/validator_set.go index af626daf..fad0413d 100644 --- a/state/validator_set.go +++ b/state/validator_set.go @@ -28,7 +28,7 @@ type ValidatorSet struct { // cached (unexported) proposer *Validator - totalVotingPower uint64 + totalVotingPower int64 } func NewValidatorSet(vals []*Validator) *ValidatorSet { @@ -43,7 +43,7 @@ func NewValidatorSet(vals []*Validator) *ValidatorSet { } // TODO: mind the overflow when times and votingPower shares too large. -func (valSet *ValidatorSet) IncrementAccum(times uint) { +func (valSet *ValidatorSet) IncrementAccum(times int) { // Add VotingPower * times to each validator and order into heap. validatorsHeap := NewHeap() for _, val := range valSet.Validators { @@ -52,7 +52,7 @@ func (valSet *ValidatorSet) IncrementAccum(times uint) { } // Decrement the validator with most accum, times times. - for i := uint(0); i < times; i++ { + for i := 0; i < times; i++ { mostest := validatorsHeap.Peek().(*Validator) if i == times-1 { valSet.proposer = mostest @@ -82,27 +82,27 @@ func (valSet *ValidatorSet) HasAddress(address []byte) bool { return idx != len(valSet.Validators) && bytes.Compare(valSet.Validators[idx].Address, address) == 0 } -func (valSet *ValidatorSet) GetByAddress(address []byte) (index uint, val *Validator) { +func (valSet *ValidatorSet) GetByAddress(address []byte) (index int, val *Validator) { idx := sort.Search(len(valSet.Validators), func(i int) bool { return bytes.Compare(address, valSet.Validators[i].Address) <= 0 }) if idx != len(valSet.Validators) && bytes.Compare(valSet.Validators[idx].Address, address) == 0 { - return uint(idx), valSet.Validators[idx].Copy() + return idx, valSet.Validators[idx].Copy() } else { return 0, nil } } -func (valSet *ValidatorSet) GetByIndex(index uint) (address []byte, val *Validator) { +func (valSet *ValidatorSet) GetByIndex(index int) (address []byte, val *Validator) { val = valSet.Validators[index] return val.Address, val.Copy() } -func (valSet *ValidatorSet) Size() uint { - return uint(len(valSet.Validators)) +func (valSet *ValidatorSet) Size() int { + return len(valSet.Validators) } -func (valSet *ValidatorSet) TotalVotingPower() uint64 { +func (valSet *ValidatorSet) TotalVotingPower() int64 { if valSet.totalVotingPower == 0 { for _, val := range valSet.Validators { valSet.totalVotingPower += val.VotingPower @@ -190,9 +190,9 @@ func (valSet *ValidatorSet) Remove(address []byte) (val *Validator, removed bool } } -func (valSet *ValidatorSet) Iterate(fn func(index uint, val *Validator) bool) { +func (valSet *ValidatorSet) Iterate(fn func(index int, val *Validator) bool) { for i, val := range valSet.Validators { - stop := fn(uint(i), val.Copy()) + stop := fn(i, val.Copy()) if stop { break } @@ -201,15 +201,15 @@ func (valSet *ValidatorSet) Iterate(fn func(index uint, val *Validator) bool) { // Verify that +2/3 of the set had signed the given signBytes func (valSet *ValidatorSet) VerifyValidation(chainID string, - hash []byte, parts types.PartSetHeader, height uint, v *types.Validation) error { - if valSet.Size() != uint(len(v.Precommits)) { + hash []byte, parts types.PartSetHeader, height int, v *types.Validation) error { + if valSet.Size() != len(v.Precommits) { return fmt.Errorf("Invalid validation -- wrong set size: %v vs %v", valSet.Size(), len(v.Precommits)) } if height != v.Height() { return fmt.Errorf("Invalid validation -- wrong height: %v vs %v", height, v.Height()) } - talliedVotingPower := uint64(0) + talliedVotingPower := int64(0) round := v.Round() for idx, precommit := range v.Precommits { @@ -226,7 +226,7 @@ func (valSet *ValidatorSet) VerifyValidation(chainID string, if precommit.Type != types.VoteTypePrecommit { return fmt.Errorf("Invalid validation -- not precommit @ index %v", idx) } - _, val := valSet.GetByIndex(uint(idx)) + _, val := valSet.GetByIndex(idx) // Validate signature precommitSignBytes := account.SignBytes(chainID, precommit) if !val.PubKey.VerifyBytes(precommitSignBytes, precommit.Signature) { @@ -256,7 +256,7 @@ func (valSet *ValidatorSet) String() string { func (valSet *ValidatorSet) StringIndented(indent string) string { valStrings := []string{} - valSet.Iterate(func(index uint, val *Validator) bool { + valSet.Iterate(func(index int, val *Validator) bool { valStrings = append(valStrings, val.String()) return false }) @@ -294,9 +294,9 @@ func (vs ValidatorsByAddress) Swap(i, j int) { //------------------------------------- // Use with Heap for sorting validators by accum -type accumComparable uint64 +type accumComparable int64 // We want to find the validator with the greatest accum. func (ac accumComparable) Less(o interface{}) bool { - return uint64(ac) < uint64(o.(accumComparable)) + return int64(ac) < int64(o.(accumComparable)) } diff --git a/state/validator_set_test.go b/state/validator_set_test.go index be108acf..dc74d484 100644 --- a/state/validator_set_test.go +++ b/state/validator_set_test.go @@ -13,9 +13,9 @@ func randValidator_() *Validator { return &Validator{ Address: RandBytes(20), PubKey: account.PubKeyEd25519(RandBytes(64)), - BondHeight: uint(RandUint32()), - VotingPower: RandUint64(), - Accum: int64(RandUint64()), + BondHeight: RandInt(), + VotingPower: RandInt64(), + Accum: RandInt64(), } } diff --git a/types/block.go b/types/block.go index b149c44e..2fdf9f1d 100644 --- a/types/block.go +++ b/types/block.go @@ -21,7 +21,7 @@ type Block struct { } // Basic validation that doesn't involve state data. -func (b *Block) ValidateBasic(chainID string, lastBlockHeight uint, lastBlockHash []byte, +func (b *Block) ValidateBasic(chainID string, lastBlockHeight int, lastBlockHash []byte, lastBlockParts PartSetHeader, lastBlockTime time.Time) error { if b.ChainID != chainID { return errors.New("Wrong Block.Header.ChainID") @@ -29,7 +29,7 @@ func (b *Block) ValidateBasic(chainID string, lastBlockHeight uint, lastBlockHas if b.Height != lastBlockHeight+1 { return errors.New("Wrong Block.Header.Height") } - if b.NumTxs != uint(len(b.Data.Txs)) { + if b.NumTxs != len(b.Data.Txs) { return errors.New("Wrong Block.Header.NumTxs") } if !bytes.Equal(b.LastBlockHash, lastBlockHash) { @@ -123,10 +123,10 @@ func (b *Block) StringShort() string { type Header struct { ChainID string `json:"chain_id"` - Height uint `json:"height"` + Height int `json:"height"` Time time.Time `json:"time"` - Fees uint64 `json:"fees"` - NumTxs uint `json:"num_txs"` + Fees int64 `json:"fees"` + NumTxs int `json:"num_txs"` LastBlockHash []byte `json:"last_block_hash"` LastBlockParts PartSetHeader `json:"last_block_parts"` StateHash []byte `json:"state_hash"` @@ -188,14 +188,14 @@ type Validation struct { bitArray *BitArray } -func (v *Validation) Height() uint { +func (v *Validation) Height() int { if len(v.Precommits) == 0 { return 0 } return v.Precommits[0].Height } -func (v *Validation) Round() uint { +func (v *Validation) Round() int { if len(v.Precommits) == 0 { return 0 } @@ -259,9 +259,9 @@ func (v *Validation) StringIndented(indent string) string { func (v *Validation) BitArray() *BitArray { if v.bitArray == nil { - v.bitArray = NewBitArray(uint(len(v.Precommits))) + v.bitArray = NewBitArray(len(v.Precommits)) for i, precommit := range v.Precommits { - v.bitArray.SetIndex(uint(i), precommit != nil) + v.bitArray.SetIndex(i, precommit != nil) } } return v.bitArray diff --git a/types/events.go b/types/events.go index e51d9e28..31cedf12 100644 --- a/types/events.go +++ b/types/events.go @@ -55,8 +55,8 @@ type CallData struct { Caller []byte `json:"caller"` Callee []byte `json:"callee"` Data []byte `json:"data"` - Value uint64 `json:"value"` - Gas uint64 `json:"gas"` + Value int64 `json:"value"` + Gas int64 `json:"gas"` } type EventMsgCall struct { diff --git a/types/names.go b/types/names.go index bebecb47..9ce4cc6f 100644 --- a/types/names.go +++ b/types/names.go @@ -5,12 +5,12 @@ import ( ) var ( - MinNameRegistrationPeriod uint64 = 5 + MinNameRegistrationPeriod int = 5 // cost for storing a name for a block is // CostPerBlock*CostPerByte*(len(data) + 32) - NameCostPerByte uint64 = 1 - NameCostPerBlock uint64 = 1 + NameCostPerByte int64 = 1 + NameCostPerBlock int64 = 1 MaxNameLength = 32 MaxDataLength = 1 << 16 @@ -31,15 +31,15 @@ func validateNameRegEntryData(data string) bool { } // base cost is "effective" number of bytes -func BaseEntryCost(name, data string) uint64 { - return uint64(len(data) + 32) +func BaseEntryCost(name, data string) int64 { + return int64(len(data) + 32) } type NameRegEntry struct { Name string `json:"name"` // registered name for the entry Owner []byte `json:"owner"` // address that created the entry Data string `json:"data"` // data to store under this name - Expires uint64 `json:"expires"` // block at which this entry expires + Expires int `json:"expires"` // block at which this entry expires } func (entry *NameRegEntry) Copy() *NameRegEntry { diff --git a/types/part_set.go b/types/part_set.go index 8c5de3be..8d4ba320 100644 --- a/types/part_set.go +++ b/types/part_set.go @@ -61,7 +61,7 @@ func (part *Part) StringIndented(indent string) string { //------------------------------------- type PartSetHeader struct { - Total uint `json:"total"` + Total int `json:"total"` Hash []byte `json:"hash"` } @@ -84,13 +84,13 @@ func (psh PartSetHeader) WriteSignBytes(w io.Writer, n *int64, err *error) { //------------------------------------- type PartSet struct { - total uint + total int hash []byte mtx sync.Mutex parts []*Part partsBitArray *BitArray - count uint + count int } // Returns an immutable, full PartSet from the data bytes. @@ -100,14 +100,14 @@ func NewPartSetFromData(data []byte) *PartSet { total := (len(data) + partSize - 1) / partSize parts := make([]*Part, total) parts_ := make([]merkle.Hashable, total) - partsBitArray := NewBitArray(uint(total)) + partsBitArray := NewBitArray(total) for i := 0; i < total; i++ { part := &Part{ Bytes: data[i*partSize : MinInt(len(data), (i+1)*partSize)], } parts[i] = part parts_[i] = part - partsBitArray.SetIndex(uint(i), true) + partsBitArray.SetIndex(i, true) } // Compute merkle proofs proofs := merkle.SimpleProofsFromHashables(parts_) @@ -115,11 +115,11 @@ func NewPartSetFromData(data []byte) *PartSet { parts[i].Proof = *proofs[i] } return &PartSet{ - total: uint(total), + total: total, hash: proofs[0].RootHash, parts: parts, partsBitArray: partsBitArray, - count: uint(total), + count: total, } } @@ -129,7 +129,7 @@ func NewPartSetFromHeader(header PartSetHeader) *PartSet { total: header.Total, hash: header.Hash, parts: make([]*Part, header.Total), - partsBitArray: NewBitArray(uint(header.Total)), + partsBitArray: NewBitArray(header.Total), count: 0, } } @@ -173,14 +173,14 @@ func (ps *PartSet) HashesTo(hash []byte) bool { return bytes.Equal(ps.hash, hash) } -func (ps *PartSet) Count() uint { +func (ps *PartSet) Count() int { if ps == nil { return 0 } return ps.count } -func (ps *PartSet) Total() uint { +func (ps *PartSet) Total() int { if ps == nil { return 0 } @@ -208,12 +208,12 @@ func (ps *PartSet) AddPart(part *Part) (bool, error) { // Add part ps.parts[part.Proof.Index] = part - ps.partsBitArray.SetIndex(uint(part.Proof.Index), true) + ps.partsBitArray.SetIndex(part.Proof.Index, true) ps.count++ return true, nil } -func (ps *PartSet) GetPart(index uint) *Part { +func (ps *PartSet) GetPart(index int) *Part { ps.mtx.Lock() defer ps.mtx.Unlock() return ps.parts[index] diff --git a/types/part_set_test.go b/types/part_set_test.go index 88cf2d58..5d2d9142 100644 --- a/types/part_set_test.go +++ b/types/part_set_test.go @@ -27,7 +27,7 @@ func TestBasicPartSet(t *testing.T) { // Test adding parts to a new partSet. partSet2 := NewPartSetFromHeader(partSet.Header()) - for i := uint(0); i < partSet.Total(); i++ { + for i := 0; i < partSet.Total(); i++ { part := partSet.GetPart(i) //t.Logf("\n%v", part) added, err := partSet2.AddPart(part) diff --git a/types/tx.go b/types/tx.go index 46362413..690528bc 100644 --- a/types/tx.go +++ b/types/tx.go @@ -24,8 +24,8 @@ var ( ) type ErrTxInvalidSequence struct { - Got uint64 - Expected uint64 + Got int + Expected int } func (e ErrTxInvalidSequence) Error() string { @@ -79,8 +79,8 @@ var _ = binary.RegisterInterface( type TxInput struct { Address []byte `json:"address"` // Hash of the PubKey - Amount uint64 `json:"amount"` // Must not exceed account balance - Sequence uint `json:"sequence"` // Must be 1 greater than the last committed TxInput + Amount int64 `json:"amount"` // Must not exceed account balance + Sequence int `json:"sequence"` // Must be 1 greater than the last committed TxInput Signature account.Signature `json:"signature"` // Depends on the PubKey type and the whole Tx PubKey account.PubKey `json:"pub_key"` // Must not be nil, may be nil } @@ -107,7 +107,7 @@ func (txIn *TxInput) String() string { type TxOutput struct { Address []byte `json:"address"` // Hash of the PubKey - Amount uint64 `json:"amount"` // The sum of all outputs must not exceed the inputs. + Amount int64 `json:"amount"` // The sum of all outputs must not exceed the inputs. } func (txOut *TxOutput) ValidateBasic() error { @@ -163,8 +163,8 @@ func (tx *SendTx) String() string { type CallTx struct { Input *TxInput `json:"input"` Address []byte `json:"address"` - GasLimit uint64 `json:"gas_limit"` - Fee uint64 `json:"fee"` + GasLimit int64 `json:"gas_limit"` + Fee int64 `json:"fee"` Data []byte `json:"data"` } @@ -186,7 +186,7 @@ type NameTx struct { Input *TxInput `json:"input"` Name string `json:"name"` Data string `json:"data"` - Fee uint64 `json:"fee"` + Fee int64 `json:"fee"` } func (tx *NameTx) WriteSignBytes(chainID string, w io.Writer, n *int64, err *error) { @@ -220,7 +220,7 @@ func (tx *NameTx) ValidateStrings() error { return nil } -func (tx *NameTx) BaseEntryCost() uint64 { +func (tx *NameTx) BaseEntryCost() int64 { return BaseEntryCost(tx.Name, tx.Data) } @@ -266,7 +266,7 @@ func (tx *BondTx) String() string { type UnbondTx struct { Address []byte `json:"address"` - Height uint `json:"height"` + Height int `json:"height"` Signature account.SignatureEd25519 `json:"signature"` } @@ -283,7 +283,7 @@ func (tx *UnbondTx) String() string { type RebondTx struct { Address []byte `json:"address"` - Height uint `json:"height"` + Height int `json:"height"` Signature account.SignatureEd25519 `json:"signature"` } diff --git a/types/tx_utils.go b/types/tx_utils.go index a4ba02de..1a960b6a 100644 --- a/types/tx_utils.go +++ b/types/tx_utils.go @@ -19,7 +19,7 @@ func NewSendTx() *SendTx { } } -func (tx *SendTx) AddInput(st AccountGetter, pubkey account.PubKey, amt uint64) error { +func (tx *SendTx) AddInput(st AccountGetter, pubkey account.PubKey, amt int64) error { addr := pubkey.Address() acc := st.GetAccount(addr) if acc == nil { @@ -28,7 +28,7 @@ func (tx *SendTx) AddInput(st AccountGetter, pubkey account.PubKey, amt uint64) return tx.AddInputWithNonce(pubkey, amt, acc.Sequence+1) } -func (tx *SendTx) AddInputWithNonce(pubkey account.PubKey, amt uint64, nonce uint) error { +func (tx *SendTx) AddInputWithNonce(pubkey account.PubKey, amt int64, nonce int) error { addr := pubkey.Address() tx.Inputs = append(tx.Inputs, &TxInput{ Address: addr, @@ -40,7 +40,7 @@ func (tx *SendTx) AddInputWithNonce(pubkey account.PubKey, amt uint64, nonce uin return nil } -func (tx *SendTx) AddOutput(addr []byte, amt uint64) error { +func (tx *SendTx) AddOutput(addr []byte, amt int64) error { tx.Outputs = append(tx.Outputs, &TxOutput{ Address: addr, Amount: amt, @@ -60,7 +60,7 @@ func (tx *SendTx) SignInput(chainID string, i int, privAccount *account.PrivAcco //---------------------------------------------------------------------------- // CallTx interface for creating tx -func NewCallTx(st AccountGetter, from account.PubKey, to, data []byte, amt, gasLimit, fee uint64) (*CallTx, error) { +func NewCallTx(st AccountGetter, from account.PubKey, to, data []byte, amt, gasLimit, fee int64) (*CallTx, error) { addr := from.Address() acc := st.GetAccount(addr) if acc == nil { @@ -71,7 +71,7 @@ func NewCallTx(st AccountGetter, from account.PubKey, to, data []byte, amt, gasL return NewCallTxWithNonce(from, to, data, amt, gasLimit, fee, nonce), nil } -func NewCallTxWithNonce(from account.PubKey, to, data []byte, amt, gasLimit, fee uint64, nonce uint) *CallTx { +func NewCallTxWithNonce(from account.PubKey, to, data []byte, amt, gasLimit, fee int64, nonce int) *CallTx { addr := from.Address() input := &TxInput{ Address: addr, @@ -98,7 +98,7 @@ func (tx *CallTx) Sign(chainID string, privAccount *account.PrivAccount) { //---------------------------------------------------------------------------- // NameTx interface for creating tx -func NewNameTx(st AccountGetter, from account.PubKey, name, data string, amt, fee uint64) (*NameTx, error) { +func NewNameTx(st AccountGetter, from account.PubKey, name, data string, amt, fee int64) (*NameTx, error) { addr := from.Address() acc := st.GetAccount(addr) if acc == nil { @@ -109,7 +109,7 @@ func NewNameTx(st AccountGetter, from account.PubKey, name, data string, amt, fe return NewNameTxWithNonce(from, name, data, amt, fee, nonce), nil } -func NewNameTxWithNonce(from account.PubKey, name, data string, amt, fee uint64, nonce uint) *NameTx { +func NewNameTxWithNonce(from account.PubKey, name, data string, amt, fee int64, nonce int) *NameTx { addr := from.Address() input := &TxInput{ Address: addr, @@ -147,7 +147,7 @@ func NewBondTx(pubkey account.PubKey) (*BondTx, error) { }, nil } -func (tx *BondTx) AddInput(st AccountGetter, pubkey account.PubKey, amt uint64) error { +func (tx *BondTx) AddInput(st AccountGetter, pubkey account.PubKey, amt int64) error { addr := pubkey.Address() acc := st.GetAccount(addr) if acc == nil { @@ -156,7 +156,7 @@ func (tx *BondTx) AddInput(st AccountGetter, pubkey account.PubKey, amt uint64) return tx.AddInputWithNonce(pubkey, amt, acc.Sequence+1) } -func (tx *BondTx) AddInputWithNonce(pubkey account.PubKey, amt uint64, nonce uint) error { +func (tx *BondTx) AddInputWithNonce(pubkey account.PubKey, amt int64, nonce int) error { addr := pubkey.Address() tx.Inputs = append(tx.Inputs, &TxInput{ Address: addr, @@ -168,7 +168,7 @@ func (tx *BondTx) AddInputWithNonce(pubkey account.PubKey, amt uint64, nonce uin return nil } -func (tx *BondTx) AddOutput(addr []byte, amt uint64) error { +func (tx *BondTx) AddOutput(addr []byte, amt int64) error { tx.UnbondTo = append(tx.UnbondTo, &TxOutput{ Address: addr, Amount: amt, @@ -198,7 +198,7 @@ func (tx *BondTx) SignInput(chainID string, i int, privAccount *account.PrivAcco //---------------------------------------------------------------------- // UnbondTx interface for creating tx -func NewUnbondTx(addr []byte, height uint) *UnbondTx { +func NewUnbondTx(addr []byte, height int) *UnbondTx { return &UnbondTx{ Address: addr, Height: height, @@ -212,7 +212,7 @@ func (tx *UnbondTx) Sign(chainID string, privAccount *account.PrivAccount) { //---------------------------------------------------------------------- // RebondTx interface for creating tx -func NewRebondTx(addr []byte, height uint) *RebondTx { +func NewRebondTx(addr []byte, height int) *RebondTx { return &RebondTx{ Address: addr, Height: height, diff --git a/types/vote.go b/types/vote.go index 2e931c23..30205d88 100644 --- a/types/vote.go +++ b/types/vote.go @@ -28,8 +28,8 @@ func (err *ErrVoteConflictingSignature) Error() string { // Represents a prevote, precommit, or commit vote from validators for consensus. type Vote struct { - Height uint `json:"height"` - Round uint `json:"round"` + Height int `json:"height"` + Round int `json:"round"` Type byte `json:"type"` BlockHash []byte `json:"block_hash"` // empty if vote is nil. BlockParts PartSetHeader `json:"block_parts"` // zero if vote is nil. diff --git a/vm/gas.go b/vm/gas.go index ebe5573a..dac978f1 100644 --- a/vm/gas.go +++ b/vm/gas.go @@ -1,17 +1,17 @@ package vm const ( - GasSha3 uint64 = 1 - GasGetAccount uint64 = 1 - GasStorageUpdate uint64 = 1 + GasSha3 int64 = 1 + GasGetAccount int64 = 1 + GasStorageUpdate int64 = 1 - GasStackOp uint64 = 1 + GasStackOp int64 = 1 - GasEcRecover uint64 = 1 - GasSha256Word uint64 = 1 - GasSha256Base uint64 = 1 - GasRipemd160Word uint64 = 1 - GasRipemd160Base uint64 = 1 - GasIdentityWord uint64 = 1 - GasIdentityBase uint64 = 1 + GasEcRecover int64 = 1 + GasSha256Word int64 = 1 + GasSha256Base int64 = 1 + GasRipemd160Word int64 = 1 + GasRipemd160Base int64 = 1 + GasIdentityWord int64 = 1 + GasIdentityBase int64 = 1 ) diff --git a/vm/native.go b/vm/native.go index 8aff146d..b7339bc3 100644 --- a/vm/native.go +++ b/vm/native.go @@ -11,17 +11,17 @@ import ( var nativeContracts = make(map[Word256]NativeContract) func init() { - nativeContracts[Uint64ToWord256(1)] = ecrecoverFunc - nativeContracts[Uint64ToWord256(2)] = sha256Func - nativeContracts[Uint64ToWord256(3)] = ripemd160Func - nativeContracts[Uint64ToWord256(4)] = identityFunc + nativeContracts[Int64ToWord256(1)] = ecrecoverFunc + nativeContracts[Int64ToWord256(2)] = sha256Func + nativeContracts[Int64ToWord256(3)] = ripemd160Func + nativeContracts[Int64ToWord256(4)] = identityFunc } //----------------------------------------------------------------------------- -type NativeContract func(input []byte, gas *uint64) (output []byte, err error) +type NativeContract func(input []byte, gas *int64) (output []byte, err error) -func ecrecoverFunc(input []byte, gas *uint64) (output []byte, err error) { +func ecrecoverFunc(input []byte, gas *int64) (output []byte, err error) { // Deduct gas gasRequired := GasEcRecover if *gas < gasRequired { @@ -42,9 +42,9 @@ func ecrecoverFunc(input []byte, gas *uint64) (output []byte, err error) { return LeftPadBytes(hashed, 32), nil } -func sha256Func(input []byte, gas *uint64) (output []byte, err error) { +func sha256Func(input []byte, gas *int64) (output []byte, err error) { // Deduct gas - gasRequired := uint64((len(input)+31)/32)*GasSha256Word + GasSha256Base + gasRequired := int64((len(input)+31)/32)*GasSha256Word + GasSha256Base if *gas < gasRequired { return nil, ErrInsufficientGas } else { @@ -59,9 +59,9 @@ func sha256Func(input []byte, gas *uint64) (output []byte, err error) { return hasher.Sum(nil), nil } -func ripemd160Func(input []byte, gas *uint64) (output []byte, err error) { +func ripemd160Func(input []byte, gas *int64) (output []byte, err error) { // Deduct gas - gasRequired := uint64((len(input)+31)/32)*GasRipemd160Word + GasRipemd160Base + gasRequired := int64((len(input)+31)/32)*GasRipemd160Word + GasRipemd160Base if *gas < gasRequired { return nil, ErrInsufficientGas } else { @@ -76,9 +76,9 @@ func ripemd160Func(input []byte, gas *uint64) (output []byte, err error) { return LeftPadBytes(hasher.Sum(nil), 32), nil } -func identityFunc(input []byte, gas *uint64) (output []byte, err error) { +func identityFunc(input []byte, gas *int64) (output []byte, err error) { // Deduct gas - gasRequired := uint64((len(input)+31)/32)*GasIdentityWord + GasIdentityBase + gasRequired := int64((len(input)+31)/32)*GasIdentityWord + GasIdentityBase if *gas < gasRequired { return nil, ErrInsufficientGas } else { diff --git a/vm/stack.go b/vm/stack.go index 500ff4d1..12bc1b77 100644 --- a/vm/stack.go +++ b/vm/stack.go @@ -10,11 +10,11 @@ type Stack struct { data []Word256 ptr int - gas *uint64 + gas *int64 err *error } -func NewStack(capacity int, gas *uint64, err *error) *Stack { +func NewStack(capacity int, gas *int64, err *error) *Stack { return &Stack{ data: make([]Word256, capacity), ptr: 0, @@ -23,7 +23,7 @@ func NewStack(capacity int, gas *uint64, err *error) *Stack { } } -func (st *Stack) useGas(gasToUse uint64) { +func (st *Stack) useGas(gasToUse int64) { if *st.gas > gasToUse { *st.gas -= gasToUse } else { @@ -54,8 +54,8 @@ func (st *Stack) PushBytes(bz []byte) { st.Push(LeftPadWord256(bz)) } -func (st *Stack) Push64(i uint64) { - st.Push(Uint64ToWord256(i)) +func (st *Stack) Push64(i int64) { + st.Push(Int64ToWord256(i)) } func (st *Stack) Pop() Word256 { @@ -72,9 +72,9 @@ func (st *Stack) PopBytes() []byte { return st.Pop().Bytes() } -func (st *Stack) Pop64() uint64 { +func (st *Stack) Pop64() int64 { d := st.Pop() - return Uint64FromWord256(d) + return Int64FromWord256(d) } func (st *Stack) Len() int { diff --git a/vm/test/fake_app_state.go b/vm/test/fake_app_state.go index 6f703d72..4880814b 100644 --- a/vm/test/fake_app_state.go +++ b/vm/test/fake_app_state.go @@ -80,6 +80,6 @@ func createAddress(creator *Account) Word256 { creator.Nonce += 1 temp := make([]byte, 32+8) copy(temp, creator.Address[:]) - PutUint64BE(temp[32:], nonce) + PutInt64BE(temp[32:], nonce) return LeftPadWord256(sha3.Sha3(temp)[:20]) } diff --git a/vm/test/vm_test.go b/vm/test/vm_test.go index e285a911..716643c4 100644 --- a/vm/test/vm_test.go +++ b/vm/test/vm_test.go @@ -43,13 +43,13 @@ func TestVM(t *testing.T) { // Create accounts account1 := &Account{ - Address: Uint64ToWord256(100), + Address: Int64ToWord256(100), } account2 := &Account{ - Address: Uint64ToWord256(101), + Address: Int64ToWord256(101), } - var gas uint64 = 100000 + var gas int64 = 100000 N := []byte{0x0f, 0x0f} // Loop N times code := []byte{0x60, 0x00, 0x60, 0x20, 0x52, 0x5B, byte(0x60 + len(N) - 1)} @@ -81,7 +81,7 @@ func TestSubcurrency(t *testing.T) { ourVm := NewVM(st, newParams(), Zero256, nil) - var gas uint64 = 1000 + var gas int64 = 1000 code_parts := []string{"620f42403355", "7c0100000000000000000000000000000000000000000000000000000000", "600035046315cf268481141561004657", @@ -105,13 +105,13 @@ func TestSendCall(t *testing.T) { // Create accounts account1 := &Account{ - Address: Uint64ToWord256(100), + Address: Int64ToWord256(100), } account2 := &Account{ - Address: Uint64ToWord256(101), + Address: Int64ToWord256(101), } account3 := &Account{ - Address: Uint64ToWord256(102), + Address: Int64ToWord256(102), } // account1 will call account2 which will trigger CALL opcode to account3 @@ -146,7 +146,7 @@ func TestSendCall(t *testing.T) { } // subscribes to an AccReceive, runs the vm, returns the exception -func runVMWaitEvents(t *testing.T, ourVm *VM, caller, callee *Account, subscribeAddr, contractCode []byte, gas uint64) string { +func runVMWaitEvents(t *testing.T, ourVm *VM, caller, callee *Account, subscribeAddr, contractCode []byte, gas int64) string { // we need to catch the event from the CALL to check for exceptions evsw := new(events.EventSwitch) evsw.Start() diff --git a/vm/types.go b/vm/types.go index d5777213..fe872c83 100644 --- a/vm/types.go +++ b/vm/types.go @@ -10,9 +10,9 @@ const ( type Account struct { Address Word256 - Balance uint64 + Balance int64 Code []byte - Nonce uint64 + Nonce int64 StorageRoot Word256 Other interface{} // For holding all other data. } @@ -26,7 +26,7 @@ type Log struct { Address Word256 Topics []Word256 Data []byte - Height uint64 + Height int64 } type AppState interface { @@ -46,8 +46,8 @@ type AppState interface { } type Params struct { - BlockHeight uint64 + BlockHeight int64 BlockHash Word256 BlockTime int64 - GasLimit uint64 + GasLimit int64 } diff --git a/vm/vm.go b/vm/vm.go index 6a814655..dc58f950 100644 --- a/vm/vm.go +++ b/vm/vm.go @@ -72,7 +72,7 @@ func (vm *VM) SetFireable(evc events.Fireable) { // value: To be transferred from caller to callee. Refunded upon error. // gas: Available gas. No refunds for gas. // code: May be nil, since the CALL opcode may be used to send value from contracts to accounts -func (vm *VM) Call(caller, callee *Account, code, input []byte, value uint64, gas *uint64) (output []byte, err error) { +func (vm *VM) Call(caller, callee *Account, code, input []byte, value int64, gas *int64) (output []byte, err error) { exception := new(string) defer func() { @@ -109,14 +109,14 @@ func (vm *VM) Call(caller, callee *Account, code, input []byte, value uint64, ga } // Just like Call() but does not transfer 'value' or modify the callDepth. -func (vm *VM) call(caller, callee *Account, code, input []byte, value uint64, gas *uint64) (output []byte, err error) { +func (vm *VM) call(caller, callee *Account, code, input []byte, value int64, gas *int64) (output []byte, err error) { dbg.Printf("(%d) (%X) %X (code=%d) gas: %v (d) %X\n", vm.callDepth, caller.Address[:4], callee.Address, len(callee.Code), *gas, input) var ( - pc uint64 = 0 - stack = NewStack(dataStackCapacity, gas, &err) - memory = make([]byte, memoryCapacity) - ok = false // convenience + pc int64 = 0 + stack = NewStack(dataStackCapacity, gas, &err) + memory = make([]byte, memoryCapacity) + ok = false // convenience ) for { @@ -388,7 +388,7 @@ func (vm *VM) call(caller, callee *Account, code, input []byte, value uint64, ga if idx < 32 { res = val[idx] } - stack.Push64(uint64(res)) + stack.Push64(int64(res)) dbg.Printf(" => 0x%X\n", res) case SHA3: // 0x20 @@ -444,7 +444,7 @@ func (vm *VM) call(caller, callee *Account, code, input []byte, value uint64, ga dbg.Printf(" => 0x%X\n", res) case CALLDATASIZE: // 0x36 - stack.Push64(uint64(len(input))) + stack.Push64(int64(len(input))) dbg.Printf(" => %d\n", len(input)) case CALLDATACOPY: // 0x37 @@ -463,7 +463,7 @@ func (vm *VM) call(caller, callee *Account, code, input []byte, value uint64, ga dbg.Printf(" => [%v, %v, %v] %X\n", memOff, inputOff, length, data) case CODESIZE: // 0x38 - l := uint64(len(code)) + l := int64(len(code)) stack.Push64(l) dbg.Printf(" => %d\n", l) @@ -496,7 +496,7 @@ func (vm *VM) call(caller, callee *Account, code, input []byte, value uint64, ga return nil, firstErr(err, ErrUnknownAddress) } code := acc.Code - l := uint64(len(code)) + l := int64(len(code)) stack.Push64(l) dbg.Printf(" => %d\n", l) @@ -534,11 +534,11 @@ func (vm *VM) call(caller, callee *Account, code, input []byte, value uint64, ga case TIMESTAMP: // 0x42 time := vm.params.BlockTime - stack.Push64(uint64(time)) + stack.Push64(int64(time)) dbg.Printf(" => 0x%X\n", time) case BLOCKHEIGHT: // 0x43 - number := uint64(vm.params.BlockHeight) + number := int64(vm.params.BlockHeight) stack.Push64(number) dbg.Printf(" => 0x%X\n", number) @@ -604,7 +604,7 @@ func (vm *VM) call(caller, callee *Account, code, input []byte, value uint64, ga stack.Push64(pc) case MSIZE: // 0x59 - stack.Push64(uint64(len(memory))) + stack.Push64(int64(len(memory))) case GAS: // 0x5A stack.Push64(*gas) @@ -615,7 +615,7 @@ func (vm *VM) call(caller, callee *Account, code, input []byte, value uint64, ga // Do nothing case PUSH1, PUSH2, PUSH3, PUSH4, PUSH5, PUSH6, PUSH7, PUSH8, PUSH9, PUSH10, PUSH11, PUSH12, PUSH13, PUSH14, PUSH15, PUSH16, PUSH17, PUSH18, PUSH19, PUSH20, PUSH21, PUSH22, PUSH23, PUSH24, PUSH25, PUSH26, PUSH27, PUSH28, PUSH29, PUSH30, PUSH31, PUSH32: - a := uint64(op - PUSH1 + 1) + a := int64(op - PUSH1 + 1) codeSegment, ok := subslice(code, pc+1, a) if !ok { return nil, firstErr(err, ErrCodeOutOfBounds) @@ -792,8 +792,8 @@ func (vm *VM) call(caller, callee *Account, code, input []byte, value uint64, ga } } -func subslice(data []byte, offset, length uint64) (ret []byte, ok bool) { - size := uint64(len(data)) +func subslice(data []byte, offset, length int64) (ret []byte, ok bool) { + size := int64(len(data)) if size < offset { return nil, false } else if size < offset+length { @@ -812,15 +812,15 @@ func rightMostBytes(data []byte, n int) []byte { return data[offset:] } -func codeGetOp(code []byte, n uint64) OpCode { - if uint64(len(code)) <= n { +func codeGetOp(code []byte, n int64) OpCode { + if int64(len(code)) <= n { return OpCode(0) // stop } else { return OpCode(code[n]) } } -func jump(code []byte, to uint64, pc *uint64) (err error) { +func jump(code []byte, to int64, pc *int64) (err error) { dest := codeGetOp(code, to) if dest != JUMPDEST { dbg.Printf(" ~> %v invalid jump dest %v\n", to, dest) @@ -839,7 +839,7 @@ func firstErr(errA, errB error) error { } } -func useGas(gas *uint64, gasToUse uint64) bool { +func useGas(gas *int64, gasToUse int64) bool { if *gas > gasToUse { *gas -= gasToUse return true @@ -848,7 +848,7 @@ func useGas(gas *uint64, gasToUse uint64) bool { } } -func transfer(from, to *Account, amount uint64) error { +func transfer(from, to *Account, amount int64) error { if from.Balance < amount { return ErrInsufficientBalance } else {