Skip to content

Commit

Permalink
Merge branch 'main' into hotfix/goVersion
Browse files Browse the repository at this point in the history
  • Loading branch information
kehiy authored Sep 12, 2023
2 parents aeeb7c3 + 8151298 commit 7c279b1
Show file tree
Hide file tree
Showing 14 changed files with 98 additions and 38 deletions.
26 changes: 13 additions & 13 deletions cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -261,21 +261,21 @@ func CreateNode(numValidators int, chain genesis.ChainType, workingDir string,
) {
// To make process faster, we update the password after creating the addresses
walletPath := PactusDefaultWalletPath(workingDir)
wallet, err := wallet.Create(walletPath, mnemonic, "", chain)
walletInstance, err := wallet.Create(walletPath, mnemonic, "", chain)
if err != nil {
return nil, nil, err
}

for i := 0; i < numValidators; i++ {
addr, err := wallet.DeriveNewAddress(fmt.Sprintf("Validator address %v", i+1))
addr, err := walletInstance.DeriveNewAddress(fmt.Sprintf("Validator address %v", i+1))
if err != nil {
return nil, nil, err
}
validatorAddrs = append(validatorAddrs, addr)
}

for i := 0; i < numValidators; i++ {
addr, err := wallet.DeriveNewAddress(fmt.Sprintf("Reward address %v", i+1))
addr, err := walletInstance.DeriveNewAddress(fmt.Sprintf("Reward address %v", i+1))
if err != nil {
return nil, nil, err
}
Expand All @@ -299,7 +299,7 @@ func CreateNode(numValidators int, chain genesis.ChainType, workingDir string,
return nil, nil, err
}
case genesis.Localnet:
err = makeLocalGenesis(*wallet).SaveToFile(genPath)
err = makeLocalGenesis(*walletInstance).SaveToFile(genPath)
if err != nil {
return nil, nil, err
}
Expand All @@ -310,12 +310,12 @@ func CreateNode(numValidators int, chain genesis.ChainType, workingDir string,
}
}

err = wallet.UpdatePassword("", walletPassword)
err = walletInstance.UpdatePassword("", walletPassword)
if err != nil {
return nil, nil, err
}

err = wallet.Save()
err = walletInstance.Save()
if err != nil {
return nil, nil, err
}
Expand Down Expand Up @@ -389,11 +389,11 @@ func StartNode(workingDir string, passwordFetcher func(*wallet.Wallet) (string,
}

walletPath := PactusDefaultWalletPath(workingDir)
wallet, err := wallet.Open(walletPath, true)
walletInstance, err := wallet.Open(walletPath, true)
if err != nil {
return nil, nil, err
}
addrLabels := wallet.AddressLabels()
addrLabels := walletInstance.AddressLabels()

// Create signers
if len(addrLabels) < conf.Node.NumValidators {
Expand All @@ -404,11 +404,11 @@ func StartNode(workingDir string, passwordFetcher func(*wallet.Wallet) (string,
validatorAddrs[i] = addrLabels[i].Address
}
signers := make([]crypto.Signer, conf.Node.NumValidators)
password, ok := passwordFetcher(wallet)
password, ok := passwordFetcher(walletInstance)
if !ok {
return nil, nil, fmt.Errorf("aborted")
}
prvKeys, err := wallet.PrivateKeys(password, validatorAddrs)
prvKeys, err := walletInstance.PrivateKeys(password, validatorAddrs)
if err != nil {
return nil, nil, err
}
Expand All @@ -431,17 +431,17 @@ func StartNode(workingDir string, passwordFetcher func(*wallet.Wallet) (string,
}
}

node, err := node.NewNode(gen, conf, signers, rewardAddrs)
nodeInstance, err := node.NewNode(gen, conf, signers, rewardAddrs)
if err != nil {
return nil, nil, err
}

err = node.Start()
err = nodeInstance.Start()
if err != nil {
return nil, nil, err
}

return node, wallet, nil
return nodeInstance, walletInstance, nil
}

// makeLocalGenesis makes genesis file for the local network.
Expand Down
8 changes: 4 additions & 4 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,10 +118,10 @@ func SaveTestnetConfig(path string, numValidators int) error {
conf.Network.Bootstrap.MaxThreshold = 8
conf.Network.EnableRelay = true
conf.Network.RelayAddrs = []string{
"/ip4/172.104.46.145/tcp/4002/p2p/12D3KooWNR79jqHVVNhNVrqnDbxbJJze4VjbEsBjZhz6mkvinHAN",
"/ip4/172.104.46.145/udp/4002/quic/p2p/12D3KooWNR79jqHVVNhNVrqnDbxbJJze4VjbEsBjZhz6mkvinHAN",
"/ip6/2400:8901::f03c:93ff:fe1c:c3ec/tcp/4002/p2p/12D3KooWNR79jqHVVNhNVrqnDbxbJJze4VjbEsBjZhz6mkvinHAN",
"/ip6/2400:8901::f03c:93ff:fe1c:c3ec/udp/4002/quic/p2p/12D3KooWNR79jqHVVNhNVrqnDbxbJJze4VjbEsBjZhz6mkvinHAN",
"/ip4/139.162.153.10/udp/4002/quic/p2p/12D3KooWNR79jqHVVNhNVrqnDbxbJJze4VjbEsBjZhz6mkvinHAN",
"/ip4/139.162.153.10/tcp/4002/p2p/12D3KooWNR79jqHVVNhNVrqnDbxbJJze4VjbEsBjZhz6mkvinHAN",
"/ip6/2a01:7e01::f03c:93ff:fed2:84c5/tcp/4002/p2p/12D3KooWNR79jqHVVNhNVrqnDbxbJJze4VjbEsBjZhz6mkvinHAN",
"/ip6/2a01:7e01::f03c:93ff:fed2:84c5/udp/4002/quic/p2p/12D3KooWNR79jqHVVNhNVrqnDbxbJJze4VjbEsBjZhz6mkvinHAN",
"/ip4/94.101.184.118/tcp/4002/p2p/12D3KooWCRHn8vjrKNBEQcut8uVCYX5q77RKidPaE6iMK31qEVHb",
"/ip4/94.101.184.118/udp/4002/quic/p2p/12D3KooWCRHn8vjrKNBEQcut8uVCYX5q77RKidPaE6iMK31qEVHb",
}
Expand Down
8 changes: 8 additions & 0 deletions genesis/genesis.go
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,14 @@ func (gen *Genesis) SaveToFile(file string) error {
return util.WriteFile(file, json)
}

func (gen *Genesis) TotalSupply() int64 {
totalSuppyly := int64(0)
for _, acc := range gen.data.Accounts {
totalSuppyly += acc.Balance
}
return totalSuppyly
}

func (gen *Genesis) ChainType() ChainType {
if gen.Hash() == TestnetGenesis().Hash() {
return Testnet
Expand Down
6 changes: 4 additions & 2 deletions genesis/genesis_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,12 @@ func TestGenesisTestNet(t *testing.T) {
assert.Equal(t, g.Accounts()[crypto.TreasuryAddress].Balance(), int64(21e15))

genTime, _ := time.Parse("2006-01-02", "2023-09-07")
expected, _ := hash.FromString("b7285501eee807780a8ab62e60b8248597b155260c118b5a76b586b00e9cfaa9")
assert.Equal(t, g.Hash(), expected)
assert.Equal(t, g.GenesisTime(), genTime)
assert.Equal(t, g.Params().BondInterval, uint32(120))
expected, _ := hash.FromString("7b105c84a220a1acd928befdd8af78b9c8b13e2297f6cc5b4b784baff28bd22f")
assert.Equal(t, g.Hash(), expected)
assert.Equal(t, g.ChainType(), genesis.Testnet)
assert.Equal(t, g.TotalSupply(), int64(42*1e15))
}

func TestCheckGenesisAccountAndValidator(t *testing.T) {
Expand Down
4 changes: 4 additions & 0 deletions genesis/testnet.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@
{
"address": "000000000000000000000000000000000000000000",
"balance": 21000000000000000
},
{
"address": "tpc1pc8uyt3w7napj704leypexr02ws6lx2ggfu9e2j",
"balance": 21000000000000000
}
],
"validators": [
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ require (
golang.org/x/exp v0.0.0-20230817173708-d852ddb80c63
google.golang.org/grpc v1.58.0
google.golang.org/protobuf v1.31.0
gopkg.in/natefinch/lumberjack.v2 v2.2.1
)

require (
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -672,6 +672,8 @@ gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EV
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw=
gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc=
gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
Expand Down
2 changes: 1 addition & 1 deletion state/execution_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,6 @@ func TestExecuteBlock(t *testing.T) {
// Check if fee is claimed
treasury := sb.Account(crypto.TreasuryAddress)
subsidy := td.state1.params.BlockReward
assert.Equal(t, treasury.Balance(), 21*1e14-(2*subsidy)) // Two blocks has committed yet
assert.Equal(t, treasury.Balance(), 21*1e15-(2*subsidy)) // Two blocks has committed yet
})
}
14 changes: 10 additions & 4 deletions state/state_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,6 @@ func setup(t *testing.T) *testData {
store3 := store.MockingStore(ts)
store4 := store.MockingStore(ts)

acc := account.NewAccount(0)
acc.AddToBalance(21 * 1e14) // 2,100,000,000,000,000
val1 := validator.NewValidator(pub1, 0)
val2 := validator.NewValidator(pub2, 1)
val3 := validator.NewValidator(pub3, 2)
Expand All @@ -74,7 +72,15 @@ func setup(t *testing.T) *testData {
params.CommitteeSize = 5
params.BondInterval = 10

accs := map[crypto.Address]*account.Account{crypto.TreasuryAddress: acc}
acc1 := account.NewAccount(0)
acc1.AddToBalance(21 * 1e15) // 21,000,000,000,000,000
acc2 := account.NewAccount(1)
acc2.AddToBalance(21 * 1e15) // 21,000,000,000,000,000

accs := map[crypto.Address]*account.Account{
crypto.TreasuryAddress: acc1,
ts.RandAddress(): acc2,
}
vals := []*validator.Validator{val1, val2, val3, val4}
gnDoc := genesis.MakeGenesis(genTime, accs, vals, params)

Expand Down Expand Up @@ -647,7 +653,7 @@ func TestLoadState(t *testing.T) {
assert.Equal(t, td.state1.committee.Committers(), st1Load.(*state).committee.Committers())
assert.Equal(t, td.state1.committee.TotalPower(), st1Load.(*state).committee.TotalPower())
assert.Equal(t, td.state1.TotalPower(), st1Load.(*state).TotalPower())
assert.Equal(t, td.state1.store.TotalAccounts(), int32(5))
assert.Equal(t, td.state1.store.TotalAccounts(), int32(6))

require.NoError(t, st1Load.CommitBlock(6, b6, c6))
require.NoError(t, td.state2.CommitBlock(6, b6, c6))
Expand Down
17 changes: 12 additions & 5 deletions tests/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,9 +113,16 @@ func TestMain(m *testing.M) {
fmt.Printf("Node %d created.\n", i+1)
}

acc := account.NewAccount(0)
acc.AddToBalance(21 * 1e14)
accs := map[crypto.Address]*account.Account{crypto.TreasuryAddress: acc}
acc1 := account.NewAccount(0)
acc1.AddToBalance(21 * 1e14)
key, _ := bls.KeyGen(ikm.Bytes(), nil)
acc2 := account.NewAccount(1)
acc2.AddToBalance(21 * 1e14)

accs := map[crypto.Address]*account.Account{
crypto.TreasuryAddress: acc1,
key.PublicKey().Address(): acc2,
}

vals := make([]*validator.Validator, 4)
vals[0] = validator.NewValidator(tSigners[tNodeIdx1][0].PublicKey().(*bls.PublicKey), 0)
Expand Down Expand Up @@ -196,8 +203,8 @@ func TestMain(m *testing.M) {
total += v.Stake()
return false
})
if total != int64(21*1e14) {
panic(fmt.Sprintf("Some coins missed: %v", total-21*1e14))
if total != tGenDoc.TotalSupply() {
panic(fmt.Sprintf("Some coins missed: %v", tGenDoc.TotalSupply()-total))
}

os.Exit(exitCode)
Expand Down
6 changes: 3 additions & 3 deletions types/tx/tx.go
Original file line number Diff line number Diff line change
Expand Up @@ -159,13 +159,13 @@ func (tx *Tx) BasicCheck() error {
Reason: fmt.Sprintf("invalid sequence: %d", tx.Sequence()),
}
}
// TODO: Define it globally ( 21*1e14 )?
if tx.Payload().Value() < 0 || tx.Payload().Value() > 21*1e14 {
// TODO: Define it globally ( 42*1e15 )?
if tx.Payload().Value() < 0 || tx.Payload().Value() > 42*1e15 {
return BasicCheckError{
Reason: fmt.Sprintf("invalid amount: %d", tx.Payload().Value()),
}
}
if tx.Fee() < 0 || tx.Fee() > 21*1e14 {
if tx.Fee() < 0 || tx.Fee() > 42*1e15 {
return BasicCheckError{
Reason: fmt.Sprintf("invalid fee: %d", tx.Fee()),
}
Expand Down
8 changes: 4 additions & 4 deletions types/tx/tx_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,11 +132,11 @@ func TestBasicCheck(t *testing.T) {

t.Run("Invalid amount", func(t *testing.T) {
trx := tx.NewTransferTx(ts.RandStamp(), ts.RandInt32NonZero(100),
ts.RandAddress(), ts.RandAddress(), 21*1e14+1, 1, "invalid amount")
ts.RandAddress(), ts.RandAddress(), (42*1e15)+1, 1, "invalid amount")

err := trx.BasicCheck()
assert.ErrorIs(t, err, tx.BasicCheckError{
Reason: "invalid amount: 2100000000000001",
Reason: "invalid amount: 42000000000000001",
})
})

Expand All @@ -152,11 +152,11 @@ func TestBasicCheck(t *testing.T) {

t.Run("Invalid fee", func(t *testing.T) {
trx := tx.NewTransferTx(ts.RandStamp(), ts.RandInt32NonZero(100),
ts.RandAddress(), ts.RandAddress(), 1, 21*1e14+1, "invalid fee")
ts.RandAddress(), ts.RandAddress(), 1, (42*1e15)+1, "invalid fee")

err := trx.BasicCheck()
assert.ErrorIs(t, err, tx.BasicCheckError{
Reason: "invalid fee: 2100000000000001",
Reason: "invalid fee: 42000000000000001",
})
})

Expand Down
5 changes: 5 additions & 0 deletions util/logger/config.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
package logger

const (
LogDirectory = "logs"
LogFilename = "pactus.log"
)

type Config struct {
Colorful bool `toml:"colorful"`
Levels map[string]string `toml:"levels"`
Expand Down
29 changes: 27 additions & 2 deletions util/logger/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@ package logger
import (
"encoding/hex"
"fmt"
"io"
"os"
"path/filepath"

"gopkg.in/natefinch/lumberjack.v2"

"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
Expand Down Expand Up @@ -89,14 +93,28 @@ func addFields(event *zerolog.Event, keyvals ...interface{}) *zerolog.Event {
}

func NewSubLogger(name string, obj fmt.Stringer) *SubLogger {
var writers []io.Writer
maxLogSize := 100

// console writer
writers = append(writers, zerolog.ConsoleWriter{Out: os.Stderr})
logFilename := filepath.Join("./", LogFilename)

fl := &lumberjack.Logger{
Filename: logFilename,
MaxSize: maxLogSize,
}
writers = append(writers, fl)

mw := io.MultiWriter(writers...)
sl := &SubLogger{
logger: zerolog.New(os.Stderr).With().Timestamp().Logger(),
logger: zerolog.New(mw).With().Timestamp().Logger(),
name: name,
obj: obj,
}

if getLoggersInst().config.Colorful {
sl.logger = sl.logger.Output(zerolog.ConsoleWriter{Out: os.Stderr})
sl.logger = sl.logger.Output(mw)
}

lvlStr := getLoggersInst().config.Levels[name]
Expand All @@ -109,6 +127,13 @@ func NewSubLogger(name string, obj fmt.Stringer) *SubLogger {
sl.logger.Level(lvl)
}

sl.logger.Info().
Bool("fileLogging", true).
Bool("jsonLogOutput", true).
Str("fileName", logFilename).
Int("maxSizeMB", maxLogSize).
Msg("logging configured")

getLoggersInst().subs[name] = sl
return sl
}
Expand Down

0 comments on commit 7c279b1

Please sign in to comment.