Remove unused code and add benchmark for consensus msg check (#3211)

pull/3217/head
Rongjian Lan 4 years ago committed by GitHub
parent a168517dfc
commit 8a08da67ca
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 23
      api/client/client.go
  2. 54
      api/client/service/client.go
  3. 1
      api/client/service/gen.sh
  4. 3
      api/client/service/proto/client.go
  5. 344
      api/client/service/proto/client.pb.go
  6. 35
      api/client/service/proto/client.proto
  7. 70
      api/client/service/server.go
  8. 60
      api/service/clientsupport/service.go
  9. 2
      cmd/harmony/main.go
  10. 2
      consensus/consensus.go
  11. 9
      consensus/consensus_service.go
  12. 21
      consensus/engine/consensus_engine.go
  13. 1
      consensus/leader.go
  14. 236
      contracts/Faucet.go
  15. 20
      contracts/Faucet.sol
  16. 5
      contracts/README.md
  17. 2
      core/evm.go
  18. 91
      core/genesis.go
  19. 19
      core/genesis_util_test.go
  20. 2
      hmy/backend.go
  21. 44
      internal/chain/engine.go
  22. 8
      internal/utils/utils.go
  23. 101
      node/contract.go
  24. 10
      node/node.go
  25. 2
      node/node_genesis.go
  26. 4
      node/node_handler.go
  27. 1
      node/node_newblock.go
  28. 20
      node/node_syncing.go
  29. 21
      node/node_utils.go
  30. 10
      node/p2p.go
  31. 11
      node/service_setup.go
  32. 9
      shard/shard_state.go
  33. 107
      test/chain/reward/main.go

@ -1,23 +0,0 @@
package client
import (
"github.com/harmony-one/harmony/core/types"
"github.com/harmony-one/harmony/p2p"
)
// Client represents a node (e.g. a wallet) which sends transactions and receives responses from the harmony network
type Client struct {
ShardID uint32 // ShardID
UpdateBlocks func([]*types.Block) // Closure function used to sync new block with the leader. Once the leader finishes the consensus on a new block, it will send it to the clients. Clients use this method to update their blockchain
// The p2p host used to send/receive p2p messages
host p2p.Host
}
// NewClient creates a new Client
func NewClient(host p2p.Host, shardID uint32) *Client {
client := Client{}
client.host = host
client.ShardID = shardID
return &client
}

@ -1,54 +0,0 @@
package client
import (
"context"
"fmt"
"time"
"github.com/ethereum/go-ethereum/common"
proto "github.com/harmony-one/harmony/api/client/service/proto"
"google.golang.org/grpc"
)
// Client is the client model for client service.
type Client struct {
clientServiceClient proto.ClientServiceClient
opts []grpc.DialOption
conn *grpc.ClientConn
}
// NewClient setups a Client given ip and port.
func NewClient(ip, port string) (*Client, error) {
client := Client{}
client.opts = append(client.opts, grpc.WithInsecure())
var err error
client.conn, err = grpc.Dial(fmt.Sprintf("%s:%s", ip, port), client.opts...)
if err != nil {
return nil, err
}
client.clientServiceClient = proto.NewClientServiceClient(client.conn)
return &client, nil
}
// Close closes the Client.
func (client *Client) Close() error {
return client.conn.Close()
}
// GetBalance gets account balance from the client service.
func (client *Client) GetBalance(address common.Address) (*proto.FetchAccountStateResponse, error) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
request := &proto.FetchAccountStateRequest{Address: address.Bytes()}
return client.clientServiceClient.FetchAccountState(ctx, request)
}
// GetFreeToken requests free token from the faucet contract.
func (client *Client) GetFreeToken(address common.Address) (*proto.GetFreeTokenResponse, error) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
request := &proto.GetFreeTokenRequest{Address: address.Bytes()}
return client.clientServiceClient.GetFreeToken(ctx, request)
}

@ -1 +0,0 @@
protoc -I proto/ proto/client.proto --go_out=plugins=grpc:proto

@ -1,3 +0,0 @@
package client
//go:generate protoc client.proto --go_out=plugins=grpc:.

@ -1,344 +0,0 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: client.proto
package client
import (
context "context"
fmt "fmt"
proto "github.com/golang/protobuf/proto"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
math "math"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package
// FetchAccountStateRequest is the request to fetch an account's balance and nonce.
type FetchAccountStateRequest struct {
// The account address
Address []byte `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *FetchAccountStateRequest) Reset() { *m = FetchAccountStateRequest{} }
func (m *FetchAccountStateRequest) String() string { return proto.CompactTextString(m) }
func (*FetchAccountStateRequest) ProtoMessage() {}
func (*FetchAccountStateRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_014de31d7ac8c57c, []int{0}
}
func (m *FetchAccountStateRequest) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_FetchAccountStateRequest.Unmarshal(m, b)
}
func (m *FetchAccountStateRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_FetchAccountStateRequest.Marshal(b, m, deterministic)
}
func (m *FetchAccountStateRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_FetchAccountStateRequest.Merge(m, src)
}
func (m *FetchAccountStateRequest) XXX_Size() int {
return xxx_messageInfo_FetchAccountStateRequest.Size(m)
}
func (m *FetchAccountStateRequest) XXX_DiscardUnknown() {
xxx_messageInfo_FetchAccountStateRequest.DiscardUnknown(m)
}
var xxx_messageInfo_FetchAccountStateRequest proto.InternalMessageInfo
func (m *FetchAccountStateRequest) GetAddress() []byte {
if m != nil {
return m.Address
}
return nil
}
// FetchAccountStateResponse is the response of FetchAccountStateRequest.
type FetchAccountStateResponse struct {
// The balance of the account (big.Int)
Balance []byte `protobuf:"bytes,1,opt,name=balance,proto3" json:"balance,omitempty"`
// The nonce of the account
Nonce uint64 `protobuf:"varint,2,opt,name=nonce,proto3" json:"nonce,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *FetchAccountStateResponse) Reset() { *m = FetchAccountStateResponse{} }
func (m *FetchAccountStateResponse) String() string { return proto.CompactTextString(m) }
func (*FetchAccountStateResponse) ProtoMessage() {}
func (*FetchAccountStateResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_014de31d7ac8c57c, []int{1}
}
func (m *FetchAccountStateResponse) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_FetchAccountStateResponse.Unmarshal(m, b)
}
func (m *FetchAccountStateResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_FetchAccountStateResponse.Marshal(b, m, deterministic)
}
func (m *FetchAccountStateResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_FetchAccountStateResponse.Merge(m, src)
}
func (m *FetchAccountStateResponse) XXX_Size() int {
return xxx_messageInfo_FetchAccountStateResponse.Size(m)
}
func (m *FetchAccountStateResponse) XXX_DiscardUnknown() {
xxx_messageInfo_FetchAccountStateResponse.DiscardUnknown(m)
}
var xxx_messageInfo_FetchAccountStateResponse proto.InternalMessageInfo
func (m *FetchAccountStateResponse) GetBalance() []byte {
if m != nil {
return m.Balance
}
return nil
}
func (m *FetchAccountStateResponse) GetNonce() uint64 {
if m != nil {
return m.Nonce
}
return 0
}
// GetFreeTokenRequest is the request to get free token from the faucet smart contract.
type GetFreeTokenRequest struct {
// The account address to receive the free token
Address []byte `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *GetFreeTokenRequest) Reset() { *m = GetFreeTokenRequest{} }
func (m *GetFreeTokenRequest) String() string { return proto.CompactTextString(m) }
func (*GetFreeTokenRequest) ProtoMessage() {}
func (*GetFreeTokenRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_014de31d7ac8c57c, []int{2}
}
func (m *GetFreeTokenRequest) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_GetFreeTokenRequest.Unmarshal(m, b)
}
func (m *GetFreeTokenRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_GetFreeTokenRequest.Marshal(b, m, deterministic)
}
func (m *GetFreeTokenRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_GetFreeTokenRequest.Merge(m, src)
}
func (m *GetFreeTokenRequest) XXX_Size() int {
return xxx_messageInfo_GetFreeTokenRequest.Size(m)
}
func (m *GetFreeTokenRequest) XXX_DiscardUnknown() {
xxx_messageInfo_GetFreeTokenRequest.DiscardUnknown(m)
}
var xxx_messageInfo_GetFreeTokenRequest proto.InternalMessageInfo
func (m *GetFreeTokenRequest) GetAddress() []byte {
if m != nil {
return m.Address
}
return nil
}
// GetFreeTokenResponse is the response of GetFreeTokenRequest.
type GetFreeTokenResponse struct {
// The transaction Id that requests free token from the faucet.
TxId []byte `protobuf:"bytes,1,opt,name=txId,proto3" json:"txId,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *GetFreeTokenResponse) Reset() { *m = GetFreeTokenResponse{} }
func (m *GetFreeTokenResponse) String() string { return proto.CompactTextString(m) }
func (*GetFreeTokenResponse) ProtoMessage() {}
func (*GetFreeTokenResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_014de31d7ac8c57c, []int{3}
}
func (m *GetFreeTokenResponse) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_GetFreeTokenResponse.Unmarshal(m, b)
}
func (m *GetFreeTokenResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_GetFreeTokenResponse.Marshal(b, m, deterministic)
}
func (m *GetFreeTokenResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_GetFreeTokenResponse.Merge(m, src)
}
func (m *GetFreeTokenResponse) XXX_Size() int {
return xxx_messageInfo_GetFreeTokenResponse.Size(m)
}
func (m *GetFreeTokenResponse) XXX_DiscardUnknown() {
xxx_messageInfo_GetFreeTokenResponse.DiscardUnknown(m)
}
var xxx_messageInfo_GetFreeTokenResponse proto.InternalMessageInfo
func (m *GetFreeTokenResponse) GetTxId() []byte {
if m != nil {
return m.TxId
}
return nil
}
func init() {
proto.RegisterType((*FetchAccountStateRequest)(nil), "client.FetchAccountStateRequest")
proto.RegisterType((*FetchAccountStateResponse)(nil), "client.FetchAccountStateResponse")
proto.RegisterType((*GetFreeTokenRequest)(nil), "client.GetFreeTokenRequest")
proto.RegisterType((*GetFreeTokenResponse)(nil), "client.GetFreeTokenResponse")
}
func init() {
proto.RegisterFile("client.proto", fileDescriptor_014de31d7ac8c57c)
}
var fileDescriptor_014de31d7ac8c57c = []byte{
// 229 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0x49, 0xce, 0xc9, 0x4c,
0xcd, 0x2b, 0xd1, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x83, 0xf0, 0x94, 0x4c, 0xb8, 0x24,
0xdc, 0x52, 0x4b, 0x92, 0x33, 0x1c, 0x93, 0x93, 0xf3, 0x4b, 0xf3, 0x4a, 0x82, 0x4b, 0x12, 0x4b,
0x52, 0x83, 0x52, 0x0b, 0x4b, 0x53, 0x8b, 0x4b, 0x84, 0x24, 0xb8, 0xd8, 0x13, 0x53, 0x52, 0x8a,
0x52, 0x8b, 0x8b, 0x25, 0x18, 0x15, 0x18, 0x35, 0x78, 0x82, 0x60, 0x5c, 0x25, 0x6f, 0x2e, 0x49,
0x2c, 0xba, 0x8a, 0x0b, 0xf2, 0xf3, 0x8a, 0x53, 0x41, 0xda, 0x92, 0x12, 0x73, 0x12, 0xf3, 0x92,
0x53, 0x61, 0xda, 0xa0, 0x5c, 0x21, 0x11, 0x2e, 0xd6, 0xbc, 0x7c, 0x90, 0x38, 0x93, 0x02, 0xa3,
0x06, 0x4b, 0x10, 0x84, 0xa3, 0xa4, 0xcf, 0x25, 0xec, 0x9e, 0x5a, 0xe2, 0x56, 0x94, 0x9a, 0x1a,
0x92, 0x9f, 0x9d, 0x9a, 0x47, 0xd8, 0x76, 0x2d, 0x2e, 0x11, 0x54, 0x0d, 0x50, 0x8b, 0x85, 0xb8,
0x58, 0x4a, 0x2a, 0x3c, 0x53, 0xa0, 0xca, 0xc1, 0x6c, 0xa3, 0x1d, 0x8c, 0x5c, 0xbc, 0xce, 0x60,
0xaf, 0x06, 0xa7, 0x16, 0x95, 0x65, 0x26, 0xa7, 0x0a, 0x45, 0x71, 0x09, 0x62, 0xb8, 0x5d, 0x48,
0x41, 0x0f, 0x1a, 0x3a, 0xb8, 0x02, 0x43, 0x4a, 0x11, 0x8f, 0x0a, 0x88, 0xfd, 0x4a, 0x0c, 0x42,
0xde, 0x5c, 0x3c, 0xc8, 0x2e, 0x13, 0x92, 0x86, 0x69, 0xc2, 0xe2, 0x41, 0x29, 0x19, 0xec, 0x92,
0x30, 0xc3, 0x92, 0xd8, 0xc0, 0x31, 0x65, 0x0c, 0x08, 0x00, 0x00, 0xff, 0xff, 0xc6, 0xd9, 0x35,
0x0c, 0xb9, 0x01, 0x00, 0x00,
}
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConnInterface
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion6
// ClientServiceClient is the client API for ClientService service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
type ClientServiceClient interface {
FetchAccountState(ctx context.Context, in *FetchAccountStateRequest, opts ...grpc.CallOption) (*FetchAccountStateResponse, error)
GetFreeToken(ctx context.Context, in *GetFreeTokenRequest, opts ...grpc.CallOption) (*GetFreeTokenResponse, error)
}
type clientServiceClient struct {
cc grpc.ClientConnInterface
}
func NewClientServiceClient(cc grpc.ClientConnInterface) ClientServiceClient {
return &clientServiceClient{cc}
}
func (c *clientServiceClient) FetchAccountState(ctx context.Context, in *FetchAccountStateRequest, opts ...grpc.CallOption) (*FetchAccountStateResponse, error) {
out := new(FetchAccountStateResponse)
err := c.cc.Invoke(ctx, "/client.ClientService/FetchAccountState", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *clientServiceClient) GetFreeToken(ctx context.Context, in *GetFreeTokenRequest, opts ...grpc.CallOption) (*GetFreeTokenResponse, error) {
out := new(GetFreeTokenResponse)
err := c.cc.Invoke(ctx, "/client.ClientService/GetFreeToken", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// ClientServiceServer is the server API for ClientService service.
type ClientServiceServer interface {
FetchAccountState(context.Context, *FetchAccountStateRequest) (*FetchAccountStateResponse, error)
GetFreeToken(context.Context, *GetFreeTokenRequest) (*GetFreeTokenResponse, error)
}
// UnimplementedClientServiceServer can be embedded to have forward compatible implementations.
type UnimplementedClientServiceServer struct {
}
func (*UnimplementedClientServiceServer) FetchAccountState(ctx context.Context, req *FetchAccountStateRequest) (*FetchAccountStateResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method FetchAccountState not implemented")
}
func (*UnimplementedClientServiceServer) GetFreeToken(ctx context.Context, req *GetFreeTokenRequest) (*GetFreeTokenResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method GetFreeToken not implemented")
}
func RegisterClientServiceServer(s *grpc.Server, srv ClientServiceServer) {
s.RegisterService(&_ClientService_serviceDesc, srv)
}
func _ClientService_FetchAccountState_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(FetchAccountStateRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ClientServiceServer).FetchAccountState(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/client.ClientService/FetchAccountState",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ClientServiceServer).FetchAccountState(ctx, req.(*FetchAccountStateRequest))
}
return interceptor(ctx, in, info, handler)
}
func _ClientService_GetFreeToken_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetFreeTokenRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ClientServiceServer).GetFreeToken(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/client.ClientService/GetFreeToken",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ClientServiceServer).GetFreeToken(ctx, req.(*GetFreeTokenRequest))
}
return interceptor(ctx, in, info, handler)
}
var _ClientService_serviceDesc = grpc.ServiceDesc{
ServiceName: "client.ClientService",
HandlerType: (*ClientServiceServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "FetchAccountState",
Handler: _ClientService_FetchAccountState_Handler,
},
{
MethodName: "GetFreeToken",
Handler: _ClientService_GetFreeToken_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "client.proto",
}

@ -1,35 +0,0 @@
syntax = "proto3";
package client;
// Client is the service used for any client-facing requests.
service ClientService {
rpc FetchAccountState(FetchAccountStateRequest) returns (FetchAccountStateResponse) {}
rpc GetFreeToken(GetFreeTokenRequest) returns (GetFreeTokenResponse) {}
}
// FetchAccountStateRequest is the request to fetch an account's balance and nonce.
message FetchAccountStateRequest {
// The account address
bytes address = 1;
}
// FetchAccountStateResponse is the response of FetchAccountStateRequest.
message FetchAccountStateResponse {
// The balance of the account (big.Int)
bytes balance = 1;
// The nonce of the account
uint64 nonce = 2;
}
// GetFreeTokenRequest is the request to get free token from the faucet smart contract.
message GetFreeTokenRequest {
// The account address to receive the free token
bytes address = 1;
}
// GetFreeTokenResponse is the response of GetFreeTokenRequest.
message GetFreeTokenResponse {
// The transaction Id that requests free token from the faucet.
bytes txId = 1;
}

@ -1,70 +0,0 @@
package client
import (
"context"
"log"
"net"
"github.com/ethereum/go-ethereum/common"
proto "github.com/harmony-one/harmony/api/client/service/proto"
"github.com/harmony-one/harmony/core/state"
"github.com/harmony-one/harmony/internal/utils"
"google.golang.org/grpc"
)
// Server is the Server struct for client service package.
type Server struct {
stateReader func() (*state.DB, error)
callFaucetContract func(common.Address) common.Hash
}
// FetchAccountState implements the FetchAccountState interface to return account state.
func (s *Server) FetchAccountState(ctx context.Context, request *proto.FetchAccountStateRequest) (*proto.FetchAccountStateResponse, error) {
var address common.Address
address.SetBytes(request.Address)
// log.Println("Returning FetchAccountStateResponse for address: ", address.Hex())
state, err := s.stateReader()
if err != nil {
return nil, err
}
return &proto.FetchAccountStateResponse{Balance: state.GetBalance(address).Bytes(), Nonce: state.GetNonce(address)}, nil
}
// GetFreeToken implements the GetFreeToken interface to request free token.
func (s *Server) GetFreeToken(ctx context.Context, request *proto.GetFreeTokenRequest) (*proto.GetFreeTokenResponse, error) {
var address common.Address
address.SetBytes(request.Address)
// log.Println("Returning GetFreeTokenResponse for address: ", address.Hex())
return &proto.GetFreeTokenResponse{TxId: s.callFaucetContract(address).Bytes()}, nil
}
// Start starts the Server on given ip and port.
func (s *Server) Start(ip, port string) (*grpc.Server, error) {
// TODO(minhdoan): Currently not using ip. Fix it later.
addr := net.JoinHostPort("", port)
lis, err := net.Listen("tcp4", addr)
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
var opts []grpc.ServerOption
grpcServer := grpc.NewServer(opts...)
proto.RegisterClientServiceServer(grpcServer, s)
go func() {
if err := grpcServer.Serve(lis); err != nil {
utils.Logger().Warn().Err(err).Msg("grpcServer.Serve() failed")
}
}()
return grpcServer, nil
}
// NewServer creates new Server which implements ClientServiceServer interface.
func NewServer(
stateReader func() (*state.DB, error),
callFaucetContract func(common.Address) common.Hash) *Server {
s := &Server{
stateReader: stateReader,
callFaucetContract: callFaucetContract,
}
return s
}

@ -1,60 +0,0 @@
package clientsupport
import (
"strconv"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/rpc"
clientService "github.com/harmony-one/harmony/api/client/service"
msg_pb "github.com/harmony-one/harmony/api/proto/message"
"github.com/harmony-one/harmony/core/state"
"google.golang.org/grpc"
)
const (
// ClientServicePortDiff is the positive port diff for client service
ClientServicePortDiff = 5555
)
// Service is the client support service.
type Service struct {
server *clientService.Server
grpcServer *grpc.Server
ip string
port string
messageChan chan *msg_pb.Message
}
// New returns new client support service.
func New(stateReader func() (*state.DB, error),
callFaucetContract func(common.Address) common.Hash,
ip, nodePort string) *Service {
port, _ := strconv.Atoi(nodePort)
return &Service{
server: clientService.NewServer(stateReader, callFaucetContract),
ip: ip,
port: strconv.Itoa(port + ClientServicePortDiff)}
}
// StartService starts client support service.
func (s *Service) StartService() {
s.grpcServer, _ = s.server.Start(s.ip, s.port)
}
// StopService stops client support service.
func (s *Service) StopService() {
s.grpcServer.Stop()
}
// SetMessageChan sets up message channel to service.
func (s *Service) SetMessageChan(messageChan chan *msg_pb.Message) {
s.messageChan = messageChan
}
// NotifyService notify service
func (s *Service) NotifyService(params map[string]interface{}) {}
// APIs for the services.
func (s *Service) APIs() []rpc.API {
return nil
}

@ -324,7 +324,6 @@ func readMultiBLSKeys(consensusMultiBLSPriKey *multibls.PrivateKeys) error {
if err != nil { if err != nil {
return err return err
} }
// TODO: assumes order between public/private key pairs
*consensusMultiBLSPriKey = append(*consensusMultiBLSPriKey, multibls.GetPrivateKeys(consensusPriKey)...) *consensusMultiBLSPriKey = append(*consensusMultiBLSPriKey, multibls.GetPrivateKeys(consensusPriKey)...)
} }
@ -421,7 +420,6 @@ func createGlobalConfig() (*nodeconfig.ConfigType, error) {
func setupConsensusAndNode(nodeConfig *nodeconfig.ConfigType) *node.Node { func setupConsensusAndNode(nodeConfig *nodeconfig.ConfigType) *node.Node {
// Consensus object. // Consensus object.
// TODO: consensus object shouldn't start here // TODO: consensus object shouldn't start here
// TODO(minhdoan): During refactoring, found out that the peers list is actually empty. Need to clean up the logic of consensus later.
decider := quorum.NewDecider(quorum.SuperMajorityVote, uint32(*shardID)) decider := quorum.NewDecider(quorum.SuperMajorityVote, uint32(*shardID))
currentConsensus, err := consensus.New( currentConsensus, err := consensus.New(

@ -172,8 +172,6 @@ func (consensus *Consensus) GetConsensusLeaderPrivateKey() (*bls.PrivateKeyWrapp
return consensus.GetLeaderPrivateKey(consensus.LeaderPubKey.Object) return consensus.GetLeaderPrivateKey(consensus.LeaderPubKey.Object)
} }
// TODO: put shardId into chain reader's chain config
// New create a new Consensus record // New create a new Consensus record
func New( func New(
host p2p.Host, shard uint32, leader p2p.Peer, multiBLSPriKey multibls.PrivateKeys, host p2p.Host, shard uint32, leader p2p.Peer, multiBLSPriKey multibls.PrivateKeys,

@ -117,7 +117,6 @@ func (consensus *Consensus) signMessage(message []byte, priKey *bls_core.SecretK
func (consensus *Consensus) signConsensusMessage(message *msg_pb.Message, func (consensus *Consensus) signConsensusMessage(message *msg_pb.Message,
priKey *bls_core.SecretKey) error { priKey *bls_core.SecretKey) error {
message.Signature = nil message.Signature = nil
// TODO: use custom serialization method rather than protobuf
marshaledMessage, err := protobuf.Marshal(message) marshaledMessage, err := protobuf.Marshal(message)
if err != nil { if err != nil {
return err return err
@ -192,15 +191,11 @@ func (consensus *Consensus) IsValidatorInCommittee(pubKey bls.SerializedPublicKe
return consensus.Decider.IndexOf(pubKey) != -1 return consensus.Decider.IndexOf(pubKey) != -1
} }
// IsValidatorInCommitteeBytes returns whether the given validator BLS address is part of my committee
func (consensus *Consensus) IsValidatorInCommitteeBytes(pubKey bls.SerializedPublicKey) bool {
return consensus.Decider.IndexOf(pubKey) != -1
}
// Verify the signature of the message are valid from the signer's public key. // Verify the signature of the message are valid from the signer's public key.
func verifyMessageSig(signerPubKey *bls_core.PublicKey, message *msg_pb.Message) error { func verifyMessageSig(signerPubKey *bls_core.PublicKey, message *msg_pb.Message) error {
signature := message.Signature signature := message.Signature
message.Signature = nil message.Signature = nil
// TODO(audit): do not marshal message again here.
messageBytes, err := protobuf.Marshal(message) messageBytes, err := protobuf.Marshal(message)
if err != nil { if err != nil {
return err return err
@ -224,7 +219,7 @@ func (consensus *Consensus) verifySenderKey(msg *msg_pb.Message) error {
senderKey := bls.SerializedPublicKey{} senderKey := bls.SerializedPublicKey{}
copy(senderKey[:], msg.GetConsensus().SenderPubkey[:]) copy(senderKey[:], msg.GetConsensus().SenderPubkey[:])
if !consensus.IsValidatorInCommitteeBytes(senderKey) { if !consensus.IsValidatorInCommittee(senderKey) {
return shard.ErrValidNotInCommittee return shard.ErrValidNotInCommittee
} }
return nil return nil

@ -70,10 +70,6 @@ type ChainReader interface {
// Engine is an algorithm agnostic consensus engine. // Engine is an algorithm agnostic consensus engine.
// Note this engine interface is still in process of being integrated with the BFT consensus. // Note this engine interface is still in process of being integrated with the BFT consensus.
type Engine interface { type Engine interface {
// Author retrieves the Harmony address of the account that validated the given
// block.
Author(header *block.Header) (common.Address, error)
// VerifyHeader checks whether a header conforms to the consensus rules of a // VerifyHeader checks whether a header conforms to the consensus rules of a
// given engine. Verifying the seal may be done optionally here, or explicitly // given engine. Verifying the seal may be done optionally here, or explicitly
// via the VerifySeal method. // via the VerifySeal method.
@ -104,10 +100,6 @@ type Engine interface {
// VerifyShardState verifies the shard state during epoch transition is valid // VerifyShardState verifies the shard state during epoch transition is valid
VerifyShardState(chain ChainReader, beacon ChainReader, header *block.Header) error VerifyShardState(chain ChainReader, beacon ChainReader, header *block.Header) error
// Prepare initializes the consensus fields of a block header according to the
// rules of a particular engine. The changes are executed inline.
Prepare(chain ChainReader, header *block.Header) error
// Beaconchain provides the handle for Beaconchain // Beaconchain provides the handle for Beaconchain
Beaconchain() ChainReader Beaconchain() ChainReader
@ -125,17 +117,4 @@ type Engine interface {
incxs []*types.CXReceiptsProof, stks staking.StakingTransactions, incxs []*types.CXReceiptsProof, stks staking.StakingTransactions,
doubleSigners slash.Records, doubleSigners slash.Records,
) (*types.Block, reward.Reader, error) ) (*types.Block, reward.Reader, error)
// Seal generates a new sealing request for the given input block and pushes
// the result into the given channel.
//
// Note, the method returns immediately and will send the result async. More
// than one result may also be returned depending on the consensus algorithm.
Seal(
chain ChainReader, block *types.Block,
results chan<- *types.Block, stop <-chan struct{},
) error
// SealHash returns the hash of a block prior to it being sealed.
SealHash(header *block.Header) common.Hash
} }

@ -38,7 +38,6 @@ func (consensus *Consensus) announce(block *types.Block) {
return return
} }
// TODO(audit): wrap bls private key with public key
networkMessage, err := consensus.construct(msg_pb.MessageType_ANNOUNCE, nil, key) networkMessage, err := consensus.construct(msg_pb.MessageType_ANNOUNCE, nil, key)
if err != nil { if err != nil {
consensus.getLogger().Err(err). consensus.getLogger().Err(err).

@ -1,236 +0,0 @@
// Code generated - DO NOT EDIT.
// This file is a generated binding and any manual changes will be lost.
package contracts
import (
"math/big"
"strings"
ethereum "github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/event"
)
// Reference imports to suppress errors if they are not otherwise used.
var (
_ = big.NewInt
_ = strings.NewReader
_ = ethereum.NotFound
_ = abi.U256
_ = bind.Bind
_ = common.Big1
_ = types.BloomLookup
_ = event.NewSubscription
)
// FaucetABI is the input ABI used to generate the binding from.
const FaucetABI = "[{\"constant\":false,\"inputs\":[{\"name\":\"requestor\",\"type\":\"address\"}],\"name\":\"request\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"money\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"}]"
// FaucetBin is the compiled bytecode used for deploying new contracts.
const FaucetBin = `0x608060405268056bc75e2d63100000600155600280546001600160a01b0319163317905561014d806100326000396000f3fe608060405234801561001057600080fd5b50600436106100365760003560e01c806327c78c421461003b5780634ddd108a14610063575b600080fd5b6100616004803603602081101561005157600080fd5b50356001600160a01b031661007d565b005b61006b61011c565b60408051918252519081900360200190f35b6002546001600160a01b0316331461009457600080fd5b600154303110156100a457600080fd5b6001600160a01b03811660009081526020819052604090205460ff16156100ca57600080fd5b6001600160a01b038116600081815260208190526040808220805460ff1916600190811790915554905181156108fc0292818181858888f19350505050158015610118573d6000803e3d6000fd5b5050565b30319056fea165627a7a72305820fff2e3fdb95fb4beeaf0ea0cf53af65742d33136d84f4511dccb95696c1d0c140029`
// DeployFaucet deploys a new Ethereum contract, binding an instance of Faucet to it.
func DeployFaucet(auth *bind.TransactOpts, backend bind.ContractBackend) (common.Address, *types.Transaction, *Faucet, error) {
parsed, err := abi.JSON(strings.NewReader(FaucetABI))
if err != nil {
return common.Address{}, nil, nil, err
}
address, tx, contract, err := bind.DeployContract(auth, parsed, common.FromHex(FaucetBin), backend)
if err != nil {
return common.Address{}, nil, nil, err
}
return address, tx, &Faucet{FaucetCaller: FaucetCaller{contract: contract}, FaucetTransactor: FaucetTransactor{contract: contract}, FaucetFilterer: FaucetFilterer{contract: contract}}, nil
}
// Faucet is an auto generated Go binding around an Ethereum contract.
type Faucet struct {
FaucetCaller // Read-only binding to the contract
FaucetTransactor // Write-only binding to the contract
FaucetFilterer // Log filterer for contract events
}
// FaucetCaller is an auto generated read-only Go binding around an Ethereum contract.
type FaucetCaller struct {
contract *bind.BoundContract // Generic contract wrapper for the low level calls
}
// FaucetTransactor is an auto generated write-only Go binding around an Ethereum contract.
type FaucetTransactor struct {
contract *bind.BoundContract // Generic contract wrapper for the low level calls
}
// FaucetFilterer is an auto generated log filtering Go binding around an Ethereum contract events.
type FaucetFilterer struct {
contract *bind.BoundContract // Generic contract wrapper for the low level calls
}
// FaucetSession is an auto generated Go binding around an Ethereum contract,
// with pre-set call and transact options.
type FaucetSession struct {
Contract *Faucet // Generic contract binding to set the session for
CallOpts bind.CallOpts // Call options to use throughout this session
TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session
}
// FaucetCallerSession is an auto generated read-only Go binding around an Ethereum contract,
// with pre-set call options.
type FaucetCallerSession struct {
Contract *FaucetCaller // Generic contract caller binding to set the session for
CallOpts bind.CallOpts // Call options to use throughout this session
}
// FaucetTransactorSession is an auto generated write-only Go binding around an Ethereum contract,
// with pre-set transact options.
type FaucetTransactorSession struct {
Contract *FaucetTransactor // Generic contract transactor binding to set the session for
TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session
}
// FaucetRaw is an auto generated low-level Go binding around an Ethereum contract.
type FaucetRaw struct {
Contract *Faucet // Generic contract binding to access the raw methods on
}
// FaucetCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract.
type FaucetCallerRaw struct {
Contract *FaucetCaller // Generic read-only contract binding to access the raw methods on
}
// FaucetTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract.
type FaucetTransactorRaw struct {
Contract *FaucetTransactor // Generic write-only contract binding to access the raw methods on
}
// NewFaucet creates a new instance of Faucet, bound to a specific deployed contract.
func NewFaucet(address common.Address, backend bind.ContractBackend) (*Faucet, error) {
contract, err := bindFaucet(address, backend, backend, backend)
if err != nil {
return nil, err
}
return &Faucet{FaucetCaller: FaucetCaller{contract: contract}, FaucetTransactor: FaucetTransactor{contract: contract}, FaucetFilterer: FaucetFilterer{contract: contract}}, nil
}
// NewFaucetCaller creates a new read-only instance of Faucet, bound to a specific deployed contract.
func NewFaucetCaller(address common.Address, caller bind.ContractCaller) (*FaucetCaller, error) {
contract, err := bindFaucet(address, caller, nil, nil)
if err != nil {
return nil, err
}
return &FaucetCaller{contract: contract}, nil
}
// NewFaucetTransactor creates a new write-only instance of Faucet, bound to a specific deployed contract.
func NewFaucetTransactor(address common.Address, transactor bind.ContractTransactor) (*FaucetTransactor, error) {
contract, err := bindFaucet(address, nil, transactor, nil)
if err != nil {
return nil, err
}
return &FaucetTransactor{contract: contract}, nil
}
// NewFaucetFilterer creates a new log filterer instance of Faucet, bound to a specific deployed contract.
func NewFaucetFilterer(address common.Address, filterer bind.ContractFilterer) (*FaucetFilterer, error) {
contract, err := bindFaucet(address, nil, nil, filterer)
if err != nil {
return nil, err
}
return &FaucetFilterer{contract: contract}, nil
}
// bindFaucet binds a generic wrapper to an already deployed contract.
func bindFaucet(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) {
parsed, err := abi.JSON(strings.NewReader(FaucetABI))
if err != nil {
return nil, err
}
return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil
}
// Call invokes the (constant) contract method with params as input values and
// sets the output to result. The result type might be a single field for simple
// returns, a slice of interfaces for anonymous returns and a struct for named
// returns.
func (_Faucet *FaucetRaw) Call(opts *bind.CallOpts, result interface{}, method string, params ...interface{}) error {
return _Faucet.Contract.FaucetCaller.contract.Call(opts, result, method, params...)
}
// Transfer initiates a plain transaction to move funds to the contract, calling
// its default method if one is available.
func (_Faucet *FaucetRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {
return _Faucet.Contract.FaucetTransactor.contract.Transfer(opts)
}
// Transact invokes the (paid) contract method with params as input values.
func (_Faucet *FaucetRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) {
return _Faucet.Contract.FaucetTransactor.contract.Transact(opts, method, params...)
}
// Call invokes the (constant) contract method with params as input values and
// sets the output to result. The result type might be a single field for simple
// returns, a slice of interfaces for anonymous returns and a struct for named
// returns.
func (_Faucet *FaucetCallerRaw) Call(opts *bind.CallOpts, result interface{}, method string, params ...interface{}) error {
return _Faucet.Contract.contract.Call(opts, result, method, params...)
}
// Transfer initiates a plain transaction to move funds to the contract, calling
// its default method if one is available.
func (_Faucet *FaucetTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {
return _Faucet.Contract.contract.Transfer(opts)
}
// Transact invokes the (paid) contract method with params as input values.
func (_Faucet *FaucetTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) {
return _Faucet.Contract.contract.Transact(opts, method, params...)
}
// Money is a free data retrieval call binding the contract method 0x4ddd108a.
//
// Solidity: function money() constant returns(uint256)
func (_Faucet *FaucetCaller) Money(opts *bind.CallOpts) (*big.Int, error) {
var (
ret0 = new(*big.Int)
)
out := ret0
err := _Faucet.contract.Call(opts, out, "money")
return *ret0, err
}
// Money is a free data retrieval call binding the contract method 0x4ddd108a.
//
// Solidity: function money() constant returns(uint256)
func (_Faucet *FaucetSession) Money() (*big.Int, error) {
return _Faucet.Contract.Money(&_Faucet.CallOpts)
}
// Money is a free data retrieval call binding the contract method 0x4ddd108a.
//
// Solidity: function money() constant returns(uint256)
func (_Faucet *FaucetCallerSession) Money() (*big.Int, error) {
return _Faucet.Contract.Money(&_Faucet.CallOpts)
}
// Request is a paid mutator transaction binding the contract method 0x27c78c42.
//
// Solidity: function request(address requestor) returns()
func (_Faucet *FaucetTransactor) Request(opts *bind.TransactOpts, requestor common.Address) (*types.Transaction, error) {
return _Faucet.contract.Transact(opts, "request", requestor)
}
// Request is a paid mutator transaction binding the contract method 0x27c78c42.
//
// Solidity: function request(address requestor) returns()
func (_Faucet *FaucetSession) Request(requestor common.Address) (*types.Transaction, error) {
return _Faucet.Contract.Request(&_Faucet.TransactOpts, requestor)
}
// Request is a paid mutator transaction binding the contract method 0x27c78c42.
//
// Solidity: function request(address requestor) returns()
func (_Faucet *FaucetTransactorSession) Request(requestor common.Address) (*types.Transaction, error) {
return _Faucet.Contract.Request(&_Faucet.TransactOpts, requestor)
}

@ -1,20 +0,0 @@
pragma solidity >=0.4.22;
contract Faucet {
mapping(address => bool) processed;
uint quota = 100 ether;
address owner;
constructor() public payable {
owner = msg.sender;
}
function request(address payable requestor) public {
require(msg.sender == owner);
require(quota <= address(this).balance);
require(!processed[requestor]);
processed[requestor] = true;
requestor.transfer(quota);
}
function money() public view returns(uint) {
return address(this).balance;
}
}

@ -1,5 +0,0 @@
The smart contract files in this folder contains protocol-level smart contracts that are critical to the overall operation of Harmony protocol:
- Faucet.sol is the smart contract to dispense free test tokens in our testnet.
Solc is needed to recompile the contracts into ABI and bytecode. Please follow https://solidity.readthedocs.io/en/v0.5.3/installing-solidity.html for the installation.

@ -51,7 +51,7 @@ func NewEVMContext(msg Message, header *block.Header, chain ChainContext, author
// If we don't have an explicit author (i.e. not mining), extract from the header // If we don't have an explicit author (i.e. not mining), extract from the header
var beneficiary common.Address var beneficiary common.Address
if author == nil { if author == nil {
beneficiary, _ = chain.Engine().Author(header) // Ignore error, we're past header validation beneficiary = common.Address{} // Ignore error, we're past header validation
} else { } else {
beneficiary = *author beneficiary = *author
} }

@ -149,63 +149,6 @@ func (e *GenesisMismatchError) Error() string {
return fmt.Sprintf("database already contains an incompatible genesis block (have %x, new %x)", e.Stored[:8], e.New[:8]) return fmt.Sprintf("database already contains an incompatible genesis block (have %x, new %x)", e.Stored[:8], e.New[:8])
} }
// SetupGenesisBlock writes or updates the genesis block in db.
// The block that will be used is:
//
// genesis == nil genesis != nil
// +------------------------------------------
// db has no genesis | main-net default | genesis
// db has genesis | from DB | genesis (if compatible)
//
// The stored chain configuration will be updated if it is compatible (i.e. does not
// specify a fork block below the local head block)
// The returned chain configuration is never nil.
func SetupGenesisBlock(
db ethdb.Database, genesis *Genesis,
) (*params.ChainConfig, common.Hash, error) {
if genesis != nil && genesis.Config == nil {
return params.AllProtocolChanges, common.Hash{}, errGenesisNoConfig
}
// Just commit the new block if there is no stored genesis block.
stored := rawdb.ReadCanonicalHash(db, 0)
if (stored == common.Hash{}) {
if genesis == nil {
utils.Logger().Info().Msg("Writing default main-net genesis block")
genesis = DefaultGenesisBlock()
} else {
utils.Logger().Info().Msg("Writing custom genesis block")
}
block, err := genesis.Commit(db)
return genesis.Config, block.Hash(), err
}
// Check whether the genesis block is already written.
if genesis != nil {
hash := genesis.ToBlock(nil).Hash()
if hash != stored {
return genesis.Config, hash, &GenesisMismatchError{stored, hash}
}
}
// Get the existing chain configuration.
newcfg := genesis.configOrDefault(stored)
storedcfg := rawdb.ReadChainConfig(db, stored)
if storedcfg == nil {
utils.Logger().Warn().Msg("Found genesis block without chain config")
rawdb.WriteChainConfig(db, stored, newcfg)
return newcfg, stored, nil
}
// Check config compatibility and write the config. Compatibility errors
// are returned to the caller unless we're already at block zero.
height := rawdb.ReadHeaderNumber(db, rawdb.ReadHeadHeaderHash(db))
if height == nil {
return newcfg, stored, fmt.Errorf("missing block number for head header hash")
}
rawdb.WriteChainConfig(db, stored, newcfg)
return newcfg, stored, nil
}
func (g *Genesis) configOrDefault(ghash common.Hash) *params.ChainConfig { func (g *Genesis) configOrDefault(ghash common.Hash) *params.ChainConfig {
switch { switch {
case g != nil: case g != nil:
@ -302,37 +245,3 @@ func (g *Genesis) MustCommit(db ethdb.Database) *types.Block {
} }
return block return block
} }
// GenesisBlockForTesting creates and writes a block in which addr has the given Nano balance.
func GenesisBlockForTesting(db ethdb.Database, addr common.Address, balance *big.Int) *types.Block {
g := Genesis{Alloc: GenesisAlloc{addr: {Balance: balance}}}
return g.MustCommit(db)
}
// DefaultGenesisBlock returns the Ethereum main net genesis block.
func DefaultGenesisBlock() *Genesis {
return &Genesis{
Config: params.MainnetChainConfig,
Factory: blockfactory.ForMainnet,
Nonce: 66,
ExtraData: hexutil.MustDecode("0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa"),
GasLimit: 5000,
Alloc: decodePrealloc("empty"),
}
}
func decodePrealloc(data string) GenesisAlloc {
var p []struct{ Addr, Balance *big.Int }
// Create empty allocation for now
// TODO: create genesis block with actual content
//if err := rlp.NewStream(strings.NewReader(data), 0).Decode(&p); err != nil {
// panic(err)
//}
_ = data
ga := make(GenesisAlloc, len(p))
for _, account := range p {
ga[common.BigToAddress(account.Addr)] = GenesisAccount{Balance: account.Balance}
}
return ga
}

@ -1,19 +0,0 @@
package core
import (
"strings"
"testing"
)
func TestEncodeGenesisConfig(t *testing.T) {
fileName := "genesis_block_test.json"
s := EncodeGenesisConfig(fileName)
genesisAcc := decodePrealloc(s)
for k := range genesisAcc {
key := strings.ToLower(k.Hex())
if key != "0xb7a2c103728b7305b5ae6e961c94ee99c9fe8e2b" && key != "0xb498bb0f520005b6216a4425b75aa9adc52d622b" {
t.Errorf("EncodeGenesisConfig incorrect")
}
}
}

@ -41,8 +41,6 @@ type NodeAPI interface {
AddPendingTransaction(newTx *types.Transaction) error AddPendingTransaction(newTx *types.Transaction) error
Blockchain() *core.BlockChain Blockchain() *core.BlockChain
Beaconchain() *core.BlockChain Beaconchain() *core.BlockChain
GetBalanceOfAddress(address common.Address) (*big.Int, error)
GetNonceOfAddress(address common.Address) uint64
GetTransactionsHistory(address, txType, order string) ([]common.Hash, error) GetTransactionsHistory(address, txType, order string) ([]common.Hash, error)
GetStakingTransactionsHistory(address, txType, order string) ([]common.Hash, error) GetStakingTransactionsHistory(address, txType, order string) ([]common.Hash, error)
GetTransactionsCount(address, txType string) (uint64, error) GetTransactionsCount(address, txType string) (uint64, error)

@ -6,7 +6,6 @@ import (
"sort" "sort"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/rlp"
"github.com/harmony-one/bls/ffi/go/bls" "github.com/harmony-one/bls/ffi/go/bls"
"github.com/harmony-one/harmony/block" "github.com/harmony-one/harmony/block"
"github.com/harmony-one/harmony/consensus/engine" "github.com/harmony-one/harmony/consensus/engine"
@ -23,7 +22,6 @@ import (
"github.com/harmony-one/harmony/staking/slash" "github.com/harmony-one/harmony/staking/slash"
staking "github.com/harmony-one/harmony/staking/types" staking "github.com/harmony-one/harmony/staking/types"
"github.com/pkg/errors" "github.com/pkg/errors"
"golang.org/x/crypto/sha3"
) )
type engineImpl struct { type engineImpl struct {
@ -42,48 +40,6 @@ func (e *engineImpl) SetBeaconchain(beaconchain engine.ChainReader) {
e.beacon = beaconchain e.beacon = beaconchain
} }
// SealHash returns the hash of a block prior to it being sealed.
func (e *engineImpl) SealHash(header *block.Header) (hash common.Hash) {
hasher := sha3.NewLegacyKeccak256()
// TODO: update with new fields
if err := rlp.Encode(hasher, []interface{}{
header.ParentHash(),
header.Coinbase(),
header.Root(),
header.TxHash(),
header.ReceiptHash(),
header.Bloom(),
header.Number(),
header.GasLimit(),
header.GasUsed(),
header.Time(),
header.Extra(),
}); err != nil {
utils.Logger().Warn().Err(err).Msg("rlp.Encode failed")
}
hasher.Sum(hash[:0])
return hash
}
// Seal is to seal final block.
func (e *engineImpl) Seal(chain engine.ChainReader, block *types.Block, results chan<- *types.Block, stop <-chan struct{}) error {
// TODO: implement final block sealing
return nil
}
// Author returns the author of the block header.
func (e *engineImpl) Author(header *block.Header) (common.Address, error) {
// TODO: implement this
return common.Address{}, nil
}
// Prepare is to prepare ...
// TODO(RJ): fix it.
func (e *engineImpl) Prepare(chain engine.ChainReader, header *block.Header) error {
// TODO: implement prepare method
return nil
}
// VerifyHeader checks whether a header conforms to the consensus rules of the bft engine. // VerifyHeader checks whether a header conforms to the consensus rules of the bft engine.
// Note that each block header contains the bls signature of the parent block // Note that each block header contains the bls signature of the parent block
func (e *engineImpl) VerifyHeader(chain engine.ChainReader, header *block.Header, seal bool) error { func (e *engineImpl) VerifyHeader(chain engine.ChainReader, header *block.Header, seal bool) error {

@ -67,14 +67,6 @@ func GetUniqueIDFromIPPort(ip, port string) uint32 {
return uint32(value) return uint32(value)
} }
// GetAddressFromBLSPubKey return the address object from bls pub key.
func GetAddressFromBLSPubKey(pubKey *bls_core.PublicKey) common.Address {
addr := common.Address{}
addrBytes := pubKey.GetAddress()
addr.SetBytes(addrBytes[:])
return addr
}
// GetAddressFromBLSPubKeyBytes return the address object from bls pub key. // GetAddressFromBLSPubKeyBytes return the address object from bls pub key.
func GetAddressFromBLSPubKeyBytes(pubKeyBytes []byte) common.Address { func GetAddressFromBLSPubKeyBytes(pubKeyBytes []byte) common.Address {
pubKey, err := bls.BytesToBLSPublicKey(pubKeyBytes[:]) pubKey, err := bls.BytesToBLSPublicKey(pubKeyBytes[:])

@ -1,101 +0,0 @@
package node
import (
"math/big"
"strings"
"sync/atomic"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto"
nodeconfig "github.com/harmony-one/harmony/internal/configs/node"
"github.com/harmony-one/harmony/internal/params"
"github.com/harmony-one/harmony/common/denominations"
"github.com/harmony-one/harmony/contracts"
"github.com/harmony-one/harmony/core/types"
common2 "github.com/harmony-one/harmony/internal/common"
"github.com/harmony-one/harmony/internal/utils"
)
// Constants related to smart contract.
const (
FaucetContractFund = 80000000
)
// GetNonceOfAddress returns nonce of an address.
func (node *Node) GetNonceOfAddress(address common.Address) uint64 {
state, err := node.Blockchain().State()
if err != nil {
utils.Logger().Error().Err(err).Msg("Failed to get chain state")
return 0
}
return state.GetNonce(address)
}
// GetBalanceOfAddress returns balance of an address.
func (node *Node) GetBalanceOfAddress(address common.Address) (*big.Int, error) {
state, err := node.Blockchain().State()
if err != nil {
utils.Logger().Error().Err(err).Msg("Failed to get chain state")
return nil, err
}
balance := big.NewInt(0)
balance.SetBytes(state.GetBalance(address).Bytes())
return balance, nil
}
// AddFaucetContractToPendingTransactions adds the faucet contract the genesis block.
func (node *Node) AddFaucetContractToPendingTransactions() {
// Add a contract deployment transactionv
priKey := node.ContractDeployerKey
dataEnc := common.FromHex(contracts.FaucetBin)
// Unsigned transaction to avoid the case of transaction address.
contractFunds := big.NewInt(FaucetContractFund)
contractFunds = contractFunds.Mul(contractFunds, big.NewInt(denominations.One))
mycontracttx, _ := types.SignTx(
types.NewContractCreation(uint64(0), node.Consensus.ShardID, contractFunds, params.TxGasContractCreation*10, nil, dataEnc),
types.HomesteadSigner{},
priKey)
node.ContractAddresses = append(node.ContractAddresses, crypto.CreateAddress(crypto.PubkeyToAddress(priKey.PublicKey), uint64(0)))
node.addPendingTransactions(types.Transactions{mycontracttx})
}
// CallFaucetContract invokes the faucet contract to give the walletAddress initial money
func (node *Node) CallFaucetContract(address common.Address) common.Hash {
if node.NodeConfig.GetNetworkType() == nodeconfig.Mainnet {
return common.Hash{}
}
// Temporary code to workaround explorer issue for searching new addresses (https://github.com/harmony-one/harmony/issues/503)
nonce := atomic.AddUint64(&node.ContractDeployerCurrentNonce, 1)
tx, _ := types.SignTx(types.NewTransaction(nonce-1, address, node.Consensus.ShardID, big.NewInt(0), params.TxGasContractCreation*10, nil, nil), types.HomesteadSigner{}, node.ContractDeployerKey)
utils.Logger().Info().Str("Address", common2.MustAddressToBech32(address)).Msg("Sending placeholder token to ")
node.addPendingTransactions(types.Transactions{tx})
// END Temporary code
nonce = atomic.AddUint64(&node.ContractDeployerCurrentNonce, 1)
return node.callGetFreeTokenWithNonce(address, nonce-1)
}
func (node *Node) callGetFreeTokenWithNonce(address common.Address, nonce uint64) common.Hash {
abi, err := abi.JSON(strings.NewReader(contracts.FaucetABI))
if err != nil {
utils.Logger().Error().Err(err).Msg("Failed to generate faucet contract's ABI")
return common.Hash{}
}
bytesData, err := abi.Pack("request", address)
if err != nil {
utils.Logger().Error().Err(err).Msg("Failed to generate ABI function bytes data")
return common.Hash{}
}
if len(node.ContractAddresses) == 0 {
utils.Logger().Error().Err(err).Msg("Failed to find the contract address")
return common.Hash{}
}
tx, _ := types.SignTx(types.NewTransaction(nonce, node.ContractAddresses[0], node.Consensus.ShardID, big.NewInt(0), params.TxGasContractCreation*10, nil, bytesData), types.HomesteadSigner{}, node.ContractDeployerKey)
utils.Logger().Info().Str("Address", common2.MustAddressToBech32(address)).Msg("Sending Free Token to ")
node.addPendingTransactions(types.Transactions{tx})
return tx.Hash()
}

@ -15,7 +15,6 @@ import (
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/harmony-one/abool" "github.com/harmony-one/abool"
bls_core "github.com/harmony-one/bls/ffi/go/bls" bls_core "github.com/harmony-one/bls/ffi/go/bls"
"github.com/harmony-one/harmony/api/client"
msg_pb "github.com/harmony-one/harmony/api/proto/message" msg_pb "github.com/harmony-one/harmony/api/proto/message"
proto_node "github.com/harmony-one/harmony/api/proto/node" proto_node "github.com/harmony-one/harmony/api/proto/node"
"github.com/harmony-one/harmony/api/service" "github.com/harmony-one/harmony/api/service"
@ -83,7 +82,6 @@ type Node struct {
pendingCXMutex sync.Mutex pendingCXMutex sync.Mutex
// Shard databases // Shard databases
shardChains shardchain.Collection shardChains shardchain.Collection
Client *client.Client // The presence of a client object means this node will also act as a client
SelfPeer p2p.Peer SelfPeer p2p.Peer
// TODO: Neighbors should store only neighbor nodes in the same shard // TODO: Neighbors should store only neighbor nodes in the same shard
Neighbors sync.Map // All the neighbor nodes, key is the sha256 of Peer IP/Port, value is the p2p.Peer Neighbors sync.Map // All the neighbor nodes, key is the sha256 of Peer IP/Port, value is the p2p.Peer
@ -479,14 +477,6 @@ func New(
// the sequence number is the next block number to be added in consensus protocol, which is // the sequence number is the next block number to be added in consensus protocol, which is
// always one more than current chain header block // always one more than current chain header block
node.Consensus.SetBlockNum(blockchain.CurrentBlock().NumberU64() + 1) node.Consensus.SetBlockNum(blockchain.CurrentBlock().NumberU64() + 1)
// Add Faucet contract to all shards, so that on testnet, we can demo wallet in explorer
if networkType != nodeconfig.Mainnet {
if node.isFirstTime {
// Setup one time smart contracts
node.AddFaucetContractToPendingTransactions()
}
}
} }
utils.Logger().Info(). utils.Logger().Info().

@ -24,8 +24,6 @@ import (
const ( const (
// GenesisONEToken is the initial total number of ONE in the genesis block for mainnet. // GenesisONEToken is the initial total number of ONE in the genesis block for mainnet.
GenesisONEToken = 12600000000 GenesisONEToken = 12600000000
// TestAccountNumber is the number of test accounts for testnet/devnet/
TestAccountNumber = 100
// ContractDeployerInitFund is the initial fund for the contract deployer account in testnet/devnet. // ContractDeployerInitFund is the initial fund for the contract deployer account in testnet/devnet.
ContractDeployerInitFund = 10000000000 ContractDeployerInitFund = 10000000000
// InitFreeFund is the initial fund for permissioned accounts for testnet/devnet/ // InitFreeFund is the initial fund for permissioned accounts for testnet/devnet/

@ -136,10 +136,6 @@ func (node *Node) HandleMessage(content []byte, sender libp2p_peer.ID) {
} }
} }
} }
if node.Client != nil && node.Client.UpdateBlocks != nil && blocks != nil {
utils.Logger().Info().Msg("Block being handled by client")
node.Client.UpdateBlocks(blocks)
}
} }
case case
proto_node.SlashCandidate, proto_node.SlashCandidate,

@ -23,7 +23,6 @@ const (
// WaitForConsensusReadyV2 listen for the readiness signal from consensus and generate new block for consensus. // WaitForConsensusReadyV2 listen for the readiness signal from consensus and generate new block for consensus.
// only leader will receive the ready signal // only leader will receive the ready signal
// TODO: clean pending transactions for validators; or validators not prepare pending transactions
func (node *Node) WaitForConsensusReadyV2(readySignal chan struct{}, stopChan chan struct{}, stoppedChan chan struct{}) { func (node *Node) WaitForConsensusReadyV2(readySignal chan struct{}, stopChan chan struct{}, stoppedChan chan struct{}) {
go func() { go func() {
// Setup stoppedChan // Setup stoppedChan

@ -2,6 +2,7 @@ package node
import ( import (
"fmt" "fmt"
"math/rand"
"net" "net"
"sync" "sync"
"time" "time"
@ -23,11 +24,24 @@ import (
// Constants related to doing syncing. // Constants related to doing syncing.
const ( const (
lastMileThreshold = 4 SyncFrequency = 60
inSyncThreshold = 1 // unit in number of block
SyncFrequency = 60
) )
var letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
func init() {
rand.Seed(time.Now().UnixNano())
}
// GenerateRandomString generates a random string with given length
func GenerateRandomString(n int) string {
b := make([]rune, n)
for i := range b {
b[i] = letterRunes[rand.Intn(len(letterRunes))]
}
return string(b)
}
// getNeighborPeers is a helper function to return list of peers // getNeighborPeers is a helper function to return list of peers
// based on different neightbor map // based on different neightbor map
func getNeighborPeers(neighbor *sync.Map) []p2p.Peer { func getNeighborPeers(neighbor *sync.Map) []p2p.Peer {

@ -1,21 +0,0 @@
package node
import (
"math/rand"
"time"
)
var letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
func init() {
rand.Seed(time.Now().UnixNano())
}
// GenerateRandomString generates a random string with given length
func GenerateRandomString(n int) string {
b := make([]rune, n)
for i := range b {
b[i] = letterRunes[rand.Intn(len(letterRunes))]
}
return string(b)
}

@ -1,10 +0,0 @@
package node
import (
"github.com/harmony-one/harmony/p2p"
)
// GetHost returns the p2p host
func (node *Node) GetHost() p2p.Host {
return node.host
}

@ -6,7 +6,6 @@ import (
msg_pb "github.com/harmony-one/harmony/api/proto/message" msg_pb "github.com/harmony-one/harmony/api/proto/message"
"github.com/harmony-one/harmony/api/service" "github.com/harmony-one/harmony/api/service"
"github.com/harmony-one/harmony/api/service/blockproposal" "github.com/harmony-one/harmony/api/service/blockproposal"
"github.com/harmony-one/harmony/api/service/clientsupport"
"github.com/harmony-one/harmony/api/service/consensus" "github.com/harmony-one/harmony/api/service/consensus"
"github.com/harmony-one/harmony/api/service/explorer" "github.com/harmony-one/harmony/api/service/explorer"
"github.com/harmony-one/harmony/api/service/networkinfo" "github.com/harmony-one/harmony/api/service/networkinfo"
@ -33,16 +32,6 @@ func (node *Node) setupForValidator() {
service.BlockProposal, service.BlockProposal,
blockproposal.New(node.Consensus.ReadySignal, node.WaitForConsensusReadyV2), blockproposal.New(node.Consensus.ReadySignal, node.WaitForConsensusReadyV2),
) )
if node.NodeConfig.GetNetworkType() != nodeconfig.Mainnet {
// Register client support service.
node.serviceManager.RegisterService(
service.ClientSupport,
clientsupport.New(
node.Blockchain().State, node.CallFaucetContract, node.SelfPeer.IP, node.SelfPeer.Port,
),
)
}
} }
func (node *Node) setupForExplorerNode() { func (node *Node) setupForExplorerNode() {

@ -179,15 +179,6 @@ func (c Committee) StakedValidators() *StakedSlots {
} }
} }
// TODO refactor with and update corresponding places
// func (ss *State) StakedValidators() []*StakedSlots {
// networkWide := make([]*StakedSlots, len(ss.Shards))
// for i := range ss.Shards {
// networkWide[i] = ss.Shards[i].StakedValidators()
// }
// return networkWide
// }
// StakedValidators here is supercommittee wide // StakedValidators here is supercommittee wide
func (ss *State) StakedValidators() *StakedSlots { func (ss *State) StakedValidators() *StakedSlots {
countStakedValidator, countStakedBLSKey := 0, 0 countStakedValidator, countStakedBLSKey := 0, 0

@ -6,6 +6,7 @@ import (
"math/rand" "math/rand"
"time" "time"
msg_pb "github.com/harmony-one/harmony/api/proto/message"
"github.com/harmony-one/harmony/crypto/bls" "github.com/harmony-one/harmony/crypto/bls"
blockfactory "github.com/harmony-one/harmony/block/factory" blockfactory "github.com/harmony-one/harmony/block/factory"
@ -22,6 +23,8 @@ import (
"github.com/harmony-one/harmony/crypto/hash" "github.com/harmony-one/harmony/crypto/hash"
"github.com/harmony-one/harmony/internal/chain" "github.com/harmony-one/harmony/internal/chain"
"github.com/harmony-one/harmony/internal/common" "github.com/harmony-one/harmony/internal/common"
protobuf "github.com/golang/protobuf/proto"
"github.com/harmony-one/harmony/numeric" "github.com/harmony-one/harmony/numeric"
staking "github.com/harmony-one/harmony/staking/types" staking "github.com/harmony-one/harmony/staking/types"
) )
@ -139,6 +142,110 @@ func main() {
statedb.AddReward(validator, big.NewInt(1000), shares) statedb.AddReward(validator, big.NewInt(1000), shares)
endTime = time.Now() endTime = time.Now()
fmt.Printf("Time required to reward a validator with %d delegations: %f seconds\n", len(validator.Delegations), endTime.Sub(startTime).Seconds()) fmt.Printf("Time required to reward a validator with %d delegations: %f seconds\n", len(validator.Delegations), endTime.Sub(startTime).Seconds())
message := &msg_pb.Message{
ServiceType: msg_pb.ServiceType_CONSENSUS,
Type: msg_pb.MessageType_PREPARE,
Request: &msg_pb.Message_Consensus{
Consensus: &msg_pb.ConsensusRequest{},
},
}
blsPriKey := bls.RandPrivateKey()
pubKeyWrapper := bls.PublicKeyWrapper{Object: blsPriKey.GetPublicKey()}
pubKeyWrapper.Bytes.FromLibBLSPublicKey(pubKeyWrapper.Object)
request := message.GetConsensus()
request.ViewId = 5
request.BlockNum = 5
request.ShardId = 1
// 32 byte block hash
request.BlockHash = []byte("stasdlkfjsadlkjfkdsljflksadjf")
// sender address
request.SenderPubkey = pubKeyWrapper.Bytes[:]
message.Signature = nil
// TODO: use custom serialization method rather than protobuf
marshaledMessage, err := protobuf.Marshal(message)
// 64 byte of signature on previous data
hash1 := hash.Keccak256(marshaledMessage)
startTime = time.Now()
for i := 0; i < 1000; i++ {
blsPriKey.SignHash(hash1[:])
}
endTime = time.Now()
fmt.Printf("Time required to sign: %f seconds\n", endTime.Sub(startTime).Seconds())
sig := blsPriKey.SignHash(hash1[:])
message.Signature = sig.Serialize()
marshaledMessage2, _ := protobuf.Marshal(message)
message = &msg_pb.Message{}
if err := protobuf.Unmarshal(marshaledMessage2, message); err != nil {
return
}
startTime = time.Now()
for i := 0; i < 1000; i++ {
if err := protobuf.Unmarshal(marshaledMessage2, message); err != nil {
return
}
}
endTime = time.Now()
fmt.Printf("Time required to unmarshall: %f seconds\n", endTime.Sub(startTime).Seconds())
signature := message.Signature
message.Signature = nil
startTime = time.Now()
for i := 0; i < 1000; i++ {
protobuf.Marshal(message)
}
endTime = time.Now()
fmt.Printf("Time required to marshal: %f seconds\n", endTime.Sub(startTime).Seconds())
messageBytes, err := protobuf.Marshal(message)
msgSig := bls_core.Sign{}
err = msgSig.Deserialize(signature)
startTime = time.Now()
for i := 0; i < 1000; i++ {
msgSig.Deserialize(signature)
}
endTime = time.Now()
fmt.Printf("Time required to deserialize sig: %f seconds\n", endTime.Sub(startTime).Seconds())
msgHash := hash.Keccak256(messageBytes)
if !msgSig.VerifyHash(pubKeyWrapper.Object, msgHash[:]) {
return
}
startTime = time.Now()
for i := 0; i < 1000; i++ {
hash.Keccak256(messageBytes)
}
endTime = time.Now()
fmt.Printf("Time required to hash message: %f seconds\n", endTime.Sub(startTime).Seconds())
startTime = time.Now()
for i := 0; i < 1000; i++ {
msgSig.VerifyHash(pubKeyWrapper.Object, msgHash[:])
}
endTime = time.Now()
fmt.Printf("Time required to verify sig: %f seconds\n", endTime.Sub(startTime).Seconds())
message.Signature = signature
// A example result of a single run:
//
//Time required to calc percentage 100001 delegations: 0.058205 seconds
//Time required to reward a validator with 100001 delegations: 0.015543 seconds
//Time required to sign: 0.479827 seconds
//Time required to unmarshall: 0.000662 seconds
//Time required to marshal: 0.000453 seconds
//Time required to deserialize sig: 0.517965 seconds
//Time required to hash message: 0.001191 seconds
//Time required to verify sig: 1.444604 seconds
} }
func lookupDelegatorShares( func lookupDelegatorShares(

Loading…
Cancel
Save