Skip to content

Commit

Permalink
Merge branch 'develop' into topic/hardfork-v4
Browse files Browse the repository at this point in the history
  • Loading branch information
kroggen committed Jul 9, 2024
2 parents 2b08d91 + 21555a7 commit 9ae6762
Show file tree
Hide file tree
Showing 20 changed files with 124 additions and 333 deletions.
59 changes: 59 additions & 0 deletions blacklist/blacklist.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package blacklist

import (
"github.com/aergoio/aergo/v2/types"
"github.com/aergoio/aergo/v2/internal/common"
"github.com/aergoio/aergo/v2/internal/enc/hex"
)

type Blacklist struct {
sourcelist []string // account address (b58 encoded like Am...) or id (32 bytes in hex = 64 bytes)
blocked map[string]bool // all above converted to account id (32 bytes)
}

var globalBlacklist *Blacklist

// Initialize sets up the blacklist with the given addresses.
// This function should be called only once at the start.
func Initialize(addresses []string) {
conf := &Blacklist{}
conf.sourcelist = make([]string, len(addresses))
copy(conf.sourcelist, addresses)
conf.blocked = make(map[string]bool)
for _, v := range addresses {
key, err := toKey(v)
if err == nil {
conf.blocked[key] = true
} else {
// Handle invalid address, log or take other actions as needed
}
}
globalBlacklist = conf
}

func Check(address string) bool {
if globalBlacklist == nil {
return false
}
key, err := toKey(address)
if err != nil {
return false
}
return globalBlacklist.blocked[key]
}

func toKey(address string) (string, error) {
var key []byte
var err error
if len(address) == 64 {
key, err = hex.Decode(address)
} else {
var addr []byte
addr, err = types.DecodeAddress(address)
if err != nil {
return "", err
}
key = common.Hasher(addr)
}
return string(key), err
}
2 changes: 2 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,8 @@ func (ctx *ServerContext) GetDefaultMempoolConfig() *MempoolConfig {
FadeoutPeriod: types.DefaultEvictPeriod,
VerifierNumber: runtime.NumCPU(),
DumpFilePath: ctx.ExpandPathEnv("$HOME/mempool.dump"),
BlockDeploy: false,
Blacklist: nil,
}
}

Expand Down
6 changes: 6 additions & 0 deletions config/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,8 @@ type MempoolConfig struct {
FadeoutPeriod int `mapstructure:"fadeoutperiod" description:"time period for evict transactions(in hour)"`
VerifierNumber int `mapstructure:"verifiers" description:"number of concurrent verifier"`
DumpFilePath string `mapstructure:"dumpfilepath" description:"file path for recording mempool at process termintation"`
BlockDeploy bool `mapstructure:"blockdeploy" description:"block the deployment of new contracts"`
Blacklist []string `mapstructure:"blacklist" description:"List of account addresses or ids to be blocked"`
}

// ConsensusConfig defines configurations for consensus service
Expand Down Expand Up @@ -258,6 +260,10 @@ enablefadeout = {{.Mempool.EnableFadeout}}
fadeoutperiod = {{.Mempool.FadeoutPeriod}}
verifiers = {{.Mempool.VerifierNumber}}
dumpfilepath = "{{.Mempool.DumpFilePath}}"
blockdeploy = {{.Mempool.BlockDeploy}}
blacklist = [{{range .Mempool.Blacklist}}
"{{.}}", {{end}}
]
[consensus]
enablebp = {{.Consensus.EnableBp}}
Expand Down
37 changes: 28 additions & 9 deletions contract/vm.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ import (
"github.com/aergoio/aergo/v2/state/statedb"
"github.com/aergoio/aergo/v2/types"
"github.com/aergoio/aergo/v2/types/dbkey"
"github.com/aergoio/aergo/v2/blacklist"
jsoniter "github.com/json-iterator/go"
)

Expand Down Expand Up @@ -292,6 +293,16 @@ func newExecutor(
}
ctx.callDepth++

if blacklist.Check(types.EncodeAddress(contractId)) {
ce := &executor{
code: contract,
ctx: ctx,
}
ce.err = fmt.Errorf("contract not available")
ctrLgr.Error().Err(ce.err).Str("contract", types.EncodeAddress(contractId)).Msg("blocked contract")
return ce
}

ce := &executor{
code: contract,
L: GetLState(),
Expand Down Expand Up @@ -817,11 +828,13 @@ func Call(
ce := newExecutor(bytecode, contractAddress, ctx, &ci, ctx.curContract.amount, false, false, contractState)
defer ce.close()

startTime := time.Now()
// execute the contract call
ce.call(callMaxInstLimit, nil)
vmExecTime := time.Now().Sub(startTime).Microseconds()
vmLogger.Trace().Int64("execµs", vmExecTime).Stringer("txHash", types.LogBase58(ce.ctx.txHash)).Msg("tx execute time in vm")
if ce.err == nil {
startTime := time.Now()
// execute the contract call
ce.call(callMaxInstLimit, nil)
vmExecTime := time.Now().Sub(startTime).Microseconds()
vmLogger.Trace().Int64("execµs", vmExecTime).Stringer("txHash", types.LogBase58(ce.ctx.txHash)).Msg("tx execute time in vm")
}

// check if there is an error
err = ce.err
Expand Down Expand Up @@ -992,8 +1005,10 @@ func Create(
ce := newExecutor(bytecode, contractAddress, ctx, &ci, ctx.curContract.amount, true, false, contractState)
defer ce.close()

// call the constructor
ce.call(callMaxInstLimit, nil)
if err == nil {
// call the constructor
ce.call(callMaxInstLimit, nil)
}

// check if the call failed
err = ce.err
Expand Down Expand Up @@ -1120,7 +1135,9 @@ func Query(contractAddress []byte, bs *state.BlockState, cdb ChainAccessor, cont
}
}()

ce.call(queryMaxInstLimit, nil)
if err == nil {
ce.call(queryMaxInstLimit, nil)
}

return []byte(ce.jsonRet), ce.err
}
Expand Down Expand Up @@ -1194,7 +1211,9 @@ func CheckFeeDelegation(contractAddress []byte, bs *state.BlockState, bi *types.
}
}()

ce.call(queryMaxInstLimit, nil)
if err == nil {
ce.call(queryMaxInstLimit, nil)
}

if ce.err != nil {
return ce.err
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@ require (
golang.org/x/text v0.13.0 // indirect
golang.org/x/tools v0.14.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20230822172742-b8732ec3820d // indirect
google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.3.0 // indirect
google.golang.org/grpc/examples v0.0.0-20230724170852-2aa261560586 // indirect
gopkg.in/yaml.v2 v2.3.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -1276,6 +1276,8 @@ google.golang.org/grpc v1.32.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM
google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc=
google.golang.org/grpc v1.59.0 h1:Z5Iec2pjwb+LEOqzpB2MR12/eKFhDPhuqW91O+4bwUk=
google.golang.org/grpc v1.59.0/go.mod h1:aUPDwccQo6OTjy7Hct4AfBPD1GptF4fyUjIkQ9YtF98=
google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.3.0 h1:rNBFJjBCOgVr9pWD7rs/knKL4FRTKgpZmsRfV214zcA=
google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.3.0/go.mod h1:Dk1tviKTvMCz5tvh7t+fh94dhmQVHuCt2OzJB3CTW9Y=
google.golang.org/grpc/examples v0.0.0-20230724170852-2aa261560586 h1:3cBl7oDZlRZ9VAnaA9QglQNOY+ZP2wZJyGpiz1uuAuU=
google.golang.org/grpc/examples v0.0.0-20230724170852-2aa261560586/go.mod h1:YYPcVQPFEuZQrEwqV6D//WM2s4HnWXtvFr/kII5NKbI=
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
Expand Down
13 changes: 13 additions & 0 deletions mempool/mempool.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import (
"github.com/aergoio/aergo/v2/state/statedb"
"github.com/aergoio/aergo/v2/types"
"github.com/aergoio/aergo/v2/types/message"
"github.com/aergoio/aergo/v2/blacklist"
)

const (
Expand Down Expand Up @@ -74,6 +75,7 @@ type MemPool struct {
acceptChainIdHash []byte
isPublic bool
whitelist *whitelistConf
blockDeploy bool
// followings are for test
testConfig bool
deadtx int
Expand Down Expand Up @@ -102,13 +104,17 @@ func NewMemPoolService(cfg *cfg.Config, cs *chain.ChainService) *MemPool {
status: initial,
verifier: nil,
quit: make(chan bool),
blockDeploy: cfg.Mempool.BlockDeploy,
}
actor.BaseComponent = component.NewBaseComponent(message.MemPoolSvc, actor, log.NewLogger("mempool"))
if cfg.Mempool.EnableFadeout == false {
evictPeriod = 0
} else if cfg.Mempool.FadeoutPeriod > 0 {
evictPeriod = time.Duration(cfg.Mempool.FadeoutPeriod) * time.Hour
}
if cfg.Mempool.Blacklist != nil {
blacklist.Initialize(cfg.Mempool.Blacklist)
}
return actor
}

Expand Down Expand Up @@ -607,13 +613,17 @@ func (mp *MemPool) nextBlockVersion() int32 {
}

// check tx sanity
// check if sender is on blacklist
// check if sender has enough balance
// check if recipient is valid name
// check tx account is lower than known value
func (mp *MemPool) validateTx(tx types.Transaction, account types.Address) error {
if !mp.whitelist.Check(types.EncodeAddress(account)) {
return types.ErrTxNotAllowedAccount
}
if blacklist.Check(types.EncodeAddress(account)) {
return types.ErrTxNotAllowedAccount
}
ns, err := mp.getAccountState(account)
if err != nil {
return err
Expand Down Expand Up @@ -657,6 +667,9 @@ func (mp *MemPool) validateTx(tx types.Transaction, account types.Address) error
if tx.GetBody().GetRecipient() != nil {
return types.ErrTxInvalidRecipient
}
if mp.blockDeploy {
return types.ErrTxInvalidType
}
case types.TxType_GOVERNANCE:
id := tx.GetBody().GetRecipient()
aergoState, err := mp.getAccountState(id)
Expand Down
78 changes: 0 additions & 78 deletions rpc/grpcserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -1067,84 +1067,6 @@ func (rpc *AergoRPCService) GetReceipt(ctx context.Context, in *types.SingleByte
return rsp.Receipt, rsp.Err
}

func (rpc *AergoRPCService) GetReceipts(ctx context.Context, in *types.ReceiptsParams) (*types.ReceiptsPaged, error) {
if err := rpc.checkAuth(ctx, ReadBlockChain); err != nil {
return nil, err
}

var result interface{}
var err error
if cap(in.Hashornumber) == 0 {
return nil, status.Errorf(codes.InvalidArgument, "Received no bytes")
}

if len(in.Hashornumber) == 32 {
result, err = rpc.hub.RequestFuture(message.ChainSvc, &message.GetReceipts{BlockHash: in.Hashornumber},
defaultActorTimeout, "rpc.(*AergoRPCService).GetReceipts#2").Result()
} else if len(in.Hashornumber) == 8 {
number := uint64(binary.LittleEndian.Uint64(in.Hashornumber))
result, err = rpc.hub.RequestFuture(message.ChainSvc, &message.GetReceiptsByNo{BlockNo: number},
defaultActorTimeout, "rpc.(*AergoRPCService).GetReceipts#1").Result()
} else {
return nil, status.Errorf(codes.InvalidArgument, "Invalid input. Should be a 32 byte hash or up to 8 byte number.")
}

if err != nil {
return nil, err
}

getPaging := func(data *types.Receipts, size uint32, offset uint32) *types.ReceiptsPaged {
allReceipts := data.Get()
total := uint32(len(allReceipts))

var fetchSize uint32
if size > uint32(1000) {
fetchSize = uint32(1000)
} else if size == uint32(0) {
fetchSize = 100
} else {
fetchSize = size
}

var receipts []*types.Receipt
if offset >= uint32(len(allReceipts)) {
receipts = []*types.Receipt{}
} else {
limit := offset + fetchSize
if limit > uint32(len(allReceipts)) {
limit = uint32(len(allReceipts))
}
receipts = allReceipts[offset:limit]
}

return &types.ReceiptsPaged{
Receipts: receipts,
BlockNo: data.GetBlockNo(),
Total: total,
Size: fetchSize,
Offset: offset,
}
}

switch result.(type) {
case message.GetReceiptsRsp:
rsp, ok := result.(message.GetReceiptsRsp)
if !ok {
return nil, status.Errorf(codes.Internal, "internal type (%v) error", reflect.TypeOf(result))
}
return getPaging(rsp.Receipts, in.Paging.Size, in.Paging.Offset), rsp.Err

case message.GetReceiptsByNoRsp:
rsp, ok := result.(message.GetReceiptsByNoRsp)
if !ok {
return nil, status.Errorf(codes.Internal, "internal type (%v) error", reflect.TypeOf(result))
}
return getPaging(rsp.Receipts, in.Paging.Size, in.Paging.Offset), rsp.Err
}

return nil, status.Errorf(codes.Internal, "unexpected result type %s, expected %s", reflect.TypeOf(result), "message.GetReceipts")
}

func (rpc *AergoRPCService) GetABI(ctx context.Context, in *types.SingleBytes) (*types.ABI, error) {
if err := rpc.checkAuth(ctx, ReadBlockChain); err != nil {
return nil, err
Expand Down
Loading

0 comments on commit 9ae6762

Please sign in to comment.