From aedde512ffd640eaf8d37c29a9140797373ca1e3 Mon Sep 17 00:00:00 2001 From: andy-shi88 Date: Fri, 16 Aug 2019 17:58:33 +0800 Subject: [PATCH 01/20] #159 init node hardware --- api/client/GetNodeHardware/client.go | 55 +++ api/handler/nodeHardwareHandler.go | 30 ++ common/model/nodeHardware.pb.go | 569 +++++++++++++++++++++++++++ common/service/nodeHardware.pb.go | 148 +++++++ common/service/nodeHardware.pb.gw.go | 151 +++++++ 5 files changed, 953 insertions(+) create mode 100644 api/client/GetNodeHardware/client.go create mode 100644 api/handler/nodeHardwareHandler.go create mode 100644 common/model/nodeHardware.pb.go create mode 100644 common/service/nodeHardware.pb.go create mode 100644 common/service/nodeHardware.pb.gw.go diff --git a/api/client/GetNodeHardware/client.go b/api/client/GetNodeHardware/client.go new file mode 100644 index 000000000..28a0a982a --- /dev/null +++ b/api/client/GetNodeHardware/client.go @@ -0,0 +1,55 @@ +package main + +import ( + "context" + "github.com/zoobc/zoobc-core/common/crypto" + "time" + + log "github.com/sirupsen/logrus" + rpcModel "github.com/zoobc/zoobc-core/common/model" + rpcService "github.com/zoobc/zoobc-core/common/service" + "google.golang.org/grpc" +) + +func main() { + conn, err := grpc.Dial(":7000", grpc.WithInsecure()) + if err != nil { + log.Fatalf("did not connect: %s", err) + } + defer conn.Close() + + c := rpcService.NewNodeHardwareServiceClient(conn) + stream, err := c.GetNodeHardware(context.Background()) + if err != nil { + log.Fatalf("error calling rpcService.GetAccountBalance: %s", err) + } + waitC := make(chan struct{}) + signature := crypto.Signature{} + poow := &rpcModel.ProofOfOwnership{ + MessageBytes: []byte("HelloBlock"), + Signature: signature.SignByNode( + []byte("HelloBlock"), + "sprinkled sneak species pork outpost thrift unwind cheesy vexingly dizzy neurology neatness", + ), + } + go func() { + for { + log.Println("Sleeping...") + time.Sleep(2 * time.Second) + log.Println("Sending request...") + err = stream.Send(&rpcModel.GetNodeHardwareRequest{ + ProofOfOwnership: poow, + }) + if err != nil { + log.Fatalf("error sending request to rpcService.GetNodeHardware: %s", err) + } + response, err := stream.Recv() + if err != nil { + log.Fatalf("error receiving response from rpcService.GetNodeHardware: %s", err) + } + log.Printf("response from remote rpcService.GetNodeHardware(): %s", response) + } + }() + <-waitC + _ = stream.CloseSend() +} diff --git a/api/handler/nodeHardwareHandler.go b/api/handler/nodeHardwareHandler.go new file mode 100644 index 000000000..2fec70e5b --- /dev/null +++ b/api/handler/nodeHardwareHandler.go @@ -0,0 +1,30 @@ +package handler + +import ( + "github.com/zoobc/zoobc-core/api/service" + rpcService "github.com/zoobc/zoobc-core/common/service" + "io" +) + +type NodeHardwareHandler struct { + Service service.NodeHardwareServiceInterface +} + +func (nhh *NodeHardwareHandler) GetNodeHardware( + stream rpcService.NodeHardwareService_GetNodeHardwareServer, +) error { + for { + in, err := stream.Recv() + if err == io.EOF { + return nil + } + nodeHardware, err := nhh.Service.GetNodeHardware(in) + if err != nil { + return err + } + err = stream.Send(nodeHardware) + if err != nil { + return err + } + } +} diff --git a/common/model/nodeHardware.pb.go b/common/model/nodeHardware.pb.go new file mode 100644 index 000000000..7c489fe51 --- /dev/null +++ b/common/model/nodeHardware.pb.go @@ -0,0 +1,569 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// source: model/nodeHardware.proto + +package model + +import ( + fmt "fmt" + proto "github.com/golang/protobuf/proto" + 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 + +type GetNodeHardwareResponse struct { + NodeHardware *NodeHardware `protobuf:"bytes,1,opt,name=NodeHardware,proto3" json:"NodeHardware,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *GetNodeHardwareResponse) Reset() { *m = GetNodeHardwareResponse{} } +func (m *GetNodeHardwareResponse) String() string { return proto.CompactTextString(m) } +func (*GetNodeHardwareResponse) ProtoMessage() {} +func (*GetNodeHardwareResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_ce967b26533b171c, []int{0} +} + +func (m *GetNodeHardwareResponse) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_GetNodeHardwareResponse.Unmarshal(m, b) +} +func (m *GetNodeHardwareResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_GetNodeHardwareResponse.Marshal(b, m, deterministic) +} +func (m *GetNodeHardwareResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_GetNodeHardwareResponse.Merge(m, src) +} +func (m *GetNodeHardwareResponse) XXX_Size() int { + return xxx_messageInfo_GetNodeHardwareResponse.Size(m) +} +func (m *GetNodeHardwareResponse) XXX_DiscardUnknown() { + xxx_messageInfo_GetNodeHardwareResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_GetNodeHardwareResponse proto.InternalMessageInfo + +func (m *GetNodeHardwareResponse) GetNodeHardware() *NodeHardware { + if m != nil { + return m.NodeHardware + } + return nil +} + +type GetNodeHardwareRequest struct { + ProofOfOwnership *ProofOfOwnership `protobuf:"bytes,1,opt,name=ProofOfOwnership,proto3" json:"ProofOfOwnership,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *GetNodeHardwareRequest) Reset() { *m = GetNodeHardwareRequest{} } +func (m *GetNodeHardwareRequest) String() string { return proto.CompactTextString(m) } +func (*GetNodeHardwareRequest) ProtoMessage() {} +func (*GetNodeHardwareRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_ce967b26533b171c, []int{1} +} + +func (m *GetNodeHardwareRequest) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_GetNodeHardwareRequest.Unmarshal(m, b) +} +func (m *GetNodeHardwareRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_GetNodeHardwareRequest.Marshal(b, m, deterministic) +} +func (m *GetNodeHardwareRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_GetNodeHardwareRequest.Merge(m, src) +} +func (m *GetNodeHardwareRequest) XXX_Size() int { + return xxx_messageInfo_GetNodeHardwareRequest.Size(m) +} +func (m *GetNodeHardwareRequest) XXX_DiscardUnknown() { + xxx_messageInfo_GetNodeHardwareRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_GetNodeHardwareRequest proto.InternalMessageInfo + +func (m *GetNodeHardwareRequest) GetProofOfOwnership() *ProofOfOwnership { + if m != nil { + return m.ProofOfOwnership + } + return nil +} + +type NodeHardware struct { + CPUInformation []*CPUInformation `protobuf:"bytes,1,rep,name=CPUInformation,proto3" json:"CPUInformation,omitempty"` + MemoryInformation *MemoryInformation `protobuf:"bytes,2,opt,name=MemoryInformation,proto3" json:"MemoryInformation,omitempty"` + StorageInformation *StorageInformation `protobuf:"bytes,3,opt,name=StorageInformation,proto3" json:"StorageInformation,omitempty"` + HostInformation *HostInformation `protobuf:"bytes,4,opt,name=HostInformation,proto3" json:"HostInformation,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *NodeHardware) Reset() { *m = NodeHardware{} } +func (m *NodeHardware) String() string { return proto.CompactTextString(m) } +func (*NodeHardware) ProtoMessage() {} +func (*NodeHardware) Descriptor() ([]byte, []int) { + return fileDescriptor_ce967b26533b171c, []int{2} +} + +func (m *NodeHardware) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_NodeHardware.Unmarshal(m, b) +} +func (m *NodeHardware) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_NodeHardware.Marshal(b, m, deterministic) +} +func (m *NodeHardware) XXX_Merge(src proto.Message) { + xxx_messageInfo_NodeHardware.Merge(m, src) +} +func (m *NodeHardware) XXX_Size() int { + return xxx_messageInfo_NodeHardware.Size(m) +} +func (m *NodeHardware) XXX_DiscardUnknown() { + xxx_messageInfo_NodeHardware.DiscardUnknown(m) +} + +var xxx_messageInfo_NodeHardware proto.InternalMessageInfo + +func (m *NodeHardware) GetCPUInformation() []*CPUInformation { + if m != nil { + return m.CPUInformation + } + return nil +} + +func (m *NodeHardware) GetMemoryInformation() *MemoryInformation { + if m != nil { + return m.MemoryInformation + } + return nil +} + +func (m *NodeHardware) GetStorageInformation() *StorageInformation { + if m != nil { + return m.StorageInformation + } + return nil +} + +func (m *NodeHardware) GetHostInformation() *HostInformation { + if m != nil { + return m.HostInformation + } + return nil +} + +type CPUInformation struct { + Family string `protobuf:"bytes,1,opt,name=Family,proto3" json:"Family,omitempty"` + CPUIndex int32 `protobuf:"varint,2,opt,name=CPUIndex,proto3" json:"CPUIndex,omitempty"` + Model string `protobuf:"bytes,3,opt,name=Model,proto3" json:"Model,omitempty"` + ModelName string `protobuf:"bytes,4,opt,name=ModelName,proto3" json:"ModelName,omitempty"` + VendorId string `protobuf:"bytes,5,opt,name=VendorId,proto3" json:"VendorId,omitempty"` + Mhz float64 `protobuf:"fixed64,6,opt,name=Mhz,proto3" json:"Mhz,omitempty"` + CacheSize int32 `protobuf:"varint,7,opt,name=CacheSize,proto3" json:"CacheSize,omitempty"` + UsedPercent float64 `protobuf:"fixed64,8,opt,name=UsedPercent,proto3" json:"UsedPercent,omitempty"` + CoreID string `protobuf:"bytes,9,opt,name=CoreID,proto3" json:"CoreID,omitempty"` + Cores int32 `protobuf:"varint,10,opt,name=Cores,proto3" json:"Cores,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *CPUInformation) Reset() { *m = CPUInformation{} } +func (m *CPUInformation) String() string { return proto.CompactTextString(m) } +func (*CPUInformation) ProtoMessage() {} +func (*CPUInformation) Descriptor() ([]byte, []int) { + return fileDescriptor_ce967b26533b171c, []int{3} +} + +func (m *CPUInformation) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_CPUInformation.Unmarshal(m, b) +} +func (m *CPUInformation) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_CPUInformation.Marshal(b, m, deterministic) +} +func (m *CPUInformation) XXX_Merge(src proto.Message) { + xxx_messageInfo_CPUInformation.Merge(m, src) +} +func (m *CPUInformation) XXX_Size() int { + return xxx_messageInfo_CPUInformation.Size(m) +} +func (m *CPUInformation) XXX_DiscardUnknown() { + xxx_messageInfo_CPUInformation.DiscardUnknown(m) +} + +var xxx_messageInfo_CPUInformation proto.InternalMessageInfo + +func (m *CPUInformation) GetFamily() string { + if m != nil { + return m.Family + } + return "" +} + +func (m *CPUInformation) GetCPUIndex() int32 { + if m != nil { + return m.CPUIndex + } + return 0 +} + +func (m *CPUInformation) GetModel() string { + if m != nil { + return m.Model + } + return "" +} + +func (m *CPUInformation) GetModelName() string { + if m != nil { + return m.ModelName + } + return "" +} + +func (m *CPUInformation) GetVendorId() string { + if m != nil { + return m.VendorId + } + return "" +} + +func (m *CPUInformation) GetMhz() float64 { + if m != nil { + return m.Mhz + } + return 0 +} + +func (m *CPUInformation) GetCacheSize() int32 { + if m != nil { + return m.CacheSize + } + return 0 +} + +func (m *CPUInformation) GetUsedPercent() float64 { + if m != nil { + return m.UsedPercent + } + return 0 +} + +func (m *CPUInformation) GetCoreID() string { + if m != nil { + return m.CoreID + } + return "" +} + +func (m *CPUInformation) GetCores() int32 { + if m != nil { + return m.Cores + } + return 0 +} + +type HostInformation struct { + Uptime uint64 `protobuf:"varint,1,opt,name=Uptime,proto3" json:"Uptime,omitempty"` + OS string `protobuf:"bytes,2,opt,name=OS,proto3" json:"OS,omitempty"` + Platform string `protobuf:"bytes,3,opt,name=Platform,proto3" json:"Platform,omitempty"` + PlatformFamily string `protobuf:"bytes,4,opt,name=PlatformFamily,proto3" json:"PlatformFamily,omitempty"` + PlatformVersion string `protobuf:"bytes,5,opt,name=PlatformVersion,proto3" json:"PlatformVersion,omitempty"` + NumberOfRunningProcess uint64 `protobuf:"varint,6,opt,name=NumberOfRunningProcess,proto3" json:"NumberOfRunningProcess,omitempty"` + HostID string `protobuf:"bytes,7,opt,name=HostID,proto3" json:"HostID,omitempty"` + HostName string `protobuf:"bytes,8,opt,name=HostName,proto3" json:"HostName,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *HostInformation) Reset() { *m = HostInformation{} } +func (m *HostInformation) String() string { return proto.CompactTextString(m) } +func (*HostInformation) ProtoMessage() {} +func (*HostInformation) Descriptor() ([]byte, []int) { + return fileDescriptor_ce967b26533b171c, []int{4} +} + +func (m *HostInformation) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_HostInformation.Unmarshal(m, b) +} +func (m *HostInformation) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_HostInformation.Marshal(b, m, deterministic) +} +func (m *HostInformation) XXX_Merge(src proto.Message) { + xxx_messageInfo_HostInformation.Merge(m, src) +} +func (m *HostInformation) XXX_Size() int { + return xxx_messageInfo_HostInformation.Size(m) +} +func (m *HostInformation) XXX_DiscardUnknown() { + xxx_messageInfo_HostInformation.DiscardUnknown(m) +} + +var xxx_messageInfo_HostInformation proto.InternalMessageInfo + +func (m *HostInformation) GetUptime() uint64 { + if m != nil { + return m.Uptime + } + return 0 +} + +func (m *HostInformation) GetOS() string { + if m != nil { + return m.OS + } + return "" +} + +func (m *HostInformation) GetPlatform() string { + if m != nil { + return m.Platform + } + return "" +} + +func (m *HostInformation) GetPlatformFamily() string { + if m != nil { + return m.PlatformFamily + } + return "" +} + +func (m *HostInformation) GetPlatformVersion() string { + if m != nil { + return m.PlatformVersion + } + return "" +} + +func (m *HostInformation) GetNumberOfRunningProcess() uint64 { + if m != nil { + return m.NumberOfRunningProcess + } + return 0 +} + +func (m *HostInformation) GetHostID() string { + if m != nil { + return m.HostID + } + return "" +} + +func (m *HostInformation) GetHostName() string { + if m != nil { + return m.HostName + } + return "" +} + +type MemoryInformation struct { + Total uint64 `protobuf:"varint,1,opt,name=Total,proto3" json:"Total,omitempty"` + // This is the kernel's notion of free memory; RAM chips whose bits nobody + // cares about the value of right now. For a human consumable number, + // Available is what you really want. + Free uint64 `protobuf:"varint,2,opt,name=Free,proto3" json:"Free,omitempty"` + // RAM available for programs to allocate + Available uint64 `protobuf:"varint,3,opt,name=Available,proto3" json:"Available,omitempty"` + Used uint64 `protobuf:"varint,4,opt,name=Used,proto3" json:"Used,omitempty"` + UsedPercent float64 `protobuf:"fixed64,5,opt,name=UsedPercent,proto3" json:"UsedPercent,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *MemoryInformation) Reset() { *m = MemoryInformation{} } +func (m *MemoryInformation) String() string { return proto.CompactTextString(m) } +func (*MemoryInformation) ProtoMessage() {} +func (*MemoryInformation) Descriptor() ([]byte, []int) { + return fileDescriptor_ce967b26533b171c, []int{5} +} + +func (m *MemoryInformation) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_MemoryInformation.Unmarshal(m, b) +} +func (m *MemoryInformation) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_MemoryInformation.Marshal(b, m, deterministic) +} +func (m *MemoryInformation) XXX_Merge(src proto.Message) { + xxx_messageInfo_MemoryInformation.Merge(m, src) +} +func (m *MemoryInformation) XXX_Size() int { + return xxx_messageInfo_MemoryInformation.Size(m) +} +func (m *MemoryInformation) XXX_DiscardUnknown() { + xxx_messageInfo_MemoryInformation.DiscardUnknown(m) +} + +var xxx_messageInfo_MemoryInformation proto.InternalMessageInfo + +func (m *MemoryInformation) GetTotal() uint64 { + if m != nil { + return m.Total + } + return 0 +} + +func (m *MemoryInformation) GetFree() uint64 { + if m != nil { + return m.Free + } + return 0 +} + +func (m *MemoryInformation) GetAvailable() uint64 { + if m != nil { + return m.Available + } + return 0 +} + +func (m *MemoryInformation) GetUsed() uint64 { + if m != nil { + return m.Used + } + return 0 +} + +func (m *MemoryInformation) GetUsedPercent() float64 { + if m != nil { + return m.UsedPercent + } + return 0 +} + +type StorageInformation struct { + FsType string `protobuf:"bytes,1,opt,name=FsType,proto3" json:"FsType,omitempty"` + Total uint64 `protobuf:"varint,2,opt,name=Total,proto3" json:"Total,omitempty"` + Free uint64 `protobuf:"varint,3,opt,name=Free,proto3" json:"Free,omitempty"` + Used uint64 `protobuf:"varint,4,opt,name=Used,proto3" json:"Used,omitempty"` + UsedPercent float64 `protobuf:"fixed64,5,opt,name=UsedPercent,proto3" json:"UsedPercent,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *StorageInformation) Reset() { *m = StorageInformation{} } +func (m *StorageInformation) String() string { return proto.CompactTextString(m) } +func (*StorageInformation) ProtoMessage() {} +func (*StorageInformation) Descriptor() ([]byte, []int) { + return fileDescriptor_ce967b26533b171c, []int{6} +} + +func (m *StorageInformation) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_StorageInformation.Unmarshal(m, b) +} +func (m *StorageInformation) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_StorageInformation.Marshal(b, m, deterministic) +} +func (m *StorageInformation) XXX_Merge(src proto.Message) { + xxx_messageInfo_StorageInformation.Merge(m, src) +} +func (m *StorageInformation) XXX_Size() int { + return xxx_messageInfo_StorageInformation.Size(m) +} +func (m *StorageInformation) XXX_DiscardUnknown() { + xxx_messageInfo_StorageInformation.DiscardUnknown(m) +} + +var xxx_messageInfo_StorageInformation proto.InternalMessageInfo + +func (m *StorageInformation) GetFsType() string { + if m != nil { + return m.FsType + } + return "" +} + +func (m *StorageInformation) GetTotal() uint64 { + if m != nil { + return m.Total + } + return 0 +} + +func (m *StorageInformation) GetFree() uint64 { + if m != nil { + return m.Free + } + return 0 +} + +func (m *StorageInformation) GetUsed() uint64 { + if m != nil { + return m.Used + } + return 0 +} + +func (m *StorageInformation) GetUsedPercent() float64 { + if m != nil { + return m.UsedPercent + } + return 0 +} + +func init() { + proto.RegisterType((*GetNodeHardwareResponse)(nil), "model.GetNodeHardwareResponse") + proto.RegisterType((*GetNodeHardwareRequest)(nil), "model.GetNodeHardwareRequest") + proto.RegisterType((*NodeHardware)(nil), "model.NodeHardware") + proto.RegisterType((*CPUInformation)(nil), "model.CPUInformation") + proto.RegisterType((*HostInformation)(nil), "model.HostInformation") + proto.RegisterType((*MemoryInformation)(nil), "model.MemoryInformation") + proto.RegisterType((*StorageInformation)(nil), "model.StorageInformation") +} + +func init() { proto.RegisterFile("model/nodeHardware.proto", fileDescriptor_ce967b26533b171c) } + +var fileDescriptor_ce967b26533b171c = []byte{ + // 624 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x54, 0x4d, 0x6f, 0xd3, 0x40, + 0x10, 0x95, 0x1d, 0xa7, 0xd4, 0x5b, 0xd4, 0x96, 0x05, 0x52, 0x53, 0x71, 0x88, 0x7c, 0x40, 0x11, + 0x12, 0x89, 0x54, 0x24, 0x38, 0x21, 0x01, 0xa9, 0x4a, 0x73, 0x68, 0x13, 0x6d, 0xda, 0x1e, 0x90, + 0x38, 0x6c, 0xec, 0x49, 0x63, 0xc9, 0xf6, 0x86, 0xf5, 0x86, 0xd2, 0xfe, 0x06, 0x2e, 0x08, 0x7e, + 0x01, 0xbf, 0x14, 0xed, 0xec, 0x36, 0x71, 0xec, 0x70, 0xe1, 0x12, 0xcd, 0x9b, 0x8f, 0xe7, 0x37, + 0x6f, 0xec, 0x90, 0x20, 0x13, 0x31, 0xa4, 0xbd, 0x5c, 0xc4, 0x70, 0xca, 0x65, 0x7c, 0xc3, 0x25, + 0x74, 0xe7, 0x52,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xcf, 0x93, 0xfc, 0x7a, 0x24, 0x45, 0x04, 0x45, 0x81, 0xe6, 0x79, 0xec, 0x1f, 0x55, 0xbd, + 0x0d, 0x2e, 0x78, 0x8c, 0x66, 0xfa, 0xcc, 0x22, 0xad, 0x5e, 0x47, 0x78, 0xb2, 0x6d, 0xa3, 0xfe, + 0x1e, 0x87, 0x3f, 0x9d, 0x0d, 0x9f, 0x80, 0x76, 0xf0, 0x42, 0x28, 0x9e, 0x5a, 0x5b, 0x0c, 0xa0, + 0x94, 0x78, 0x27, 0x12, 0x00, 0x7d, 0xf1, 0x18, 0xc6, 0xfa, 0x86, 0x1f, 0xbe, 0xf1, 0x24, 0xe5, + 0x93, 0x14, 0xd0, 0x1a, 0x8f, 0xad, 0x12, 0x7a, 0x42, 0x1f, 0x0c, 0x1d, 0xf1, 0x18, 0xc6, 0xd5, + 0xbb, 0x36, 0x6b, 0x77, 0x0d, 0x7f, 0x38, 0x9b, 0x3e, 0x27, 0x7c, 0x89, 0x8b, 0x8b, 0xdb, 0x39, + 0x2c, 0x5f, 0x62, 0x44, 0x2b, 0xb1, 0xee, 0x26, 0xb1, 0x8d, 0x92, 0xd8, 0xff, 0x92, 0xf3, 0xf1, + 0xe5, 0xe7, 0xce, 0x75, 0xa2, 0x66, 0x8b, 0x49, 0x37, 0x12, 0x59, 0xef, 0x4e, 0x88, 0x49, 0x64, + 0x7e, 0x5f, 0x45, 0x42, 0x42, 0x2f, 0x12, 0x59, 0x26, 0xf2, 0x1e, 0x7e, 0x9c, 0x93, 0x2d, 0xfc, + 0x6b, 0x7d, 0xfd, 0x37, 0x00, 0x00, 0xff, 0xff, 0x08, 0x8d, 0x1e, 0xcf, 0x96, 0x05, 0x00, 0x00, +} diff --git a/common/service/nodeHardware.pb.go b/common/service/nodeHardware.pb.go new file mode 100644 index 000000000..bdfcd16a1 --- /dev/null +++ b/common/service/nodeHardware.pb.go @@ -0,0 +1,148 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// source: service/nodeHardware.proto + +package service + +import ( + context "context" + fmt "fmt" + proto "github.com/golang/protobuf/proto" + model "github.com/zoobc/zoobc-core/common/model" + _ "google.golang.org/genproto/googleapis/api/annotations" + grpc "google.golang.org/grpc" + 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 + +func init() { proto.RegisterFile("service/nodeHardware.proto", fileDescriptor_a9639805248a2100) } + +var fileDescriptor_a9639805248a2100 = []byte{ + // 201 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x2a, 0x4e, 0x2d, 0x2a, + 0xcb, 0x4c, 0x4e, 0xd5, 0xcf, 0xcb, 0x4f, 0x49, 0xf5, 0x48, 0x2c, 0x4a, 0x29, 0x4f, 0x2c, 0x4a, + 0xd5, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x87, 0xca, 0x49, 0x49, 0xe4, 0xe6, 0xa7, 0xa4, + 0xe6, 0x60, 0x51, 0x22, 0x25, 0x93, 0x9e, 0x9f, 0x9f, 0x9e, 0x93, 0xaa, 0x9f, 0x58, 0x90, 0xa9, + 0x9f, 0x98, 0x97, 0x97, 0x5f, 0x92, 0x58, 0x92, 0x99, 0x9f, 0x57, 0x0c, 0x91, 0x35, 0xea, 0x65, + 0xe4, 0x12, 0xf6, 0x43, 0xd2, 0x14, 0x0c, 0x31, 0x4f, 0xa8, 0x8c, 0x8b, 0xdf, 0x3d, 0xb5, 0x04, + 0x59, 0x46, 0x48, 0x56, 0x0f, 0x6c, 0x87, 0x1e, 0x9a, 0x78, 0x50, 0x6a, 0x61, 0x69, 0x6a, 0x71, + 0x89, 0x94, 0x1c, 0x2e, 0xe9, 0xe2, 0x82, 0xfc, 0xbc, 0xe2, 0x54, 0x25, 0x85, 0xa6, 0xcb, 0x4f, + 0x26, 0x33, 0x49, 0x09, 0x49, 0xe8, 0x97, 0x19, 0x82, 0xdd, 0xa9, 0x8f, 0xa6, 0x52, 0x83, 0xd1, + 0x80, 0xd1, 0x49, 0x27, 0x4a, 0x2b, 0x3d, 0xb3, 0x24, 0xa3, 0x34, 0x49, 0x2f, 0x39, 0x3f, 0x57, + 0xbf, 0x2a, 0x3f, 0x3f, 0x29, 0x19, 0x42, 0xea, 0x26, 0xe7, 0x17, 0xa5, 0xea, 0x27, 0xe7, 0xe7, + 0xe6, 0xe6, 0xe7, 0xe9, 0x43, 0x7d, 0x9d, 0xc4, 0x06, 0xf6, 0x84, 0x31, 0x20, 0x00, 0x00, 0xff, + 0xff, 0xa4, 0x09, 0x36, 0x76, 0x23, 0x01, 0x00, 0x00, +} + +// Reference imports to suppress errors if they are not otherwise used. +var _ context.Context +var _ grpc.ClientConn + +// 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.SupportPackageIsVersion4 + +// NodeHardwareServiceClient is the client API for NodeHardwareService service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. +type NodeHardwareServiceClient interface { + GetNodeHardware(ctx context.Context, opts ...grpc.CallOption) (NodeHardwareService_GetNodeHardwareClient, error) +} + +type nodeHardwareServiceClient struct { + cc *grpc.ClientConn +} + +func NewNodeHardwareServiceClient(cc *grpc.ClientConn) NodeHardwareServiceClient { + return &nodeHardwareServiceClient{cc} +} + +func (c *nodeHardwareServiceClient) GetNodeHardware(ctx context.Context, opts ...grpc.CallOption) (NodeHardwareService_GetNodeHardwareClient, error) { + stream, err := c.cc.NewStream(ctx, &_NodeHardwareService_serviceDesc.Streams[0], "/service.NodeHardwareService/GetNodeHardware", opts...) + if err != nil { + return nil, err + } + x := &nodeHardwareServiceGetNodeHardwareClient{stream} + return x, nil +} + +type NodeHardwareService_GetNodeHardwareClient interface { + Send(*model.GetNodeHardwareRequest) error + Recv() (*model.GetNodeHardwareResponse, error) + grpc.ClientStream +} + +type nodeHardwareServiceGetNodeHardwareClient struct { + grpc.ClientStream +} + +func (x *nodeHardwareServiceGetNodeHardwareClient) Send(m *model.GetNodeHardwareRequest) error { + return x.ClientStream.SendMsg(m) +} + +func (x *nodeHardwareServiceGetNodeHardwareClient) Recv() (*model.GetNodeHardwareResponse, error) { + m := new(model.GetNodeHardwareResponse) + if err := x.ClientStream.RecvMsg(m); err != nil { + return nil, err + } + return m, nil +} + +// NodeHardwareServiceServer is the server API for NodeHardwareService service. +type NodeHardwareServiceServer interface { + GetNodeHardware(NodeHardwareService_GetNodeHardwareServer) error +} + +func RegisterNodeHardwareServiceServer(s *grpc.Server, srv NodeHardwareServiceServer) { + s.RegisterService(&_NodeHardwareService_serviceDesc, srv) +} + +func _NodeHardwareService_GetNodeHardware_Handler(srv interface{}, stream grpc.ServerStream) error { + return srv.(NodeHardwareServiceServer).GetNodeHardware(&nodeHardwareServiceGetNodeHardwareServer{stream}) +} + +type NodeHardwareService_GetNodeHardwareServer interface { + Send(*model.GetNodeHardwareResponse) error + Recv() (*model.GetNodeHardwareRequest, error) + grpc.ServerStream +} + +type nodeHardwareServiceGetNodeHardwareServer struct { + grpc.ServerStream +} + +func (x *nodeHardwareServiceGetNodeHardwareServer) Send(m *model.GetNodeHardwareResponse) error { + return x.ServerStream.SendMsg(m) +} + +func (x *nodeHardwareServiceGetNodeHardwareServer) Recv() (*model.GetNodeHardwareRequest, error) { + m := new(model.GetNodeHardwareRequest) + if err := x.ServerStream.RecvMsg(m); err != nil { + return nil, err + } + return m, nil +} + +var _NodeHardwareService_serviceDesc = grpc.ServiceDesc{ + ServiceName: "service.NodeHardwareService", + HandlerType: (*NodeHardwareServiceServer)(nil), + Methods: []grpc.MethodDesc{}, + Streams: []grpc.StreamDesc{ + { + StreamName: "GetNodeHardware", + Handler: _NodeHardwareService_GetNodeHardware_Handler, + ServerStreams: true, + ClientStreams: true, + }, + }, + Metadata: "service/nodeHardware.proto", +} diff --git a/common/service/nodeHardware.pb.gw.go b/common/service/nodeHardware.pb.gw.go new file mode 100644 index 000000000..75cb12ab1 --- /dev/null +++ b/common/service/nodeHardware.pb.gw.go @@ -0,0 +1,151 @@ +// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. +// source: service/nodeHardware.proto + +/* +Package service is a reverse proxy. + +It translates gRPC into RESTful JSON APIs. +*/ +package service + +import ( + "context" + "io" + "net/http" + + "github.com/golang/protobuf/proto" + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/grpc-ecosystem/grpc-gateway/utilities" + "github.com/zoobc/zoobc-core/common/model" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/grpclog" + "google.golang.org/grpc/status" +) + +var _ codes.Code +var _ io.Reader +var _ status.Status +var _ = runtime.String +var _ = utilities.NewDoubleArray + +func request_NodeHardwareService_GetNodeHardware_0(ctx context.Context, marshaler runtime.Marshaler, client NodeHardwareServiceClient, req *http.Request, pathParams map[string]string) (NodeHardwareService_GetNodeHardwareClient, runtime.ServerMetadata, error) { + var metadata runtime.ServerMetadata + stream, err := client.GetNodeHardware(ctx) + if err != nil { + grpclog.Infof("Failed to start streaming: %v", err) + return nil, metadata, err + } + dec := marshaler.NewDecoder(req.Body) + handleSend := func() error { + var protoReq model.GetNodeHardwareRequest + err := dec.Decode(&protoReq) + if err == io.EOF { + return err + } + if err != nil { + grpclog.Infof("Failed to decode request: %v", err) + return err + } + if err := stream.Send(&protoReq); err != nil { + grpclog.Infof("Failed to send request: %v", err) + return err + } + return nil + } + if err := handleSend(); err != nil { + if cerr := stream.CloseSend(); cerr != nil { + grpclog.Infof("Failed to terminate client stream: %v", cerr) + } + if err == io.EOF { + return stream, metadata, nil + } + return nil, metadata, err + } + go func() { + for { + if err := handleSend(); err != nil { + break + } + } + if err := stream.CloseSend(); err != nil { + grpclog.Infof("Failed to terminate client stream: %v", err) + } + }() + header, err := stream.Header() + if err != nil { + grpclog.Infof("Failed to get header from client: %v", err) + return nil, metadata, err + } + metadata.HeaderMD = header + return stream, metadata, nil +} + +// RegisterNodeHardwareServiceHandlerFromEndpoint is same as RegisterNodeHardwareServiceHandler but +// automatically dials to "endpoint" and closes the connection when "ctx" gets done. +func RegisterNodeHardwareServiceHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { + conn, err := grpc.Dial(endpoint, opts...) + if err != nil { + return err + } + defer func() { + if err != nil { + if cerr := conn.Close(); cerr != nil { + grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) + } + return + } + go func() { + <-ctx.Done() + if cerr := conn.Close(); cerr != nil { + grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) + } + }() + }() + + return RegisterNodeHardwareServiceHandler(ctx, mux, conn) +} + +// RegisterNodeHardwareServiceHandler registers the http handlers for service NodeHardwareService to "mux". +// The handlers forward requests to the grpc endpoint over "conn". +func RegisterNodeHardwareServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { + return RegisterNodeHardwareServiceHandlerClient(ctx, mux, NewNodeHardwareServiceClient(conn)) +} + +// RegisterNodeHardwareServiceHandlerClient registers the http handlers for service NodeHardwareService +// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "NodeHardwareServiceClient". +// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "NodeHardwareServiceClient" +// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in +// "NodeHardwareServiceClient" to call the correct interceptors. +func RegisterNodeHardwareServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux, client NodeHardwareServiceClient) error { + + mux.Handle("GET", pattern_NodeHardwareService_GetNodeHardware_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_NodeHardwareService_GetNodeHardware_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_NodeHardwareService_GetNodeHardware_0(ctx, mux, outboundMarshaler, w, req, func() (proto.Message, error) { return resp.Recv() }, mux.GetForwardResponseOptions()...) + + }) + + return nil +} + +var ( + pattern_NodeHardwareService_GetNodeHardware_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "node", "GetNodeHardware"}, "", runtime.AssumeColonVerbOpt(true))) +) + +var ( + forward_NodeHardwareService_GetNodeHardware_0 = runtime.ForwardResponseStream +) From 17d723f6cc686d17fa76679a7c8c7371ed788f4e Mon Sep 17 00:00:00 2001 From: andy-shi88 Date: Mon, 19 Aug 2019 11:32:18 +0800 Subject: [PATCH 02/20] #159 update auth for node administration endpoint --- api/api.go | 13 ++- api/auth/nodeAdmin.go | 34 ++++++ api/client/GetNodeHardware/client.go | 20 +++- api/client/GetProofOfOwnership/client.go | 3 +- api/service/nodeHardwareApiService.go | 120 +++++++++++++++++++ cmd/transaction/transactionGenerator.go | 3 +- common/constant/fieldsSize.go | 2 + common/crypto/signature.go | 21 +++- common/crypto/signature_test.go | 25 ++-- common/model/auth.pb.go | 122 ++++++++++++++++++++ common/model/nodeHardware.pb.go | 92 +++++++-------- common/transaction/fixtureGenerator.go | 5 +- common/transaction/nodeRegistration_test.go | 2 +- common/util/nodeRegistration.go | 4 +- main.go | 8 +- 15 files changed, 391 insertions(+), 83 deletions(-) create mode 100644 api/auth/nodeAdmin.go create mode 100644 api/service/nodeHardwareApiService.go create mode 100644 common/model/auth.pb.go diff --git a/api/api.go b/api/api.go index 1d07e32cf..af2348915 100644 --- a/api/api.go +++ b/api/api.go @@ -33,7 +33,7 @@ func init() { } func startGrpcServer(port int, queryExecutor query.ExecutorInterface, p2pHostService p2p.ServiceInterface, - blockServices map[int32]coreService.BlockServiceInterface) { + blockServices map[int32]coreService.BlockServiceInterface, ownerAccountAddress string) { grpcServer := grpc.NewServer( grpc.UnaryInterceptor(util.NewServerInterceptor(apiLogger)), ) @@ -84,7 +84,12 @@ func startGrpcServer(port int, queryExecutor query.ExecutorInterface, p2pHostSer rpcService.RegisterNodeAdminServiceServer(grpcServer, &handler.NodeAdminHandler{ Service: service.NewNodeAdminService(queryExecutor), }) - + rpcService.RegisterNodeHardwareServiceServer(grpcServer, &handler.NodeHardwareHandler{ + Service: service.NewNodeHardwareService( + ownerAccountAddress, + crypto.NewSignature(), + ), + }) // Set GRPC handler for unconfirmed // run grpc-gateway handler go func() { @@ -97,6 +102,6 @@ func startGrpcServer(port int, queryExecutor query.ExecutorInterface, p2pHostSer // Start starts api servers in the given port and passing query executor func Start(grpcPort, restPort int, queryExecutor query.ExecutorInterface, p2pHostService p2p.ServiceInterface, - blockServices map[int32]coreService.BlockServiceInterface) { - startGrpcServer(grpcPort, queryExecutor, p2pHostService, blockServices) + blockServices map[int32]coreService.BlockServiceInterface, ownerAccountAddress string) { + startGrpcServer(grpcPort, queryExecutor, p2pHostService, blockServices, ownerAccountAddress) } diff --git a/api/auth/nodeAdmin.go b/api/auth/nodeAdmin.go new file mode 100644 index 000000000..b32e5bcec --- /dev/null +++ b/api/auth/nodeAdmin.go @@ -0,0 +1,34 @@ +package auth + +import ( + "bytes" + "github.com/zoobc/zoobc-core/common/blocker" + "github.com/zoobc/zoobc-core/common/crypto" + "github.com/zoobc/zoobc-core/common/model" + "github.com/zoobc/zoobc-core/common/util" +) + +// VerifyAuthApi verify the request body and the signature of the request message, checking include +// request type checking, and the validity of the signature to the owner address +// return nil if valid, and Blocker object otherwise +func VerifyAuthApi(ownerAddress string, auth *model.Auth, requestType model.RequestType) error { + if auth.RequestType != requestType { + return blocker.NewBlocker( + blocker.RequestParameterErr, + "invalid request type", + ) + } + signature := crypto.NewSignature() + buffer := bytes.NewBuffer([]byte{}) + buffer.Write(util.ConvertUint32ToBytes(uint32(auth.RequestType))) + buffer.Write(util.ConvertUint64ToBytes(auth.Timestamp)) + signatureValid := signature.VerifySignature( + buffer.Bytes(), + auth.Signature, + ownerAddress, + ) + if !signatureValid { + return blocker.NewBlocker(blocker.ValidationErr, "request signature invalid") + } + return nil +} diff --git a/api/client/GetNodeHardware/client.go b/api/client/GetNodeHardware/client.go index 28a0a982a..c59ea5c27 100644 --- a/api/client/GetNodeHardware/client.go +++ b/api/client/GetNodeHardware/client.go @@ -1,8 +1,11 @@ package main import ( + "bytes" "context" + "github.com/zoobc/zoobc-core/common/constant" "github.com/zoobc/zoobc-core/common/crypto" + "github.com/zoobc/zoobc-core/common/util" "time" log "github.com/sirupsen/logrus" @@ -25,11 +28,16 @@ func main() { } waitC := make(chan struct{}) signature := crypto.Signature{} - poow := &rpcModel.ProofOfOwnership{ - MessageBytes: []byte("HelloBlock"), - Signature: signature.SignByNode( - []byte("HelloBlock"), - "sprinkled sneak species pork outpost thrift unwind cheesy vexingly dizzy neurology neatness", + buffer := bytes.NewBuffer([]byte{}) + buffer.Write(util.ConvertUint32ToBytes(uint32(rpcModel.RequestType_GetNodeHardware))) + buffer.Write(util.ConvertUint64ToBytes(130000)) + auth := &rpcModel.Auth{ + RequestType: rpcModel.RequestType_GetNodeHardware, + Timestamp: 130000, + Signature: signature.Sign( + buffer.Bytes(), + constant.NodeSignatureTypeDefault, + "concur vocalist rotten busload gap quote stinging undiluted surfer goofiness deviation starved", ), } go func() { @@ -38,7 +46,7 @@ func main() { time.Sleep(2 * time.Second) log.Println("Sending request...") err = stream.Send(&rpcModel.GetNodeHardwareRequest{ - ProofOfOwnership: poow, + Auth: auth, }) if err != nil { log.Fatalf("error sending request to rpcService.GetNodeHardware: %s", err) diff --git a/api/client/GetProofOfOwnership/client.go b/api/client/GetProofOfOwnership/client.go index ce71f2c8d..73018f6de 100644 --- a/api/client/GetProofOfOwnership/client.go +++ b/api/client/GetProofOfOwnership/client.go @@ -3,6 +3,7 @@ package main import ( "bytes" "context" + "github.com/zoobc/zoobc-core/common/constant" log "github.com/sirupsen/logrus" "github.com/zoobc/zoobc-core/common/crypto" @@ -22,7 +23,7 @@ func main() { c := rpc_service.NewNodeAdminServiceClient(conn) sig := crypto.NewSignature().Sign([]byte("BCZEGOb3WNx3fDOVf9ZS4EjvOIv_UeW4TVBQJ_6tHKlE"), - "BCZEGOb3WNx3fDOVf9ZS4EjvOIv_UeW4TVBQJ_6tHKlE", + constant.NodeSignatureTypeDefault, "concur vocalist rotten busload gap quote stinging undiluted surfer goofiness deviation starved") buffer := bytes.NewBuffer([]byte{}) buffer.Write(util.ConvertUint32ToBytes(1)) diff --git a/api/service/nodeHardwareApiService.go b/api/service/nodeHardwareApiService.go new file mode 100644 index 000000000..ad85497d3 --- /dev/null +++ b/api/service/nodeHardwareApiService.go @@ -0,0 +1,120 @@ +package service + +import ( + "github.com/shirou/gopsutil/cpu" + "github.com/shirou/gopsutil/disk" + "github.com/shirou/gopsutil/host" + "github.com/shirou/gopsutil/mem" + "github.com/zoobc/zoobc-core/api/auth" + "github.com/zoobc/zoobc-core/common/crypto" + "github.com/zoobc/zoobc-core/common/model" + "runtime" +) + +type ( + NodeHardwareServiceInterface interface { + GetNodeHardware(request *model.GetNodeHardwareRequest) (*model.GetNodeHardwareResponse, error) + } + + NodeHardwareService struct { + OwnerAccountAddress string + Signature crypto.SignatureInterface + } +) + +func NewNodeHardwareService( + ownerAccountAddress string, + signature crypto.SignatureInterface, +) *NodeHardwareService { + return &NodeHardwareService{ + OwnerAccountAddress: ownerAccountAddress, + Signature: signature, + } +} + +func (nhs *NodeHardwareService) GetNodeHardware(request *model.GetNodeHardwareRequest) (*model.GetNodeHardwareResponse, error) { + var ( + nodeHardware *model.NodeHardware + cpuStats []*model.CPUInformation + err error + diskStat *disk.UsageStat + ) + // validate request + err = auth.VerifyAuthApi(nhs.OwnerAccountAddress, request.Auth, model.RequestType_GetNodeHardware) + if err != nil { + return nil, err + } + runtimeOS := runtime.GOOS + // memory + vmStat, err := mem.VirtualMemory() + if err != nil { + return nil, err + } + if runtimeOS == "windows" { + diskStat, err = disk.Usage("\\") + } else { + diskStat, err = disk.Usage("/") + } + if err != nil { + return nil, err + } + // host or machine kernel, uptime, platform Info + hostStat, err := host.Info() + if err != nil { + return nil, err + } + // cpu - get CPU number of cores and speed + cpuStat, err := cpu.Info() + if err != nil { + return nil, err + } + percentage, err := cpu.Percent(0, true) + if err != nil { + return nil, err + } + // host or machine kernel, uptime, platform Info + for i := 0; i < len(cpuStat); i++ { + cpuStats = append(cpuStats, &model.CPUInformation{ + Family: cpuStat[i].Family, + CPUIndex: cpuStat[i].CPU, + ModelName: cpuStat[i].ModelName, + VendorId: cpuStat[i].VendorID, + Mhz: cpuStat[i].Mhz, + CacheSize: cpuStat[i].CacheSize, + UsedPercent: percentage[i], + Cores: cpuStat[i].Cores, + CoreID: cpuStat[i].CoreID, + }) + + } + nodeHardware = &model.NodeHardware{ + CPUInformation: cpuStats, + MemoryInformation: &model.MemoryInformation{ + Total: vmStat.Total, + Free: vmStat.Free, + Available: vmStat.Available, + Used: vmStat.Used, + UsedPercent: vmStat.UsedPercent, + }, + StorageInformation: &model.StorageInformation{ + FsType: diskStat.Fstype, + Total: diskStat.Total, + Free: diskStat.Free, + Used: diskStat.Used, + UsedPercent: diskStat.UsedPercent, + }, + HostInformation: &model.HostInformation{ + Uptime: hostStat.Uptime, + OS: hostStat.OS, + Platform: hostStat.Platform, + PlatformFamily: hostStat.PlatformFamily, + PlatformVersion: hostStat.PlatformVersion, + NumberOfRunningProcess: hostStat.Procs, + HostID: hostStat.HostID, + HostName: hostStat.Hostname, + }, + } + return &model.GetNodeHardwareResponse{ + NodeHardware: nodeHardware, + }, nil +} diff --git a/cmd/transaction/transactionGenerator.go b/cmd/transaction/transactionGenerator.go index e0e927025..3f0620867 100644 --- a/cmd/transaction/transactionGenerator.go +++ b/cmd/transaction/transactionGenerator.go @@ -3,6 +3,7 @@ package transaction import ( "encoding/hex" "fmt" + "github.com/zoobc/zoobc-core/common/constant" "time" "github.com/zoobc/zoobc-core/common/transaction" @@ -39,7 +40,7 @@ func GenerateTransactionBytes(logger *logrus.Logger, unsignedTxBytes, _ := util.GetTransactionBytes(tx, false) tx.Signature = signature.Sign( unsignedTxBytes, - tx.SenderAccountAddress, + constant.NodeSignatureTypeDefault, seed, ) signedTxBytes, _ := util.GetTransactionBytes(tx, true) diff --git a/common/constant/fieldsSize.go b/common/constant/fieldsSize.go index 20f2f5c0c..5542c2347 100644 --- a/common/constant/fieldsSize.go +++ b/common/constant/fieldsSize.go @@ -18,4 +18,6 @@ var ( TransactionBodyLength uint32 = 4 // AccountSignature TODO: this is valid for signatures using Ed25519. in future we might have more implementations AccountSignature uint32 = 64 + // Signature variables + SignatureType uint32 = 4 ) diff --git a/common/crypto/signature.go b/common/crypto/signature.go index 52f07e89e..3c510f6ae 100644 --- a/common/crypto/signature.go +++ b/common/crypto/signature.go @@ -10,7 +10,7 @@ import ( type ( SignatureInterface interface { - Sign(payload []byte, accountAddress, seed string) []byte + Sign(payload []byte, signatureType uint32, seed string) []byte SignByNode(payload []byte, nodeSeed string) []byte VerifySignature(payload, signature []byte, accountAddress string) bool } @@ -27,10 +27,21 @@ func NewSignature() *Signature { // Sign accept account ID and payload to be signed then return the signature byte based on the // signature method associated with account.Type -func (sig *Signature) Sign(payload []byte, accountAddress, seed string) []byte { - accountPrivateKey := ed25519GetPrivateKeyFromSeed(seed) - signature := ed25519.Sign(accountPrivateKey, payload) - return signature +func (sig *Signature) Sign(payload []byte, signatureType uint32, seed string) []byte { + buffer := bytes.NewBuffer([]byte{}) + buffer.Write(util.ConvertUint32ToBytes(signatureType)) + switch signatureType { + case 0: + accountPrivateKey := ed25519GetPrivateKeyFromSeed(seed) + signature := ed25519.Sign(accountPrivateKey, payload) + buffer.Write(signature) + return buffer.Bytes() + default: + accountPrivateKey := ed25519GetPrivateKeyFromSeed(seed) + signature := ed25519.Sign(accountPrivateKey, payload) + buffer.Write(signature) + return buffer.Bytes() + } } // SignByNode special method for signing block only, there will be no multiple signature options diff --git a/common/crypto/signature_test.go b/common/crypto/signature_test.go index 1d736e915..20c8fad50 100644 --- a/common/crypto/signature_test.go +++ b/common/crypto/signature_test.go @@ -1,6 +1,7 @@ package crypto import ( + "github.com/zoobc/zoobc-core/common/constant" "reflect" "testing" ) @@ -26,9 +27,9 @@ func TestNewSignature(t *testing.T) { func TestSignature_Sign(t *testing.T) { type args struct { - payload []byte - accountAddress string - seed string + payload []byte + signatureType uint32 + seed string } tests := []struct { name string @@ -38,22 +39,22 @@ func TestSignature_Sign(t *testing.T) { { name: "Sign:valid", args: args{ - payload: []byte{12, 43, 65, 65, 12, 123, 43, 12, 1, 24, 5, 5, 12, 54}, - accountAddress: "BCZEGOb3WNx3fDOVf9ZS4EjvOIv_UeW4TVBQJ_6tHKlE", - seed: "concur vocalist rotten busload gap quote stinging undiluted surfer goofiness deviation starved", + payload: []byte{12, 43, 65, 65, 12, 123, 43, 12, 1, 24, 5, 5, 12, 54}, + signatureType: constant.NodeSignatureTypeDefault, + seed: "concur vocalist rotten busload gap quote stinging undiluted surfer goofiness deviation starved", }, - want: []byte{42, 62, 47, 200, 180, 101, 85, 204, 179, 147, 143, 68, 30, 111, 6, 94, 81, 248, 219, 43, 90, 6, 167, + want: []byte{0, 0, 0, 0, 42, 62, 47, 200, 180, 101, 85, 204, 179, 147, 143, 68, 30, 111, 6, 94, 81, 248, 219, 43, 90, 6, 167, 45, 132, 96, 130, 0, 153, 244, 159, 137, 159, 113, 78, 9, 164, 154, 213, 255, 17, 206, 153, 156, 176, 206, 33, 103, 72, 182, 228, 148, 234, 15, 176, 243, 50, 221, 106, 152, 53, 54, 173, 15}, }, { name: "Sign:valid-{default type}", args: args{ - payload: []byte{12, 43, 65, 65, 12, 123, 43, 12, 1, 24, 5, 5, 12, 54}, - accountAddress: "BCZEGOb3WNx3fDOVf9ZS4EjvOIv_UeW4TVBQJ_6tHKlE", - seed: "concur vocalist rotten busload gap quote stinging undiluted surfer goofiness deviation starved", + payload: []byte{12, 43, 65, 65, 12, 123, 43, 12, 1, 24, 5, 5, 12, 54}, + signatureType: 1011, + seed: "concur vocalist rotten busload gap quote stinging undiluted surfer goofiness deviation starved", }, - want: []byte{42, 62, 47, 200, 180, 101, 85, 204, 179, 147, 143, 68, 30, 111, 6, 94, 81, 248, 219, 43, 90, 6, 167, + want: []byte{243, 3, 0, 0, 42, 62, 47, 200, 180, 101, 85, 204, 179, 147, 143, 68, 30, 111, 6, 94, 81, 248, 219, 43, 90, 6, 167, 45, 132, 96, 130, 0, 153, 244, 159, 137, 159, 113, 78, 9, 164, 154, 213, 255, 17, 206, 153, 156, 176, 206, 33, 103, 72, 182, 228, 148, 234, 15, 176, 243, 50, 221, 106, 152, 53, 54, 173, 15}, }, @@ -61,7 +62,7 @@ func TestSignature_Sign(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { s := &Signature{} - got := s.Sign(tt.args.payload, tt.args.accountAddress, tt.args.seed) + got := s.Sign(tt.args.payload, tt.args.signatureType, tt.args.seed) if !reflect.DeepEqual(got, tt.want) { t.Errorf("Signature.Sign() = %v, want %v", got, tt.want) } diff --git a/common/model/auth.pb.go b/common/model/auth.pb.go new file mode 100644 index 000000000..adfe6c20f --- /dev/null +++ b/common/model/auth.pb.go @@ -0,0 +1,122 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// source: model/auth.proto + +package model + +import ( + fmt "fmt" + proto "github.com/golang/protobuf/proto" + 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 + +type RequestType int32 + +const ( + RequestType_GetNodeHardware RequestType = 0 +) + +var RequestType_name = map[int32]string{ + 0: "GetNodeHardware", +} + +var RequestType_value = map[string]int32{ + "GetNodeHardware": 0, +} + +func (x RequestType) String() string { + return proto.EnumName(RequestType_name, int32(x)) +} + +func (RequestType) EnumDescriptor() ([]byte, []int) { + return fileDescriptor_50b87fa4d1f0d790, []int{0} +} + +type Auth struct { + RequestType RequestType `protobuf:"varint,1,opt,name=RequestType,proto3,enum=model.RequestType" json:"RequestType,omitempty"` + Timestamp uint64 `protobuf:"varint,2,opt,name=Timestamp,proto3" json:"Timestamp,omitempty"` + Signature []byte `protobuf:"bytes,3,opt,name=Signature,proto3" json:"Signature,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *Auth) Reset() { *m = Auth{} } +func (m *Auth) String() string { return proto.CompactTextString(m) } +func (*Auth) ProtoMessage() {} +func (*Auth) Descriptor() ([]byte, []int) { + return fileDescriptor_50b87fa4d1f0d790, []int{0} +} + +func (m *Auth) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_Auth.Unmarshal(m, b) +} +func (m *Auth) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_Auth.Marshal(b, m, deterministic) +} +func (m *Auth) XXX_Merge(src proto.Message) { + xxx_messageInfo_Auth.Merge(m, src) +} +func (m *Auth) XXX_Size() int { + return xxx_messageInfo_Auth.Size(m) +} +func (m *Auth) XXX_DiscardUnknown() { + xxx_messageInfo_Auth.DiscardUnknown(m) +} + +var xxx_messageInfo_Auth proto.InternalMessageInfo + +func (m *Auth) GetRequestType() RequestType { + if m != nil { + return m.RequestType + } + return RequestType_GetNodeHardware +} + +func (m *Auth) GetTimestamp() uint64 { + if m != nil { + return m.Timestamp + } + return 0 +} + +func (m *Auth) GetSignature() []byte { + if m != nil { + return m.Signature + } + return nil +} + +func init() { + proto.RegisterEnum("model.RequestType", RequestType_name, RequestType_value) + proto.RegisterType((*Auth)(nil), "model.Auth") +} + +func init() { proto.RegisterFile("model/auth.proto", fileDescriptor_50b87fa4d1f0d790) } + +var fileDescriptor_50b87fa4d1f0d790 = []byte{ + // 195 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0xc8, 0xcd, 0x4f, 0x49, + 0xcd, 0xd1, 0x4f, 0x2c, 0x2d, 0xc9, 0xd0, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x05, 0x8b, + 0x28, 0x55, 0x70, 0xb1, 0x38, 0x96, 0x96, 0x64, 0x08, 0x99, 0x70, 0x71, 0x07, 0xa5, 0x16, 0x96, + 0xa6, 0x16, 0x97, 0x84, 0x54, 0x16, 0xa4, 0x4a, 0x30, 0x2a, 0x30, 0x6a, 0xf0, 0x19, 0x09, 0xe9, + 0x81, 0x15, 0xe9, 0x21, 0xc9, 0x04, 0x21, 0x2b, 0x13, 0x92, 0xe1, 0xe2, 0x0c, 0xc9, 0xcc, 0x4d, + 0x2d, 0x2e, 0x49, 0xcc, 0x2d, 0x90, 0x60, 0x52, 0x60, 0xd4, 0x60, 0x09, 0x42, 0x08, 0x80, 0x64, + 0x83, 0x33, 0xd3, 0xf3, 0x12, 0x4b, 0x4a, 0x8b, 0x52, 0x25, 0x98, 0x15, 0x18, 0x35, 0x78, 0x82, + 0x10, 0x02, 0x5a, 0x4a, 0x28, 0x36, 0x0a, 0x09, 0x73, 0xf1, 0xbb, 0xa7, 0x96, 0xf8, 0xe5, 0xa7, + 0xa4, 0x7a, 0x24, 0x16, 0xa5, 0x94, 0x27, 0x16, 0xa5, 0x0a, 0x30, 0x38, 0x69, 0x45, 0x69, 0xa4, + 0x67, 0x96, 0x64, 0x94, 0x26, 0xe9, 0x25, 0xe7, 0xe7, 0xea, 0x57, 0xe5, 0xe7, 0x27, 0x25, 0x43, + 0x48, 0xdd, 0xe4, 0xfc, 0xa2, 0x54, 0xfd, 0xe4, 0xfc, 0xdc, 0xdc, 0xfc, 0x3c, 0x7d, 0xb0, 0x23, + 0x93, 0xd8, 0xc0, 0xfe, 0x32, 0x06, 0x04, 0x00, 0x00, 0xff, 0xff, 0xaf, 0x46, 0xb7, 0xd7, 0xeb, + 0x00, 0x00, 0x00, +} diff --git a/common/model/nodeHardware.pb.go b/common/model/nodeHardware.pb.go index 7c489fe51..560846165 100644 --- a/common/model/nodeHardware.pb.go +++ b/common/model/nodeHardware.pb.go @@ -60,10 +60,10 @@ func (m *GetNodeHardwareResponse) GetNodeHardware() *NodeHardware { } type GetNodeHardwareRequest struct { - ProofOfOwnership *ProofOfOwnership `protobuf:"bytes,1,opt,name=ProofOfOwnership,proto3" json:"ProofOfOwnership,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` + Auth *Auth `protobuf:"bytes,1,opt,name=Auth,proto3" json:"Auth,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } func (m *GetNodeHardwareRequest) Reset() { *m = GetNodeHardwareRequest{} } @@ -91,9 +91,9 @@ func (m *GetNodeHardwareRequest) XXX_DiscardUnknown() { var xxx_messageInfo_GetNodeHardwareRequest proto.InternalMessageInfo -func (m *GetNodeHardwareRequest) GetProofOfOwnership() *ProofOfOwnership { +func (m *GetNodeHardwareRequest) GetAuth() *Auth { if m != nil { - return m.ProofOfOwnership + return m.Auth } return nil } @@ -526,44 +526,44 @@ func init() { func init() { proto.RegisterFile("model/nodeHardware.proto", fileDescriptor_ce967b26533b171c) } var fileDescriptor_ce967b26533b171c = []byte{ - // 624 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x54, 0x4d, 0x6f, 0xd3, 0x40, - 0x10, 0x95, 0x1d, 0xa7, 0xd4, 0x5b, 0xd4, 0x96, 0x05, 0x52, 0x53, 0x71, 0x88, 0x7c, 0x40, 0x11, - 0x12, 0x89, 0x54, 0x24, 0x38, 0x21, 0x01, 0xa9, 0x4a, 0x73, 0x68, 0x13, 0x6d, 0xda, 0x1e, 0x90, - 0x38, 0x6c, 0xec, 0x49, 0x63, 0xc9, 0xf6, 0x86, 0xf5, 0x86, 0xd2, 0xfe, 0x06, 0x2e, 0x08, 0x7e, - 0x01, 0xbf, 0x14, 0xed, 0xec, 0x36, 0x71, 0xec, 0x70, 0xe1, 0x12, 0xcd, 0x9b, 0x8f, 0xe7, 0x37, - 0x6f, 0xec, 0x90, 0x20, 0x13, 0x31, 0xa4, 0xbd, 0x5c, 0xc4, 0x70, 0xca, 0x65, 0x7c, 0xc3, 0x25, - 0x74, 0xe7, 0x52, 0x28, 0x41, 0x9b, 0x58, 0x39, 0x3c, 0x30, 0x0d, 0x4a, 0xf2, 0xbc, 0xe0, 0x91, - 0x4a, 0x44, 0x6e, 0xea, 0x21, 0x23, 0x07, 0x9f, 0x40, 0x9d, 0x97, 0x06, 0x19, 0x14, 0x73, 0x91, - 0x17, 0x40, 0xdf, 0x92, 0x87, 0xe5, 0x7c, 0xe0, 0xb4, 0x9d, 0xce, 0xce, 0xd1, 0xe3, 0x2e, 0x52, - 0x75, 0xd7, 0x46, 0xd6, 0x1a, 0xc3, 0x2f, 0xa4, 0x55, 0xe3, 0xfc, 0xba, 0x80, 0x42, 0xd1, 0x3e, - 0xd9, 0x1f, 0x49, 0x21, 0xa6, 0xc3, 0xe9, 0xf0, 0x26, 0x07, 0x59, 0xcc, 0x92, 0xb9, 0xa5, 0x3d, - 0xb0, 0xb4, 0xd5, 0x32, 0xab, 0x0d, 0x84, 0x7f, 0xdc, 0x75, 0x61, 0xf4, 0x1d, 0xd9, 0xed, 0x8f, - 0x2e, 0x07, 0xf9, 0x54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x5f, 0x62, 0x44, 0x2b, 0xb1, 0xee, 0x26, 0xb1, 0x8d, 0x92, 0xd8, 0xff, 0x92, 0xf3, 0xf1, - 0xe5, 0xe7, 0xce, 0x75, 0xa2, 0x66, 0x8b, 0x49, 0x37, 0x12, 0x59, 0xef, 0x4e, 0x88, 0x49, 0x64, - 0x7e, 0x5f, 0x45, 0x42, 0x42, 0x2f, 0x12, 0x59, 0x26, 0xf2, 0x1e, 0x7e, 0x9c, 0x93, 0x2d, 0xfc, - 0x6b, 0x7d, 0xfd, 0x37, 0x00, 0x00, 0xff, 0xff, 0x08, 0x8d, 0x1e, 0xcf, 0x96, 0x05, 0x00, 0x00, + // 611 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x54, 0xcd, 0x6e, 0xd3, 0x40, + 0x10, 0x96, 0x1d, 0xa7, 0xd4, 0x1b, 0xd4, 0x96, 0x05, 0x82, 0xa9, 0x90, 0x88, 0x7c, 0x40, 0x11, + 0x12, 0x89, 0x54, 0x24, 0x10, 0x07, 0x24, 0x4a, 0xab, 0xd2, 0x1c, 0xda, 0x46, 0x9b, 0xb6, 0x07, + 0x6e, 0x1b, 0x7b, 0xda, 0x58, 0xb2, 0xbd, 0x61, 0xbd, 0x06, 0xda, 0x67, 0xe0, 0x82, 0xe0, 0x09, + 0x78, 0x52, 0xb4, 0xb3, 0xdb, 0xc4, 0xb1, 0xc3, 0x85, 0x8b, 0x35, 0xdf, 0xfc, 0x7c, 0x3b, 0xf3, + 0xcd, 0xae, 0x49, 0x90, 0x89, 0x18, 0xd2, 0x61, 0x2e, 0x62, 0x38, 0xe6, 0x32, 0xfe, 0xc6, 0x25, + 0x0c, 0xe6, 0x52, 0x28, 0x41, 0xdb, 0x18, 0xd9, 0xdd, 0x31, 0x09, 0xbc, 0x54, 0x33, 0x13, 0x08, + 0x19, 0x79, 0xf2, 0x09, 0xd4, 0x69, 0xa5, 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x87, 0x3f, 0x9d, 0x35, 0x4f, 0x40, 0x2b, 0x78, 0x2e, 0x14, 0x4f, 0xad, + 0x2c, 0x06, 0x50, 0x4a, 0xbc, 0x23, 0x09, 0x80, 0xba, 0x78, 0x0c, 0x6d, 0xbd, 0xc3, 0xfd, 0xaf, + 0x3c, 0x49, 0xf9, 0x34, 0x05, 0x94, 0xc6, 0x63, 0x4b, 0x87, 0xae, 0xd0, 0x0b, 0x43, 0x45, 0x3c, + 0x86, 0x76, 0x7d, 0xaf, 0xed, 0xc6, 0x5e, 0xc3, 0x1f, 0xce, 0xba, 0xe7, 0x84, 0x97, 0xb8, 0x38, + 0xbf, 0x99, 0xc3, 0xe2, 0x12, 0x23, 0x5a, 0x36, 0xeb, 0xae, 0x6b, 0xb6, 0x55, 0x69, 0xf6, 0xbf, + 0xda, 0xf9, 0xf8, 0xf2, 0x73, 0xff, 0x3a, 0x51, 0xb3, 0x72, 0x3a, 0x88, 0x44, 0x36, 0xbc, 0x15, + 0x62, 0x1a, 0x99, 0xef, 0xab, 0x48, 0x48, 0x18, 0x46, 0x22, 0xcb, 0x44, 0x3e, 0xc4, 0xc7, 0x39, + 0xdd, 0xc0, 0xdf, 0xe6, 0xeb, 0xbf, 0x01, 0x00, 0x00, 0xff, 0xff, 0x8e, 0x0c, 0x65, 0x14, 0x6b, + 0x05, 0x00, 0x00, } diff --git a/common/transaction/fixtureGenerator.go b/common/transaction/fixtureGenerator.go index 821326b4e..b4ab8c796 100644 --- a/common/transaction/fixtureGenerator.go +++ b/common/transaction/fixtureGenerator.go @@ -1,6 +1,7 @@ package transaction import ( + "github.com/zoobc/zoobc-core/common/constant" "github.com/zoobc/zoobc-core/common/crypto" "github.com/zoobc/zoobc-core/common/model" "github.com/zoobc/zoobc-core/common/util" @@ -22,7 +23,7 @@ func GetFixturesForNoderegistration() (poownMessage *model.ProofOfOwnershipMessa poownMessageBytes := util.GetProofOfOwnershipMessageBytes(poownMessage) poownSignature := crypto.NewSignature().Sign( poownMessageBytes, - senderAddress1, + constant.NodeSignatureTypeDefault, senderSeed1, ) poown = &model.ProofOfOwnership{ @@ -57,7 +58,7 @@ func GetFixturesForUpdateNoderegistration() (poownMessage *model.ProofOfOwnershi poownMessageBytes := util.GetProofOfOwnershipMessageBytes(poownMessage) poownSignature := crypto.NewSignature().Sign( poownMessageBytes, - senderAddress1, + constant.NodeSignatureTypeDefault, senderSeed1, ) poown = &model.ProofOfOwnership{ diff --git a/common/transaction/nodeRegistration_test.go b/common/transaction/nodeRegistration_test.go index 32633c2f1..583f1a72e 100644 --- a/common/transaction/nodeRegistration_test.go +++ b/common/transaction/nodeRegistration_test.go @@ -609,7 +609,7 @@ func TestNodeRegistration_GetSize(t *testing.T) { NodeAddress: "127.0.0.1", }, }, - want: 277, + want: 281, }, } for _, tt := range tests { diff --git a/common/util/nodeRegistration.go b/common/util/nodeRegistration.go index 5c6bdef7a..44d474ddb 100644 --- a/common/util/nodeRegistration.go +++ b/common/util/nodeRegistration.go @@ -11,7 +11,7 @@ import ( func GetProofOfOwnershipSize(withSignature bool) uint32 { message := constant.AccountAddress + constant.BlockHash + constant.Height if withSignature { - return message + constant.NodeSignature + return message + constant.NodeSignature + constant.SignatureType } return message } @@ -30,7 +30,7 @@ func GetProofOfOwnershipBytes(poown *model.ProofOfOwnership) []byte { func ParseProofOfOwnershipBytes(poownBytes []byte) *model.ProofOfOwnership { buffer := bytes.NewBuffer(poownBytes) poownMessageBytes := buffer.Next(int(GetProofOfOwnershipSize(false))) - signature := buffer.Next(int(constant.NodeSignature)) + signature := buffer.Next(int(constant.NodeSignature + constant.SignatureType)) return &model.ProofOfOwnership{ MessageBytes: poownMessageBytes, Signature: signature, diff --git a/main.go b/main.go index cd413069b..861ebf59a 100644 --- a/main.go +++ b/main.go @@ -37,6 +37,7 @@ var ( p2pServiceInstance p2p.ServiceInterface queryExecutor *query.Executor observerInstance *observer.Observer + ownerAccountAddress string ) var ( @@ -68,6 +69,7 @@ func init() { if apiHTTPPort == 0 { apiHTTPPort = 8000 } + ownerAccountAddress = viper.GetString("ownerAccountAddress") } dbInstance = database.NewSqliteDB() @@ -84,9 +86,9 @@ func init() { observerInstance = observer.NewObserver() } -func startServices(queryExecutor query.ExecutorInterface) { +func startServices(queryExecutor query.ExecutorInterface, ownerAccountAddress string) { startP2pService() - api.Start(apiRPCPort, apiHTTPPort, queryExecutor, p2pServiceInstance, blockServices) + api.Start(apiRPCPort, apiHTTPPort, queryExecutor, p2pServiceInstance, blockServices, ownerAccountAddress) } func startP2pService() { @@ -174,7 +176,7 @@ func main() { logrus.Fatal(err) } - startServices(queryExecutor) + startServices(queryExecutor, ownerAccountAddress) mainchainSyncChannel := make(chan bool, 1) mainchainSyncChannel <- true From eb11f00ee0eb56ff5a6cf015c798ea49a97835af Mon Sep 17 00:00:00 2001 From: andy-shi88 Date: Mon, 19 Aug 2019 11:37:48 +0800 Subject: [PATCH 03/20] #159 add nil handler --- api/handler/nodeHardwareHandler.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/api/handler/nodeHardwareHandler.go b/api/handler/nodeHardwareHandler.go index 2fec70e5b..970978565 100644 --- a/api/handler/nodeHardwareHandler.go +++ b/api/handler/nodeHardwareHandler.go @@ -18,6 +18,9 @@ func (nhh *NodeHardwareHandler) GetNodeHardware( if err == io.EOF { return nil } + if in == nil { + return nil + } nodeHardware, err := nhh.Service.GetNodeHardware(in) if err != nil { return err From eb1f6aa9af32e5659d7c56f43d342c262a898c95 Mon Sep 17 00:00:00 2001 From: andy-shi88 Date: Mon, 19 Aug 2019 11:53:59 +0800 Subject: [PATCH 04/20] #159 add timestamp checking --- api/auth/nodeAdmin.go | 13 +++++++++++-- api/client/GetNodeHardware/client.go | 27 +++++++++++++++------------ api/service/nodeHardwareApiService.go | 2 +- 3 files changed, 27 insertions(+), 15 deletions(-) diff --git a/api/auth/nodeAdmin.go b/api/auth/nodeAdmin.go index b32e5bcec..2d12c3bc7 100644 --- a/api/auth/nodeAdmin.go +++ b/api/auth/nodeAdmin.go @@ -8,16 +8,25 @@ import ( "github.com/zoobc/zoobc-core/common/util" ) -// VerifyAuthApi verify the request body and the signature of the request message, checking include +var LastRequestTimestamp uint64 + +// VerifyAuthAPI verify the request body and the signature of the request message, checking include // request type checking, and the validity of the signature to the owner address // return nil if valid, and Blocker object otherwise -func VerifyAuthApi(ownerAddress string, auth *model.Auth, requestType model.RequestType) error { +func VerifyAuthAPI(ownerAddress string, auth *model.Auth, requestType model.RequestType) error { if auth.RequestType != requestType { return blocker.NewBlocker( blocker.RequestParameterErr, "invalid request type", ) } + if auth.Timestamp <= LastRequestTimestamp { + return blocker.NewBlocker( + blocker.ValidationErr, + "timestamp is in the past", + ) + } + LastRequestTimestamp = auth.Timestamp signature := crypto.NewSignature() buffer := bytes.NewBuffer([]byte{}) buffer.Write(util.ConvertUint32ToBytes(uint32(auth.RequestType))) diff --git a/api/client/GetNodeHardware/client.go b/api/client/GetNodeHardware/client.go index c59ea5c27..a71ea7e85 100644 --- a/api/client/GetNodeHardware/client.go +++ b/api/client/GetNodeHardware/client.go @@ -28,20 +28,23 @@ func main() { } waitC := make(chan struct{}) signature := crypto.Signature{} - buffer := bytes.NewBuffer([]byte{}) - buffer.Write(util.ConvertUint32ToBytes(uint32(rpcModel.RequestType_GetNodeHardware))) - buffer.Write(util.ConvertUint64ToBytes(130000)) - auth := &rpcModel.Auth{ - RequestType: rpcModel.RequestType_GetNodeHardware, - Timestamp: 130000, - Signature: signature.Sign( - buffer.Bytes(), - constant.NodeSignatureTypeDefault, - "concur vocalist rotten busload gap quote stinging undiluted surfer goofiness deviation starved", - ), - } + + go func() { for { + currentTime := uint64(time.Now().Unix()) + buffer := bytes.NewBuffer([]byte{}) + buffer.Write(util.ConvertUint32ToBytes(uint32(rpcModel.RequestType_GetNodeHardware))) + buffer.Write(util.ConvertUint64ToBytes(currentTime)) + auth := &rpcModel.Auth{ + RequestType: rpcModel.RequestType_GetNodeHardware, + Timestamp: currentTime, + Signature: signature.Sign( + buffer.Bytes(), + constant.NodeSignatureTypeDefault, + "concur vocalist rotten busload gap quote stinging undiluted surfer goofiness deviation starved", + ), + } log.Println("Sleeping...") time.Sleep(2 * time.Second) log.Println("Sending request...") diff --git a/api/service/nodeHardwareApiService.go b/api/service/nodeHardwareApiService.go index ad85497d3..71ea75d19 100644 --- a/api/service/nodeHardwareApiService.go +++ b/api/service/nodeHardwareApiService.go @@ -40,7 +40,7 @@ func (nhs *NodeHardwareService) GetNodeHardware(request *model.GetNodeHardwareRe diskStat *disk.UsageStat ) // validate request - err = auth.VerifyAuthApi(nhs.OwnerAccountAddress, request.Auth, model.RequestType_GetNodeHardware) + err = auth.VerifyAuthAPI(nhs.OwnerAccountAddress, request.Auth, model.RequestType_GetNodeHardware) if err != nil { return nil, err } From 9322cbacd00fac5b4684cbc5b9145ccc821a4772 Mon Sep 17 00:00:00 2001 From: andy-shi88 Date: Mon, 19 Aug 2019 11:54:30 +0800 Subject: [PATCH 05/20] #159 new schema commit --- common/schema | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/common/schema b/common/schema index ef6b4cbdd..158cdb227 160000 --- a/common/schema +++ b/common/schema @@ -1 +1 @@ -Subproject commit ef6b4cbdd8bf63846a4ead37326747d662b474ae +Subproject commit 158cdb22749fe084374feedccd97ff4f6d560d82 From 7b6a2ee3b8a902e0f944333a8396ea488fb048b9 Mon Sep 17 00:00:00 2001 From: andy-shi88 Date: Mon, 19 Aug 2019 13:25:54 +0800 Subject: [PATCH 06/20] #159 update gopkg --- Gopkg.lock | 236 +++++++++-------------------------------------------- Gopkg.toml | 5 +- 2 files changed, 41 insertions(+), 200 deletions(-) diff --git a/Gopkg.lock b/Gopkg.lock index 9c67e72b6..87641a1ed 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -2,356 +2,194 @@ [[projects]] - digest = "1:c84a587136cb69cecc11f3dbe9f9001444044c0dba74997b07f7e4c150b07cda" name = "github.com/DATA-DOG/go-sqlmock" packages = ["."] - pruneopts = "UT" revision = "3f9954f6f6697845b082ca57995849ddf614f450" version = "v1.3.3" [[projects]] - digest = "1:abeb38ade3f32a92943e5be54f55ed6d6e3b6602761d74b4aab4c9dd45c18abd" + name = "github.com/StackExchange/wmi" + packages = ["."] + revision = "5d049714c4a64225c3c79a7cf7d02f7fb5b96338" + version = "1.0.0" + +[[projects]] name = "github.com/fsnotify/fsnotify" packages = ["."] - pruneopts = "UT" revision = "c2828203cd70a50dcccfb2761f8b1f8ceef9a8e9" version = "v1.4.7" [[projects]] - digest = "1:b532ee3f683c057e797694b5bfeb3827d89e6adf41c53dbc80e549bca76364ea" + name = "github.com/go-ole/go-ole" + packages = [".","oleutil"] + revision = "97b6244175ae18ea6eef668034fd6565847501c9" + version = "v1.2.4" + +[[projects]] name = "github.com/golang/protobuf" - packages = [ - "jsonpb", - "proto", - "protoc-gen-go/descriptor", - "protoc-gen-go/generator", - "protoc-gen-go/generator/internal/remap", - "protoc-gen-go/plugin", - "ptypes", - "ptypes/any", - "ptypes/duration", - "ptypes/struct", - "ptypes/timestamp", - "ptypes/wrappers", - ] - pruneopts = "UT" + packages = ["jsonpb","proto","protoc-gen-go/descriptor","protoc-gen-go/generator","protoc-gen-go/generator/internal/remap","protoc-gen-go/plugin","ptypes","ptypes/any","ptypes/duration","ptypes/struct","ptypes/timestamp","ptypes/wrappers"] revision = "6c65a5562fc06764971b7c5d05c76c75e84bdbf7" version = "v1.3.2" [[projects]] - digest = "1:bf40199583e5143d1472fc34d10d6f4b69d97572142acf343b3e43136da40823" name = "github.com/google/go-cmp" - packages = [ - "cmp", - "cmp/internal/diff", - "cmp/internal/flags", - "cmp/internal/function", - "cmp/internal/value", - ] - pruneopts = "UT" + packages = ["cmp","cmp/internal/diff","cmp/internal/flags","cmp/internal/function","cmp/internal/value"] revision = "6f77996f0c42f7b84e5a2b252227263f93432e9b" version = "v0.3.0" [[projects]] - digest = "1:07ac748d2913b3c6d963aceec7fc4348c34a4ea58c0063779d08c2717380f7e9" name = "github.com/grpc-ecosystem/grpc-gateway" - packages = [ - "internal", - "runtime", - "utilities", - ] - pruneopts = "UT" + packages = ["internal","runtime","utilities"] revision = "bebc7374a79e1105d786ef3468b474e47d652511" version = "v1.9.4" [[projects]] - digest = "1:c0d19ab64b32ce9fe5cf4ddceba78d5bc9807f0016db6b1183599da3dcc24d10" name = "github.com/hashicorp/hcl" - packages = [ - ".", - "hcl/ast", - "hcl/parser", - "hcl/printer", - "hcl/scanner", - "hcl/strconv", - "hcl/token", - "json/parser", - "json/scanner", - "json/token", - ] - pruneopts = "UT" + packages = [".","hcl/ast","hcl/parser","hcl/printer","hcl/scanner","hcl/strconv","hcl/token","json/parser","json/scanner","json/token"] revision = "8cb6e5b959231cc1119e43259c4a608f9c51a241" version = "v1.0.0" [[projects]] - digest = "1:870d441fe217b8e689d7949fef6e43efbc787e50f200cb1e70dbca9204a1d6be" name = "github.com/inconshreveable/mousetrap" packages = ["."] - pruneopts = "UT" revision = "76626ae9c91c4f2a10f34cad8ce83ea42c93bb75" version = "v1.0" [[projects]] - digest = "1:31e761d97c76151dde79e9d28964a812c46efc5baee4085b86f68f0c654450de" name = "github.com/konsorten/go-windows-terminal-sequences" packages = ["."] - pruneopts = "UT" revision = "f55edac94c9bbba5d6182a4be46d86a2c9b5b50e" version = "v1.0.2" [[projects]] - digest = "1:5a0ef768465592efca0412f7e838cdc0826712f8447e70e6ccc52eb441e9ab13" name = "github.com/magiconair/properties" packages = ["."] - pruneopts = "UT" revision = "de8848e004dd33dc07a2947b3d76f618a7fc7ef1" version = "v1.8.1" [[projects]] - digest = "1:4a49346ca45376a2bba679ca0e83bec949d780d4e927931317904bad482943ec" name = "github.com/mattn/go-sqlite3" packages = ["."] - pruneopts = "UT" revision = "c7c4067b79cc51e6dfdcef5c702e74b1e0fa7c75" version = "v1.10.0" [[projects]] - digest = "1:53bc4cd4914cd7cd52139990d5170d6dc99067ae31c56530621b18b35fc30318" name = "github.com/mitchellh/mapstructure" packages = ["."] - pruneopts = "UT" revision = "3536a929edddb9a5b34bd6861dc4a9647cb459fe" version = "v1.1.2" [[projects]] - digest = "1:93131d8002d7025da13582877c32d1fc302486775a1b06f62241741006428c5e" name = "github.com/pelletier/go-toml" packages = ["."] - pruneopts = "UT" revision = "728039f679cbcd4f6a54e080d2219a4c4928c546" version = "v1.4.0" [[projects]] - digest = "1:04457f9f6f3ffc5fea48e71d62f2ca256637dee0a04d710288e27e05c8b41976" + name = "github.com/shirou/gopsutil" + packages = ["cpu","disk","host","internal/common","mem","net","process"] + revision = "d80c43f9c984a48783daf22f4bd9278006ae483a" + version = "v2.19.7" + +[[projects]] + branch = "master" + name = "github.com/shirou/w32" + packages = ["."] + revision = "bb4de0191aa41b5507caa14b0650cdbddcd9280b" + +[[projects]] name = "github.com/sirupsen/logrus" packages = ["."] - pruneopts = "UT" revision = "839c75faf7f98a33d445d181f3018b5c3409a45e" version = "v1.4.2" [[projects]] - digest = "1:bb495ec276ab82d3dd08504bbc0594a65de8c3b22c6f2aaa92d05b73fbf3a82e" name = "github.com/spf13/afero" - packages = [ - ".", - "mem", - ] - pruneopts = "UT" + packages = [".","mem"] revision = "588a75ec4f32903aa5e39a2619ba6a4631e28424" version = "v1.2.2" [[projects]] - digest = "1:08d65904057412fc0270fc4812a1c90c594186819243160dc779a402d4b6d0bc" name = "github.com/spf13/cast" packages = ["."] - pruneopts = "UT" revision = "8c9545af88b134710ab1cd196795e7f2388358d7" version = "v1.3.0" [[projects]] - digest = "1:e096613fb7cf34743d49af87d197663cfccd61876e2219853005a57baedfa562" name = "github.com/spf13/cobra" packages = ["."] - pruneopts = "UT" revision = "f2b07da1e2c38d5f12845a4f607e2e1018cbb1f5" version = "v0.0.5" [[projects]] - digest = "1:1b753ec16506f5864d26a28b43703c58831255059644351bbcb019b843950900" name = "github.com/spf13/jwalterweatherman" packages = ["."] - pruneopts = "UT" revision = "94f6ae3ed3bceceafa716478c5fbf8d29ca601a1" version = "v1.1.0" [[projects]] - digest = "1:c1b1102241e7f645bc8e0c22ae352e8f0dc6484b6cb4d132fa9f24174e0119e2" name = "github.com/spf13/pflag" packages = ["."] - pruneopts = "UT" revision = "298182f68c66c05229eb03ac171abe6e309ee79a" version = "v1.0.3" [[projects]] - digest = "1:11118bd196646c6515fea3d6c43f66162833c6ae4939bfb229b9956d91c6cf17" name = "github.com/spf13/viper" packages = ["."] - pruneopts = "UT" revision = "b5bf975e5823809fb22c7644d008757f78a4259e" version = "v1.4.0" [[projects]] branch = "master" - digest = "1:6bae001f7c4cddc9ebf2b47bd5ff1bd3978a84b422c468d6037dad284c8c8e9d" name = "github.com/tyler-smith/go-bip39" - packages = [ - ".", - "wordlists", - ] - pruneopts = "UT" + packages = [".","wordlists"] revision = "dbb3b84ba2ef14e894f5e33d6c6e43641e665738" [[projects]] branch = "master" - digest = "1:6bc5f992ed1dd4346d657b7467f7b3c61b3188607770ee20ab3ad75ab666e3c7" name = "golang.org/x/crypto" - packages = [ - "ed25519", - "ed25519/internal/edwards25519", - "pbkdf2", - "sha3", - ] - pruneopts = "UT" + packages = ["ed25519","ed25519/internal/edwards25519","pbkdf2","sha3"] revision = "4def268fd1a49955bfb3dda92fe3db4f924f2285" [[projects]] branch = "master" - digest = "1:d31a812696686f0059241fa6c3b56d89ada56dddde4db1d5036de5c1084000c5" name = "golang.org/x/net" - packages = [ - "http/httpguts", - "http2", - "http2/hpack", - "idna", - "internal/timeseries", - "trace", - ] - pruneopts = "UT" + packages = ["http/httpguts","http2","http2/hpack","idna","internal/timeseries","trace"] revision = "da137c7871d730100384dbcf36e6f8fa493aef5b" [[projects]] branch = "master" - digest = "1:a0e4b2275e7939970d395eb6d03f409378eb586aab72e0a461d95e3435c6c5c4" name = "golang.org/x/sys" - packages = [ - "cpu", - "unix", - ] - pruneopts = "UT" + packages = ["cpu","unix","windows"] revision = "fae7ac547cb717d141c433a2a173315e216b64c4" [[projects]] - digest = "1:8d8faad6b12a3a4c819a3f9618cb6ee1fa1cfc33253abeeea8b55336721e3405" name = "golang.org/x/text" - packages = [ - "collate", - "collate/build", - "internal/colltab", - "internal/gen", - "internal/language", - "internal/language/compact", - "internal/tag", - "internal/triegen", - "internal/ucd", - "language", - "secure/bidirule", - "transform", - "unicode/bidi", - "unicode/cldr", - "unicode/norm", - "unicode/rangetable", - ] - pruneopts = "UT" + packages = ["collate","collate/build","internal/colltab","internal/gen","internal/language","internal/language/compact","internal/tag","internal/triegen","internal/ucd","language","secure/bidirule","transform","unicode/bidi","unicode/cldr","unicode/norm","unicode/rangetable"] revision = "342b2e1fbaa52c93f31447ad2c6abc048c63e475" version = "v0.3.2" [[projects]] branch = "master" - digest = "1:1233ed1b527b0ff66c3df5879f7e80b1d8631e030cc45821b77fc25acd0d72a6" name = "google.golang.org/genproto" - packages = [ - "googleapis/api/annotations", - "googleapis/api/httpbody", - "googleapis/rpc/status", - "protobuf/field_mask", - ] - pruneopts = "UT" + packages = ["googleapis/api/annotations","googleapis/api/httpbody","googleapis/rpc/status","protobuf/field_mask"] revision = "3bdd9d9f5532d75d09efb230bd767d265245cfe5" [[projects]] - digest = "1:118eaeffc8cc29314354c26079c4142568834e9f465631f461a25526f71b0de8" name = "google.golang.org/grpc" - packages = [ - ".", - "balancer", - "balancer/base", - "balancer/roundrobin", - "binarylog/grpc_binarylog_v1", - "codes", - "connectivity", - "credentials", - "credentials/internal", - "encoding", - "encoding/proto", - "grpclog", - "internal", - "internal/backoff", - "internal/balancerload", - "internal/binarylog", - "internal/channelz", - "internal/envconfig", - "internal/grpcrand", - "internal/grpcsync", - "internal/syscall", - "internal/transport", - "keepalive", - "metadata", - "naming", - "peer", - "resolver", - "resolver/dns", - "resolver/passthrough", - "serviceconfig", - "stats", - "status", - "tap", - "test/bufconn", - ] - pruneopts = "UT" + packages = [".","balancer","balancer/base","balancer/roundrobin","binarylog/grpc_binarylog_v1","codes","connectivity","credentials","credentials/internal","encoding","encoding/proto","grpclog","internal","internal/backoff","internal/balancerload","internal/binarylog","internal/channelz","internal/envconfig","internal/grpcrand","internal/grpcsync","internal/syscall","internal/transport","keepalive","metadata","naming","peer","resolver","resolver/dns","resolver/passthrough","serviceconfig","stats","status","tap","test/bufconn"] revision = "1d89a3c832915b2314551c1d2a506874d62e53f7" version = "v1.22.0" [[projects]] - digest = "1:4d2e5a73dc1500038e504a8d78b986630e3626dc027bc030ba5c75da257cdb96" name = "gopkg.in/yaml.v2" packages = ["."] - pruneopts = "UT" revision = "51d6538a90f86fe93ac480b35f37b2be17fef232" version = "v2.2.2" [solve-meta] analyzer-name = "dep" analyzer-version = 1 - input-imports = [ - "github.com/DATA-DOG/go-sqlmock", - "github.com/golang/protobuf/proto", - "github.com/google/go-cmp/cmp", - "github.com/grpc-ecosystem/grpc-gateway/runtime", - "github.com/grpc-ecosystem/grpc-gateway/utilities", - "github.com/mattn/go-sqlite3", - "github.com/sirupsen/logrus", - "github.com/spf13/cobra", - "github.com/spf13/viper", - "github.com/tyler-smith/go-bip39", - "golang.org/x/crypto/ed25519", - "golang.org/x/crypto/sha3", - "golang.org/x/net/context", - "google.golang.org/genproto/googleapis/api/annotations", - "google.golang.org/grpc", - "google.golang.org/grpc/codes", - "google.golang.org/grpc/grpclog", - "google.golang.org/grpc/status", - "google.golang.org/grpc/test/bufconn", - ] + inputs-digest = "a58916738556e36d4a28d9c8538e132b5de70979dbe768bfabdee186988aa298" solver-name = "gps-cdcl" solver-version = 1 diff --git a/Gopkg.toml b/Gopkg.toml index a471d0980..047b56de6 100644 --- a/Gopkg.toml +++ b/Gopkg.toml @@ -72,4 +72,7 @@ [[constraint]] branch = "master" - name = "github.com/tyler-smith/go-bip39" \ No newline at end of file + name = "github.com/tyler-smith/go-bip39" +[[constraint]] + name = "github.com/shirou/gopsutil" + version = "2.19.7" From 4131e8703b98b9604f9b7ad92793952efd60675a Mon Sep 17 00:00:00 2001 From: andy-shi88 Date: Mon, 19 Aug 2019 14:08:43 +0800 Subject: [PATCH 07/20] #159 update proto --- common/service/nodeHardware.pb.go | 27 +++++++++++++-------------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/common/service/nodeHardware.pb.go b/common/service/nodeHardware.pb.go index bdfcd16a1..64b66ab91 100644 --- a/common/service/nodeHardware.pb.go +++ b/common/service/nodeHardware.pb.go @@ -27,20 +27,19 @@ const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package func init() { proto.RegisterFile("service/nodeHardware.proto", fileDescriptor_a9639805248a2100) } var fileDescriptor_a9639805248a2100 = []byte{ - // 201 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x2a, 0x4e, 0x2d, 0x2a, - 0xcb, 0x4c, 0x4e, 0xd5, 0xcf, 0xcb, 0x4f, 0x49, 0xf5, 0x48, 0x2c, 0x4a, 0x29, 0x4f, 0x2c, 0x4a, - 0xd5, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x87, 0xca, 0x49, 0x49, 0xe4, 0xe6, 0xa7, 0xa4, - 0xe6, 0x60, 0x51, 0x22, 0x25, 0x93, 0x9e, 0x9f, 0x9f, 0x9e, 0x93, 0xaa, 0x9f, 0x58, 0x90, 0xa9, - 0x9f, 0x98, 0x97, 0x97, 0x5f, 0x92, 0x58, 0x92, 0x99, 0x9f, 0x57, 0x0c, 0x91, 0x35, 0xea, 0x65, - 0xe4, 0x12, 0xf6, 0x43, 0xd2, 0x14, 0x0c, 0x31, 0x4f, 0xa8, 0x8c, 0x8b, 0xdf, 0x3d, 0xb5, 0x04, - 0x59, 0x46, 0x48, 0x56, 0x0f, 0x6c, 0x87, 0x1e, 0x9a, 0x78, 0x50, 0x6a, 0x61, 0x69, 0x6a, 0x71, - 0x89, 0x94, 0x1c, 0x2e, 0xe9, 0xe2, 0x82, 0xfc, 0xbc, 0xe2, 0x54, 0x25, 0x85, 0xa6, 0xcb, 0x4f, - 0x26, 0x33, 0x49, 0x09, 0x49, 0xe8, 0x97, 0x19, 0x82, 0xdd, 0xa9, 0x8f, 0xa6, 0x52, 0x83, 0xd1, - 0x80, 0xd1, 0x49, 0x27, 0x4a, 0x2b, 0x3d, 0xb3, 0x24, 0xa3, 0x34, 0x49, 0x2f, 0x39, 0x3f, 0x57, - 0xbf, 0x2a, 0x3f, 0x3f, 0x29, 0x19, 0x42, 0xea, 0x26, 0xe7, 0x17, 0xa5, 0xea, 0x27, 0xe7, 0xe7, - 0xe6, 0xe6, 0xe7, 0xe9, 0x43, 0x7d, 0x9d, 0xc4, 0x06, 0xf6, 0x84, 0x31, 0x20, 0x00, 0x00, 0xff, - 0xff, 0xa4, 0x09, 0x36, 0x76, 0x23, 0x01, 0x00, 0x00, + // 183 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0xcf, 0xbd, 0x0a, 0xc2, 0x30, + 0x10, 0x07, 0x70, 0xbb, 0x28, 0x74, 0x11, 0xea, 0x22, 0x41, 0x1d, 0x9c, 0x44, 0x34, 0x11, 0x7d, + 0x03, 0x17, 0x9d, 0x1c, 0x14, 0x1c, 0xdc, 0xd2, 0xf4, 0xa8, 0x81, 0x26, 0xff, 0x9a, 0xa4, 0x0a, + 0x3e, 0xbd, 0xd0, 0x76, 0x28, 0xa2, 0xcb, 0x0d, 0xf7, 0xbb, 0xcf, 0x98, 0x79, 0x72, 0x4f, 0xad, + 0x48, 0x58, 0x64, 0x74, 0x94, 0x2e, 0x7b, 0x49, 0x47, 0xbc, 0x74, 0x08, 0x48, 0x06, 0xad, 0xb1, + 0xb1, 0x41, 0x46, 0xc5, 0x8f, 0x12, 0x36, 0xc9, 0x81, 0xbc, 0x20, 0x21, 0x4b, 0x2d, 0xa4, 0xb5, + 0x08, 0x32, 0x68, 0x58, 0xdf, 0xe8, 0xd6, 0xc4, 0xa3, 0x53, 0xa7, 0xe7, 0xd2, 0x8c, 0x4b, 0xae, + 0xf1, 0xf0, 0x40, 0xa1, 0x2b, 0xc9, 0x94, 0xd7, 0x2b, 0xf8, 0x57, 0xfe, 0x4c, 0x8f, 0x8a, 0x7c, + 0x60, 0xb3, 0x7f, 0xec, 0x4b, 0x58, 0x4f, 0xf3, 0xde, 0x22, 0xda, 0x44, 0xfb, 0xd5, 0x6d, 0x99, + 0xeb, 0x70, 0xaf, 0x52, 0xae, 0x60, 0xc4, 0x1b, 0x48, 0x55, 0x13, 0xd7, 0x0a, 0x8e, 0x84, 0x82, + 0x31, 0xb0, 0xa2, 0x7d, 0x2a, 0xed, 0xd7, 0x37, 0xee, 0x3e, 0x01, 0x00, 0x00, 0xff, 0xff, 0x68, + 0x6b, 0xe8, 0x5b, 0x02, 0x01, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. From 943a90a0c29374dc8cb8311502f303535330b910 Mon Sep 17 00:00:00 2001 From: andy-shi88 Date: Mon, 19 Aug 2019 14:19:20 +0800 Subject: [PATCH 08/20] #159 inject signature object --- api/auth/nodeAdmin.go | 7 +- api/auth/nodeAdmin_test.go | 102 +++++++++++++++++ api/service/nodeHardwareApiService.go | 6 +- api/service/nodeHardwareApiService_test.go | 123 +++++++++++++++++++++ common/constant/fieldsSize.go | 2 +- 5 files changed, 236 insertions(+), 4 deletions(-) create mode 100644 api/auth/nodeAdmin_test.go create mode 100644 api/service/nodeHardwareApiService_test.go diff --git a/api/auth/nodeAdmin.go b/api/auth/nodeAdmin.go index 2d12c3bc7..e66e66fc8 100644 --- a/api/auth/nodeAdmin.go +++ b/api/auth/nodeAdmin.go @@ -13,7 +13,11 @@ var LastRequestTimestamp uint64 // VerifyAuthAPI verify the request body and the signature of the request message, checking include // request type checking, and the validity of the signature to the owner address // return nil if valid, and Blocker object otherwise -func VerifyAuthAPI(ownerAddress string, auth *model.Auth, requestType model.RequestType) error { +func VerifyAuthAPI( + ownerAddress string, + auth *model.Auth, + requestType model.RequestType, + signature crypto.SignatureInterface) error { if auth.RequestType != requestType { return blocker.NewBlocker( blocker.RequestParameterErr, @@ -27,7 +31,6 @@ func VerifyAuthAPI(ownerAddress string, auth *model.Auth, requestType model.Requ ) } LastRequestTimestamp = auth.Timestamp - signature := crypto.NewSignature() buffer := bytes.NewBuffer([]byte{}) buffer.Write(util.ConvertUint32ToBytes(uint32(auth.RequestType))) buffer.Write(util.ConvertUint64ToBytes(auth.Timestamp)) diff --git a/api/auth/nodeAdmin_test.go b/api/auth/nodeAdmin_test.go new file mode 100644 index 000000000..35dad625e --- /dev/null +++ b/api/auth/nodeAdmin_test.go @@ -0,0 +1,102 @@ +package auth + +import ( + "bytes" + "github.com/zoobc/zoobc-core/common/constant" + "github.com/zoobc/zoobc-core/common/crypto" + "github.com/zoobc/zoobc-core/common/model" + "github.com/zoobc/zoobc-core/common/util" + "testing" +) + +var ( + mockOwnerAddress = "BCZEGOb3WNx3fDOVf9ZS4EjvOIv_UeW4TVBQJ_6tHKlE" + mockOwnerSeed = "concur vocalist rotten busload gap quote stinging undiluted surfer goofiness deviation starved" +) + +func TestVerifyAuthAPI(t *testing.T) { + type args struct { + ownerAddress string + auth *model.Auth + requestType model.RequestType + signature crypto.SignatureInterface + } + buffer := bytes.NewBuffer([]byte{}) + buffer.Write(util.ConvertUint32ToBytes(0)) + buffer.Write(util.ConvertUint64ToBytes(10000)) + validSignature := (&crypto.Signature{}).Sign( + buffer.Bytes(), + constant.NodeSignatureTypeDefault, + mockOwnerSeed, + ) + tests := []struct { + name string + args args + wantErr bool + }{ + { + name: "VerifyAuthAPI:fail-invalid-requestType", + args: args{ + ownerAddress: "", + auth: &model.Auth{ + RequestType: 1, + Timestamp: 0, + Signature: nil, + }, + requestType: 0, + signature: crypto.NewSignature(), + }, + wantErr: true, + }, + { + name: "VerifyAuthAPI:fail-invalid-timestamp", + args: args{ + ownerAddress: "", + auth: &model.Auth{ + RequestType: 0, + Timestamp: 0, + Signature: nil, + }, + requestType: 0, + signature: crypto.NewSignature(), + }, + wantErr: true, + }, + { + name: "VerifyAuthAPI:fail-invalid-signature", + args: args{ + ownerAddress: mockOwnerAddress, + auth: &model.Auth{ + RequestType: 0, + Timestamp: 1000, + Signature: []byte{0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0}, + }, + requestType: 0, + signature: crypto.NewSignature(), + }, + wantErr: true, + }, + { + name: "VerifyAuthAPI:success", + args: args{ + ownerAddress: mockOwnerAddress, + auth: &model.Auth{ + RequestType: 0, + Timestamp: 10000, + Signature: validSignature, + }, + requestType: 0, + signature: crypto.NewSignature(), + }, + wantErr: false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if err := VerifyAuthAPI(tt.args.ownerAddress, tt.args.auth, + tt.args.requestType, tt.args.signature); (err != nil) != tt.wantErr { + t.Errorf("VerifyAuthAPI() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} diff --git a/api/service/nodeHardwareApiService.go b/api/service/nodeHardwareApiService.go index 71ea75d19..f6ce31fc3 100644 --- a/api/service/nodeHardwareApiService.go +++ b/api/service/nodeHardwareApiService.go @@ -40,7 +40,11 @@ func (nhs *NodeHardwareService) GetNodeHardware(request *model.GetNodeHardwareRe diskStat *disk.UsageStat ) // validate request - err = auth.VerifyAuthAPI(nhs.OwnerAccountAddress, request.Auth, model.RequestType_GetNodeHardware) + err = auth.VerifyAuthAPI( + nhs.OwnerAccountAddress, + request.Auth, + model.RequestType_GetNodeHardware, + nhs.Signature) if err != nil { return nil, err } diff --git a/api/service/nodeHardwareApiService_test.go b/api/service/nodeHardwareApiService_test.go new file mode 100644 index 000000000..3877f9c7f --- /dev/null +++ b/api/service/nodeHardwareApiService_test.go @@ -0,0 +1,123 @@ +package service + +import ( + "bytes" + "github.com/zoobc/zoobc-core/common/constant" + "github.com/zoobc/zoobc-core/common/crypto" + "github.com/zoobc/zoobc-core/common/model" + "github.com/zoobc/zoobc-core/common/util" + "reflect" + "testing" +) + +var ( + mockSignature = crypto.NewSignature() + mockOwnerAddress = "BCZEGOb3WNx3fDOVf9ZS4EjvOIv_UeW4TVBQJ_6tHKlE" + mockOwnerSeed = "concur vocalist rotten busload gap quote stinging undiluted surfer goofiness deviation starved" + mockAuth = &model.Auth{ + RequestType: 0, + Timestamp: 10000, + Signature: nil, + } + mockInvalidAuth = &model.Auth{ + RequestType: 0, + Timestamp: 0, + Signature: nil, + } + mockValidSignature []byte + mockInvalidSignature []byte +) + +func setupNodeHardwareService() { + buffer := bytes.NewBuffer([]byte{}) + buffer.Write(util.ConvertUint32ToBytes(uint32(mockAuth.RequestType))) + buffer.Write(util.ConvertUint64ToBytes(mockAuth.Timestamp)) + mockValidSignature = (&crypto.Signature{}).Sign( + buffer.Bytes(), + constant.NodeSignatureTypeDefault, + mockOwnerSeed, + ) + mockInvalidSignature = []byte{ + 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, + } +} + +func TestNewNodeHardwareService(t *testing.T) { + type args struct { + ownerAccountAddress string + signature crypto.SignatureInterface + } + tests := []struct { + name string + args args + want *NodeHardwareService + }{ + { + name: "NewNodeHardwareService:success", + args: args{ + ownerAccountAddress: mockOwnerAddress, + signature: mockSignature, + }, + want: &NodeHardwareService{ + OwnerAccountAddress: mockOwnerAddress, + Signature: mockSignature, + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := NewNodeHardwareService(tt.args.ownerAccountAddress, tt.args.signature); !reflect.DeepEqual(got, tt.want) { + t.Errorf("NewNodeHardwareService() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestNodeHardwareService_GetNodeHardware(t *testing.T) { + setupNodeHardwareService() + type fields struct { + OwnerAccountAddress string + Signature crypto.SignatureInterface + } + type args struct { + request *model.GetNodeHardwareRequest + } + tests := []struct { + name string + fields fields + args args + want *model.GetNodeHardwareResponse + wantErr bool + }{ + { + name: "GetNodeHardware:fail-invalidAuth", + fields: fields{ + OwnerAccountAddress: mockOwnerAddress, + Signature: mockSignature, + }, + args: args{ + &model.GetNodeHardwareRequest{ + Auth: mockInvalidAuth, + }, + }, + want: nil, + wantErr: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + nhs := &NodeHardwareService{ + OwnerAccountAddress: tt.fields.OwnerAccountAddress, + Signature: tt.fields.Signature, + } + got, err := nhs.GetNodeHardware(tt.args.request) + if (err != nil) != tt.wantErr { + t.Errorf("GetNodeHardware() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetNodeHardware() got = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/common/constant/fieldsSize.go b/common/constant/fieldsSize.go index 5542c2347..7fa7f9236 100644 --- a/common/constant/fieldsSize.go +++ b/common/constant/fieldsSize.go @@ -18,6 +18,6 @@ var ( TransactionBodyLength uint32 = 4 // AccountSignature TODO: this is valid for signatures using Ed25519. in future we might have more implementations AccountSignature uint32 = 64 - // Signature variables + // SignatureType variables SignatureType uint32 = 4 ) From c2abd706714601ce7f1bafb1d8597d27db3205ec Mon Sep 17 00:00:00 2001 From: andy-shi88 Date: Mon, 19 Aug 2019 14:20:45 +0800 Subject: [PATCH 09/20] #159 new schema commit --- common/schema | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/common/schema b/common/schema index 158cdb227..e58346b7f 160000 --- a/common/schema +++ b/common/schema @@ -1 +1 @@ -Subproject commit 158cdb22749fe084374feedccd97ff4f6d560d82 +Subproject commit e58346b7fcfb50d3dea14b97d1032cb371b9376a From 89862fa10789bc636a4271c05605cf10cfdcda1a Mon Sep 17 00:00:00 2001 From: andy-shi88 Date: Mon, 19 Aug 2019 15:31:31 +0800 Subject: [PATCH 10/20] #159 use blocker --- api/service/nodeHardwareApiService.go | 26 +++++++++++++++++++++----- common/blocker/blocker.go | 1 + 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/api/service/nodeHardwareApiService.go b/api/service/nodeHardwareApiService.go index f6ce31fc3..693ecc8bd 100644 --- a/api/service/nodeHardwareApiService.go +++ b/api/service/nodeHardwareApiService.go @@ -6,6 +6,7 @@ import ( "github.com/shirou/gopsutil/host" "github.com/shirou/gopsutil/mem" "github.com/zoobc/zoobc-core/api/auth" + "github.com/zoobc/zoobc-core/common/blocker" "github.com/zoobc/zoobc-core/common/crypto" "github.com/zoobc/zoobc-core/common/model" "runtime" @@ -52,7 +53,10 @@ func (nhs *NodeHardwareService) GetNodeHardware(request *model.GetNodeHardwareRe // memory vmStat, err := mem.VirtualMemory() if err != nil { - return nil, err + return nil, blocker.NewBlocker( + blocker.ServerError, + err.Error(), + ) } if runtimeOS == "windows" { diskStat, err = disk.Usage("\\") @@ -60,21 +64,33 @@ func (nhs *NodeHardwareService) GetNodeHardware(request *model.GetNodeHardwareRe diskStat, err = disk.Usage("/") } if err != nil { - return nil, err + return nil, blocker.NewBlocker( + blocker.ServerError, + err.Error(), + ) } // host or machine kernel, uptime, platform Info hostStat, err := host.Info() if err != nil { - return nil, err + return nil, blocker.NewBlocker( + blocker.ServerError, + err.Error(), + ) } // cpu - get CPU number of cores and speed cpuStat, err := cpu.Info() if err != nil { - return nil, err + return nil, blocker.NewBlocker( + blocker.ServerError, + err.Error(), + ) } percentage, err := cpu.Percent(0, true) if err != nil { - return nil, err + return nil, blocker.NewBlocker( + blocker.ServerError, + err.Error(), + ) } // host or machine kernel, uptime, platform Info for i := 0; i < len(cpuStat); i++ { diff --git a/common/blocker/blocker.go b/common/blocker/blocker.go index 724464301..7e3bc9b0b 100644 --- a/common/blocker/blocker.go +++ b/common/blocker/blocker.go @@ -19,6 +19,7 @@ var ( AppErr TypeBlocker = "AppErr" AuthErr TypeBlocker = "AuthErr" ValidationErr TypeBlocker = "ValidationErr" + ServerError TypeBlocker = "ServerError" ) func NewBlocker(typeBlocker TypeBlocker, message string) error { From 24e193780bc0356bb6069582c06ffb5295e9fb6b Mon Sep 17 00:00:00 2001 From: andy-shi88 Date: Mon, 19 Aug 2019 15:53:36 +0800 Subject: [PATCH 11/20] #159 add todo comment for later task --- api/service/nodeHardwareApiService.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/api/service/nodeHardwareApiService.go b/api/service/nodeHardwareApiService.go index 693ecc8bd..f6bdf0855 100644 --- a/api/service/nodeHardwareApiService.go +++ b/api/service/nodeHardwareApiService.go @@ -41,6 +41,8 @@ func (nhs *NodeHardwareService) GetNodeHardware(request *model.GetNodeHardwareRe diskStat *disk.UsageStat ) // validate request + // todo: this is verifying against whatever owner address is in the config file, update this + // todo: to follow how `claim` node work. err = auth.VerifyAuthAPI( nhs.OwnerAccountAddress, request.Auth, From 162548f545dcc81dfa674cac2180cbd0d52c757d Mon Sep 17 00:00:00 2001 From: andy-shi88 Date: Tue, 20 Aug 2019 16:04:50 +0800 Subject: [PATCH 12/20] #159 move node admin to common/crypto --- api/api.go | 34 ++++- {api/auth => common/crypto}/nodeAdmin.go | 7 +- {api/auth => common/crypto}/nodeAdmin_test.go | 7 +- common/util/interceptor.go | 116 -------------- common/util/interceptor_test.go | 144 ------------------ 5 files changed, 38 insertions(+), 270 deletions(-) rename {api/auth => common/crypto}/nodeAdmin.go (86%) rename {api/auth => common/crypto}/nodeAdmin_test.go (93%) delete mode 100644 common/util/interceptor.go delete mode 100644 common/util/interceptor_test.go diff --git a/api/api.go b/api/api.go index af2348915..41d62fdb9 100644 --- a/api/api.go +++ b/api/api.go @@ -1,12 +1,16 @@ package api import ( + "context" "fmt" + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/zoobc/zoobc-core/common/interceptor" "net" + "net/http" "github.com/zoobc/zoobc-core/common/chaintype" coreService "github.com/zoobc/zoobc-core/core/service" - p2p "github.com/zoobc/zoobc-core/p2p" + "github.com/zoobc/zoobc-core/p2p" "github.com/zoobc/zoobc-core/common/crypto" "github.com/zoobc/zoobc-core/common/transaction" @@ -35,7 +39,8 @@ func init() { func startGrpcServer(port int, queryExecutor query.ExecutorInterface, p2pHostService p2p.ServiceInterface, blockServices map[int32]coreService.BlockServiceInterface, ownerAccountAddress string) { grpcServer := grpc.NewServer( - grpc.UnaryInterceptor(util.NewServerInterceptor(apiLogger)), + grpc.UnaryInterceptor(interceptor.NewServerInterceptor(apiLogger)), + grpc.StreamInterceptor(interceptor.NewNodeAdminAuthStreamInterceptor(ownerAccountAddress)), ) actionTypeSwitcher := &transaction.TypeSwitcher{ Executor: queryExecutor, @@ -104,4 +109,29 @@ func startGrpcServer(port int, queryExecutor query.ExecutorInterface, p2pHostSer func Start(grpcPort, restPort int, queryExecutor query.ExecutorInterface, p2pHostService p2p.ServiceInterface, blockServices map[int32]coreService.BlockServiceInterface, ownerAccountAddress string) { startGrpcServer(grpcPort, queryExecutor, p2pHostService, blockServices, ownerAccountAddress) + go func() { + _ = runProxy(restPort, grpcPort) + }() +} + +/** +runProxy only ran when `Debug` flag is set to `true` in `config.toml` +this function open a http endpoint that will be proxy to our rpc service +*/ +func runProxy(apiPort, rpcPort int) error { + ctx := context.Background() + ctx, cancel := context.WithCancel(ctx) + defer cancel() + mux := runtime.NewServeMux() + opts := []grpc.DialOption{grpc.WithInsecure()} + _ = rpcService.RegisterAccountBalanceServiceHandlerFromEndpoint(ctx, mux, fmt.Sprintf("localhost:%d", rpcPort), opts) + _ = rpcService.RegisterBlockServiceHandlerFromEndpoint(ctx, mux, fmt.Sprintf("localhost:%d", rpcPort), opts) + _ = rpcService.RegisterHostServiceHandlerFromEndpoint(ctx, mux, fmt.Sprintf("localhost:%d", rpcPort), opts) + _ = rpcService.RegisterMempoolServiceHandlerFromEndpoint(ctx, mux, fmt.Sprintf("localhost:%d", rpcPort), opts) + _ = rpcService.RegisterNodeHardwareServiceHandlerFromEndpoint(ctx, mux, fmt.Sprintf("localhost:%d", rpcPort), opts) + _ = rpcService.RegisterNodeRegistrationServiceHandlerFromEndpoint(ctx, mux, fmt.Sprintf("localhost:%d", rpcPort), opts) + _ = rpcService.RegisterNodeAdminServiceHandlerFromEndpoint(ctx, mux, fmt.Sprintf("localhost:%d", rpcPort), opts) + _ = rpcService.RegisterTransactionServiceHandlerFromEndpoint(ctx, mux, fmt.Sprintf("localhost:%d", rpcPort), opts) + + return http.ListenAndServe(fmt.Sprintf(":%d", apiPort), mux) } diff --git a/api/auth/nodeAdmin.go b/common/crypto/nodeAdmin.go similarity index 86% rename from api/auth/nodeAdmin.go rename to common/crypto/nodeAdmin.go index e66e66fc8..d1db94d67 100644 --- a/api/auth/nodeAdmin.go +++ b/common/crypto/nodeAdmin.go @@ -1,11 +1,10 @@ -package auth +package util import ( "bytes" "github.com/zoobc/zoobc-core/common/blocker" "github.com/zoobc/zoobc-core/common/crypto" "github.com/zoobc/zoobc-core/common/model" - "github.com/zoobc/zoobc-core/common/util" ) var LastRequestTimestamp uint64 @@ -32,8 +31,8 @@ func VerifyAuthAPI( } LastRequestTimestamp = auth.Timestamp buffer := bytes.NewBuffer([]byte{}) - buffer.Write(util.ConvertUint32ToBytes(uint32(auth.RequestType))) - buffer.Write(util.ConvertUint64ToBytes(auth.Timestamp)) + buffer.Write(ConvertUint32ToBytes(uint32(auth.RequestType))) + buffer.Write(ConvertUint64ToBytes(auth.Timestamp)) signatureValid := signature.VerifySignature( buffer.Bytes(), auth.Signature, diff --git a/api/auth/nodeAdmin_test.go b/common/crypto/nodeAdmin_test.go similarity index 93% rename from api/auth/nodeAdmin_test.go rename to common/crypto/nodeAdmin_test.go index 35dad625e..677556acb 100644 --- a/api/auth/nodeAdmin_test.go +++ b/common/crypto/nodeAdmin_test.go @@ -1,11 +1,10 @@ -package auth +package util import ( "bytes" "github.com/zoobc/zoobc-core/common/constant" "github.com/zoobc/zoobc-core/common/crypto" "github.com/zoobc/zoobc-core/common/model" - "github.com/zoobc/zoobc-core/common/util" "testing" ) @@ -22,8 +21,8 @@ func TestVerifyAuthAPI(t *testing.T) { signature crypto.SignatureInterface } buffer := bytes.NewBuffer([]byte{}) - buffer.Write(util.ConvertUint32ToBytes(0)) - buffer.Write(util.ConvertUint64ToBytes(10000)) + buffer.Write(ConvertUint32ToBytes(0)) + buffer.Write(ConvertUint64ToBytes(10000)) validSignature := (&crypto.Signature{}).Sign( buffer.Bytes(), constant.NodeSignatureTypeDefault, diff --git a/common/util/interceptor.go b/common/util/interceptor.go deleted file mode 100644 index 6766504c1..000000000 --- a/common/util/interceptor.go +++ /dev/null @@ -1,116 +0,0 @@ -package util - -import ( - "context" - "fmt" - "runtime" - "time" - - "github.com/sirupsen/logrus" - - "google.golang.org/grpc" -) - -/* -NewServerInterceptor function can use to inject middlewares like: - - `recover` - - `log` triggered - - validate `authentication` if needed -With `recover()` function can handle re-run the app while got panic or error -*/ -func NewServerInterceptor(logger *logrus.Logger) grpc.UnaryServerInterceptor { - return func( - ctx context.Context, - req interface{}, - info *grpc.UnaryServerInfo, - handler grpc.UnaryHandler, - ) (interface{}, error) { - var ( - errHandler error - resp interface{} - ) - start := time.Now() - fields := logrus.Fields{ - "method": info.FullMethod, - "time": start.String(), - } - - defer func() { - - fields["latency"] = fmt.Sprintf("%d ns", time.Since(start).Nanoseconds()) - err := recover() - if err != nil { - // get stack after panic called and perhaps its first error - _, file, line, _ := runtime.Caller(4) - fields["panic"] = fmt.Sprintf("%s %d", file, line) - } else if errHandler != nil { - fields["error"] = errHandler - } - - if logger != nil { - switch { - case err != nil: - logger.WithFields(fields).Error(fmt.Sprint(err)) - case errHandler != nil: - logger.WithFields(fields).Warning(errHandler) - default: - logger.WithFields(fields).Info("success") - } - } - }() - - resp, errHandler = handler(ctx, req) - return resp, errHandler - } -} - -/* -NewClientInterceptor function can use to inject using grpc client like: - - `recover` - - `log` triggered - - add access token if needed -With `recover()` function can handle re-run the app while got panic -*/ -func NewClientInterceptor(logger *logrus.Logger) grpc.UnaryClientInterceptor { - return func( - ctx context.Context, - method string, - req interface{}, - reply interface{}, - cc *grpc.ClientConn, - invoker grpc.UnaryInvoker, - opts ...grpc.CallOption, - ) error { - var ( - errInvoker error - ) - start := time.Now() - fields := logrus.Fields{ - "method": method, - "time": start.String(), - } - - defer func() { - fields["latency"] = fmt.Sprintf("%d ns", time.Since(start).Nanoseconds()) - err := recover() - if err != nil { - // get stack after panic called and perhaps its first error - _, file, line, _ := runtime.Caller(4) - fields["panic"] = fmt.Sprintf("%s %d", file, line) - } - if logger != nil { - switch { - case err != nil: - logger.WithFields(fields).Error(fmt.Sprint(err)) - case errInvoker != nil: - logger.WithFields(fields).Warning(fmt.Sprint(errInvoker)) - default: - logger.WithFields(fields).Info("success") - } - } - }() - errInvoker = invoker(ctx, method, req, reply, cc, opts...) - return errInvoker - } - -} diff --git a/common/util/interceptor_test.go b/common/util/interceptor_test.go deleted file mode 100644 index a9daa4338..000000000 --- a/common/util/interceptor_test.go +++ /dev/null @@ -1,144 +0,0 @@ -package util - -import ( - "context" - "testing" - - "github.com/google/go-cmp/cmp" - "github.com/sirupsen/logrus" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" -) - -func TestNewServerInterceptor(t *testing.T) { - - type args struct { - logger *logrus.Logger - } - tests := []struct { - name string - args args - want grpc.UnaryServerInterceptor - wantRecover bool - }{ - { - name: "wantRecover", - args: args{ - logger: logrus.New(), - }, - want: func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) { - return nil, status.Errorf(codes.Internal, "there's something wrong") - }, - wantRecover: true, - }, - { - name: "wantNotRecover", - args: args{ - logger: logrus.New(), - }, - want: func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) { - return nil, status.Errorf(codes.Internal, "there's something wrong") - }, - wantRecover: false, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got := NewServerInterceptor(tt.args.logger) - if cmp.Equal(got, tt.want) { - t.Errorf("NewInterceptor() = %v, want %v", got, tt.want) - } - testServerInterceptor(got, tt.wantRecover) - }) - } -} - -func testServerInterceptor(fn grpc.UnaryServerInterceptor, wantRecover bool) { - var ( - handler grpc.UnaryHandler - ) - if wantRecover { - handler = func(ctx context.Context, req interface{}) (resp interface{}, err error) { - panic(handler) - } - } else { - handler = func(ctx context.Context, req interface{}) (resp interface{}, err error) { - return nil, status.Errorf(codes.Internal, "there's something wrong") - } - } - _, _ = fn(context.Background(), nil, &grpc.UnaryServerInfo{}, handler) -} - -func TestNewClientInterceptor(t *testing.T) { - type args struct { - logger *logrus.Logger - } - tests := []struct { - name string - args args - want grpc.UnaryClientInterceptor - wantRecover bool - }{ - { - name: "wantRecover", - args: args{ - logger: logrus.New(), - }, - want: func( - ctx context.Context, - method string, - req, reply interface{}, - cc *grpc.ClientConn, - invoker grpc.UnaryInvoker, - opts ...grpc.CallOption) error { - return status.Errorf(codes.Internal, "there's something wrong") - }, - wantRecover: false, - }, - { - name: "wantRecover", - args: args{ - logger: logrus.New(), - }, - want: func( - ctx context.Context, - method string, - req, reply interface{}, - cc *grpc.ClientConn, - invoker grpc.UnaryInvoker, - opts ...grpc.CallOption) error { - return status.Errorf(codes.Internal, "there's something wrong") - }, - wantRecover: true, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got := NewClientInterceptor(tt.args.logger) - if cmp.Equal(got, tt.want) { - t.Errorf("NewClientInterceptor() = %v, want %v", got, tt.want) - } - testClientInterceptor(got, tt.wantRecover) - }) - } -} - -func testClientInterceptor(fn grpc.UnaryClientInterceptor, wantRecover bool) { - var ( - invoker grpc.UnaryInvoker - ) - if wantRecover { - invoker = func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, opts ...grpc.CallOption) error { - panic(invoker) - } - } else { - invoker = func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, opts ...grpc.CallOption) error { - return status.Errorf(codes.Internal, "there's something wrong") - } - } - - cc, _ := grpc.Dial("127.0.0.1:8001", grpc.WithInsecure()) - _ = fn(context.Background(), "testMethod", nil, nil, cc, invoker, nil) - -} From f116beddca529a74e92d8e840020d7d3055be2a3 Mon Sep 17 00:00:00 2001 From: andy-shi88 Date: Tue, 20 Aug 2019 16:05:55 +0800 Subject: [PATCH 13/20] #159 delegate authentication to interceptor --- api/client/GetNodeHardware/client.go | 30 ++++---- api/service/nodeHardwareApiService.go | 13 +--- api/service/nodeHardwareApiService_test.go | 80 ---------------------- 3 files changed, 17 insertions(+), 106 deletions(-) diff --git a/api/client/GetNodeHardware/client.go b/api/client/GetNodeHardware/client.go index a71ea7e85..fe1442ade 100644 --- a/api/client/GetNodeHardware/client.go +++ b/api/client/GetNodeHardware/client.go @@ -3,9 +3,11 @@ package main import ( "bytes" "context" + "encoding/hex" "github.com/zoobc/zoobc-core/common/constant" "github.com/zoobc/zoobc-core/common/crypto" "github.com/zoobc/zoobc-core/common/util" + "google.golang.org/grpc/metadata" "time" log "github.com/sirupsen/logrus" @@ -22,35 +24,35 @@ func main() { defer conn.Close() c := rpcService.NewNodeHardwareServiceClient(conn) - stream, err := c.GetNodeHardware(context.Background()) + var stream rpcService.NodeHardwareService_GetNodeHardwareClient + if err != nil { log.Fatalf("error calling rpcService.GetAccountBalance: %s", err) } waitC := make(chan struct{}) signature := crypto.Signature{} - go func() { for { currentTime := uint64(time.Now().Unix()) buffer := bytes.NewBuffer([]byte{}) buffer.Write(util.ConvertUint32ToBytes(uint32(rpcModel.RequestType_GetNodeHardware))) buffer.Write(util.ConvertUint64ToBytes(currentTime)) - auth := &rpcModel.Auth{ - RequestType: rpcModel.RequestType_GetNodeHardware, - Timestamp: currentTime, - Signature: signature.Sign( - buffer.Bytes(), - constant.NodeSignatureTypeDefault, - "concur vocalist rotten busload gap quote stinging undiluted surfer goofiness deviation starved", - ), - } + sig := signature.Sign( + buffer.Bytes(), + constant.NodeSignatureTypeDefault, + "concur vocalist rotten busload gap quote stinging undiluted surfer goofiness deviation starved", + ) + buffer.Write(sig) + + ctx := context.Background() + md := metadata.Pairs("authorization", hex.EncodeToString(buffer.Bytes())) + ctx = metadata.NewOutgoingContext(ctx, md) + stream, err = c.GetNodeHardware(ctx) log.Println("Sleeping...") time.Sleep(2 * time.Second) log.Println("Sending request...") - err = stream.Send(&rpcModel.GetNodeHardwareRequest{ - Auth: auth, - }) + err = stream.Send(&rpcModel.GetNodeHardwareRequest{}) if err != nil { log.Fatalf("error sending request to rpcService.GetNodeHardware: %s", err) } diff --git a/api/service/nodeHardwareApiService.go b/api/service/nodeHardwareApiService.go index f6bdf0855..db47c1e19 100644 --- a/api/service/nodeHardwareApiService.go +++ b/api/service/nodeHardwareApiService.go @@ -5,7 +5,6 @@ import ( "github.com/shirou/gopsutil/disk" "github.com/shirou/gopsutil/host" "github.com/shirou/gopsutil/mem" - "github.com/zoobc/zoobc-core/api/auth" "github.com/zoobc/zoobc-core/common/blocker" "github.com/zoobc/zoobc-core/common/crypto" "github.com/zoobc/zoobc-core/common/model" @@ -40,17 +39,7 @@ func (nhs *NodeHardwareService) GetNodeHardware(request *model.GetNodeHardwareRe err error diskStat *disk.UsageStat ) - // validate request - // todo: this is verifying against whatever owner address is in the config file, update this - // todo: to follow how `claim` node work. - err = auth.VerifyAuthAPI( - nhs.OwnerAccountAddress, - request.Auth, - model.RequestType_GetNodeHardware, - nhs.Signature) - if err != nil { - return nil, err - } + runtimeOS := runtime.GOOS // memory vmStat, err := mem.VirtualMemory() diff --git a/api/service/nodeHardwareApiService_test.go b/api/service/nodeHardwareApiService_test.go index 3877f9c7f..f5aceca7f 100644 --- a/api/service/nodeHardwareApiService_test.go +++ b/api/service/nodeHardwareApiService_test.go @@ -1,11 +1,7 @@ package service import ( - "bytes" - "github.com/zoobc/zoobc-core/common/constant" "github.com/zoobc/zoobc-core/common/crypto" - "github.com/zoobc/zoobc-core/common/model" - "github.com/zoobc/zoobc-core/common/util" "reflect" "testing" ) @@ -13,35 +9,8 @@ import ( var ( mockSignature = crypto.NewSignature() mockOwnerAddress = "BCZEGOb3WNx3fDOVf9ZS4EjvOIv_UeW4TVBQJ_6tHKlE" - mockOwnerSeed = "concur vocalist rotten busload gap quote stinging undiluted surfer goofiness deviation starved" - mockAuth = &model.Auth{ - RequestType: 0, - Timestamp: 10000, - Signature: nil, - } - mockInvalidAuth = &model.Auth{ - RequestType: 0, - Timestamp: 0, - Signature: nil, - } - mockValidSignature []byte - mockInvalidSignature []byte ) -func setupNodeHardwareService() { - buffer := bytes.NewBuffer([]byte{}) - buffer.Write(util.ConvertUint32ToBytes(uint32(mockAuth.RequestType))) - buffer.Write(util.ConvertUint64ToBytes(mockAuth.Timestamp)) - mockValidSignature = (&crypto.Signature{}).Sign( - buffer.Bytes(), - constant.NodeSignatureTypeDefault, - mockOwnerSeed, - ) - mockInvalidSignature = []byte{ - 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, - } -} - func TestNewNodeHardwareService(t *testing.T) { type args struct { ownerAccountAddress string @@ -72,52 +41,3 @@ func TestNewNodeHardwareService(t *testing.T) { }) } } - -func TestNodeHardwareService_GetNodeHardware(t *testing.T) { - setupNodeHardwareService() - type fields struct { - OwnerAccountAddress string - Signature crypto.SignatureInterface - } - type args struct { - request *model.GetNodeHardwareRequest - } - tests := []struct { - name string - fields fields - args args - want *model.GetNodeHardwareResponse - wantErr bool - }{ - { - name: "GetNodeHardware:fail-invalidAuth", - fields: fields{ - OwnerAccountAddress: mockOwnerAddress, - Signature: mockSignature, - }, - args: args{ - &model.GetNodeHardwareRequest{ - Auth: mockInvalidAuth, - }, - }, - want: nil, - wantErr: true, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - nhs := &NodeHardwareService{ - OwnerAccountAddress: tt.fields.OwnerAccountAddress, - Signature: tt.fields.Signature, - } - got, err := nhs.GetNodeHardware(tt.args.request) - if (err != nil) != tt.wantErr { - t.Errorf("GetNodeHardware() error = %v, wantErr %v", err, tt.wantErr) - return - } - if !reflect.DeepEqual(got, tt.want) { - t.Errorf("GetNodeHardware() got = %v, want %v", got, tt.want) - } - }) - } -} From 4425d73c8f2653e6954f26996eb29915322d406f Mon Sep 17 00:00:00 2001 From: andy-shi88 Date: Tue, 20 Aug 2019 16:06:59 +0800 Subject: [PATCH 14/20] #159 request auth will be validated in hex string --- common/constant/fieldsSize.go | 4 +- common/crypto/nodeAdmin.go | 39 ++++++++----- common/crypto/nodeAdmin_test.go | 97 +++++++++++++++++++-------------- 3 files changed, 84 insertions(+), 56 deletions(-) diff --git a/common/constant/fieldsSize.go b/common/constant/fieldsSize.go index 7fa7f9236..f691b0db7 100644 --- a/common/constant/fieldsSize.go +++ b/common/constant/fieldsSize.go @@ -19,5 +19,7 @@ var ( // AccountSignature TODO: this is valid for signatures using Ed25519. in future we might have more implementations AccountSignature uint32 = 64 // SignatureType variables - SignatureType uint32 = 4 + SignatureType uint32 = 4 + AuthRequestType = 4 + AuthTimestamp = 8 ) diff --git a/common/crypto/nodeAdmin.go b/common/crypto/nodeAdmin.go index d1db94d67..0f071df6a 100644 --- a/common/crypto/nodeAdmin.go +++ b/common/crypto/nodeAdmin.go @@ -1,10 +1,12 @@ -package util +package crypto import ( "bytes" + "encoding/hex" "github.com/zoobc/zoobc-core/common/blocker" - "github.com/zoobc/zoobc-core/common/crypto" + "github.com/zoobc/zoobc-core/common/constant" "github.com/zoobc/zoobc-core/common/model" + "github.com/zoobc/zoobc-core/common/util" ) var LastRequestTimestamp uint64 @@ -13,29 +15,38 @@ var LastRequestTimestamp uint64 // request type checking, and the validity of the signature to the owner address // return nil if valid, and Blocker object otherwise func VerifyAuthAPI( - ownerAddress string, - auth *model.Auth, - requestType model.RequestType, - signature crypto.SignatureInterface) error { - if auth.RequestType != requestType { + ownerAddress, + auth string, + requestType model.RequestType) error { + // parse + var ( + authRequestType int32 + authTimestamp uint64 + ) + signature := NewSignature() + authBytes, err := hex.DecodeString(auth) + if err != nil { + return err + } + authBytesBuffer := bytes.NewBuffer(authBytes) + authRequestType = int32(util.ConvertBytesToUint32(authBytesBuffer.Next(constant.AuthRequestType))) + authTimestamp = util.ConvertBytesToUint64(authBytesBuffer.Next(constant.AuthTimestamp)) + if authRequestType != int32(requestType) { return blocker.NewBlocker( blocker.RequestParameterErr, "invalid request type", ) } - if auth.Timestamp <= LastRequestTimestamp { + if authTimestamp <= LastRequestTimestamp { return blocker.NewBlocker( blocker.ValidationErr, "timestamp is in the past", ) } - LastRequestTimestamp = auth.Timestamp - buffer := bytes.NewBuffer([]byte{}) - buffer.Write(ConvertUint32ToBytes(uint32(auth.RequestType))) - buffer.Write(ConvertUint64ToBytes(auth.Timestamp)) + LastRequestTimestamp = authTimestamp signatureValid := signature.VerifySignature( - buffer.Bytes(), - auth.Signature, + authBytes[:constant.AuthRequestType+constant.AuthTimestamp], + authBytes[constant.AuthRequestType+constant.AuthTimestamp:], ownerAddress, ) if !signatureValid { diff --git a/common/crypto/nodeAdmin_test.go b/common/crypto/nodeAdmin_test.go index 677556acb..6056b6694 100644 --- a/common/crypto/nodeAdmin_test.go +++ b/common/crypto/nodeAdmin_test.go @@ -1,49 +1,78 @@ -package util +package crypto import ( "bytes" + "encoding/hex" "github.com/zoobc/zoobc-core/common/constant" - "github.com/zoobc/zoobc-core/common/crypto" "github.com/zoobc/zoobc-core/common/model" + "github.com/zoobc/zoobc-core/common/util" "testing" ) var ( mockOwnerAddress = "BCZEGOb3WNx3fDOVf9ZS4EjvOIv_UeW4TVBQJ_6tHKlE" mockOwnerSeed = "concur vocalist rotten busload gap quote stinging undiluted surfer goofiness deviation starved" + mockValidAuth, + mockInvalidTimestampAuth, + mockInvalidRequestTypeAuth, + mockInvalidSignatureAuth string ) +func setupVerifyAuthAPI() { + var ( + bufferValid *bytes.Buffer + bufferInvalidTimestamp *bytes.Buffer + bufferInvalidRequestType *bytes.Buffer + ) + bufferValid = bytes.NewBuffer([]byte{}) + bufferInvalidRequestType = bytes.NewBuffer([]byte{}) + bufferInvalidTimestamp = bytes.NewBuffer([]byte{}) + bufferValid.Write(util.ConvertUint32ToBytes(0)) + bufferValid.Write(util.ConvertUint64ToBytes(10000)) + bufferInvalidRequestType.Write(util.ConvertUint32ToBytes(10000)) + bufferInvalidRequestType.Write(util.ConvertUint64ToBytes(10000)) + bufferInvalidTimestamp.Write(util.ConvertUint32ToBytes(0)) + bufferInvalidTimestamp.Write(util.ConvertUint64ToBytes(0)) + validSignature := (&Signature{}).Sign( + bufferValid.Bytes(), + constant.NodeSignatureTypeDefault, + mockOwnerSeed, + ) + bufferValid.Write(validSignature) + mockValidAuth = hex.EncodeToString(bufferValid.Bytes()) + bufferValid.Write([]byte{1, 2}) + mockInvalidSignatureAuth = hex.EncodeToString(bufferValid.Bytes()) + mockInvalidTimestampAuth = hex.EncodeToString(bufferInvalidTimestamp.Bytes()) + mockInvalidRequestTypeAuth = hex.EncodeToString(bufferInvalidRequestType.Bytes()) +} + func TestVerifyAuthAPI(t *testing.T) { + setupVerifyAuthAPI() type args struct { ownerAddress string - auth *model.Auth + auth string requestType model.RequestType - signature crypto.SignatureInterface } - buffer := bytes.NewBuffer([]byte{}) - buffer.Write(ConvertUint32ToBytes(0)) - buffer.Write(ConvertUint64ToBytes(10000)) - validSignature := (&crypto.Signature{}).Sign( - buffer.Bytes(), - constant.NodeSignatureTypeDefault, - mockOwnerSeed, - ) tests := []struct { name string args args wantErr bool }{ + { + name: "VerifyAuthAPI:fail-invalid-auth", + args: args{ + ownerAddress: "", + auth: "XXXX", + requestType: 0, + }, + wantErr: true, + }, { name: "VerifyAuthAPI:fail-invalid-requestType", args: args{ ownerAddress: "", - auth: &model.Auth{ - RequestType: 1, - Timestamp: 0, - Signature: nil, - }, - requestType: 0, - signature: crypto.NewSignature(), + auth: mockInvalidRequestTypeAuth, + requestType: 0, }, wantErr: true, }, @@ -51,13 +80,8 @@ func TestVerifyAuthAPI(t *testing.T) { name: "VerifyAuthAPI:fail-invalid-timestamp", args: args{ ownerAddress: "", - auth: &model.Auth{ - RequestType: 0, - Timestamp: 0, - Signature: nil, - }, - requestType: 0, - signature: crypto.NewSignature(), + auth: mockInvalidTimestampAuth, + requestType: 0, }, wantErr: true, }, @@ -65,13 +89,8 @@ func TestVerifyAuthAPI(t *testing.T) { name: "VerifyAuthAPI:fail-invalid-signature", args: args{ ownerAddress: mockOwnerAddress, - auth: &model.Auth{ - RequestType: 0, - Timestamp: 1000, - Signature: []byte{0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0}, - }, - requestType: 0, - signature: crypto.NewSignature(), + auth: mockInvalidSignatureAuth, + requestType: 0, }, wantErr: true, }, @@ -79,13 +98,8 @@ func TestVerifyAuthAPI(t *testing.T) { name: "VerifyAuthAPI:success", args: args{ ownerAddress: mockOwnerAddress, - auth: &model.Auth{ - RequestType: 0, - Timestamp: 10000, - Signature: validSignature, - }, - requestType: 0, - signature: crypto.NewSignature(), + auth: mockValidAuth, + requestType: 0, }, wantErr: false, }, @@ -93,9 +107,10 @@ func TestVerifyAuthAPI(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if err := VerifyAuthAPI(tt.args.ownerAddress, tt.args.auth, - tt.args.requestType, tt.args.signature); (err != nil) != tt.wantErr { + tt.args.requestType); (err != nil) != tt.wantErr { t.Errorf("VerifyAuthAPI() error = %v, wantErr %v", err, tt.wantErr) } + LastRequestTimestamp = 0 }) } } From 2087644d972828f2475921abf41cde99816c5a08 Mon Sep 17 00:00:00 2001 From: andy-shi88 Date: Tue, 20 Aug 2019 16:07:51 +0800 Subject: [PATCH 15/20] #159 omit usage of Auth struct for validation, use hex string representation instead --- common/model/auth.pb.go | 76 +++-------------------------- common/model/nodeHardware.pb.go | 86 +++++++++++++++------------------ 2 files changed, 46 insertions(+), 116 deletions(-) diff --git a/common/model/auth.pb.go b/common/model/auth.pb.go index adfe6c20f..4e625181a 100644 --- a/common/model/auth.pb.go +++ b/common/model/auth.pb.go @@ -20,6 +20,7 @@ var _ = math.Inf // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package +// RequestType used to sign a node administration request type RequestType int32 const ( @@ -42,81 +43,20 @@ func (RequestType) EnumDescriptor() ([]byte, []int) { return fileDescriptor_50b87fa4d1f0d790, []int{0} } -type Auth struct { - RequestType RequestType `protobuf:"varint,1,opt,name=RequestType,proto3,enum=model.RequestType" json:"RequestType,omitempty"` - Timestamp uint64 `protobuf:"varint,2,opt,name=Timestamp,proto3" json:"Timestamp,omitempty"` - Signature []byte `protobuf:"bytes,3,opt,name=Signature,proto3" json:"Signature,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Auth) Reset() { *m = Auth{} } -func (m *Auth) String() string { return proto.CompactTextString(m) } -func (*Auth) ProtoMessage() {} -func (*Auth) Descriptor() ([]byte, []int) { - return fileDescriptor_50b87fa4d1f0d790, []int{0} -} - -func (m *Auth) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Auth.Unmarshal(m, b) -} -func (m *Auth) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Auth.Marshal(b, m, deterministic) -} -func (m *Auth) XXX_Merge(src proto.Message) { - xxx_messageInfo_Auth.Merge(m, src) -} -func (m *Auth) XXX_Size() int { - return xxx_messageInfo_Auth.Size(m) -} -func (m *Auth) XXX_DiscardUnknown() { - xxx_messageInfo_Auth.DiscardUnknown(m) -} - -var xxx_messageInfo_Auth proto.InternalMessageInfo - -func (m *Auth) GetRequestType() RequestType { - if m != nil { - return m.RequestType - } - return RequestType_GetNodeHardware -} - -func (m *Auth) GetTimestamp() uint64 { - if m != nil { - return m.Timestamp - } - return 0 -} - -func (m *Auth) GetSignature() []byte { - if m != nil { - return m.Signature - } - return nil -} - func init() { proto.RegisterEnum("model.RequestType", RequestType_name, RequestType_value) - proto.RegisterType((*Auth)(nil), "model.Auth") } func init() { proto.RegisterFile("model/auth.proto", fileDescriptor_50b87fa4d1f0d790) } var fileDescriptor_50b87fa4d1f0d790 = []byte{ - // 195 bytes of a gzipped FileDescriptorProto + // 124 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0xc8, 0xcd, 0x4f, 0x49, 0xcd, 0xd1, 0x4f, 0x2c, 0x2d, 0xc9, 0xd0, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x05, 0x8b, - 0x28, 0x55, 0x70, 0xb1, 0x38, 0x96, 0x96, 0x64, 0x08, 0x99, 0x70, 0x71, 0x07, 0xa5, 0x16, 0x96, - 0xa6, 0x16, 0x97, 0x84, 0x54, 0x16, 0xa4, 0x4a, 0x30, 0x2a, 0x30, 0x6a, 0xf0, 0x19, 0x09, 0xe9, - 0x81, 0x15, 0xe9, 0x21, 0xc9, 0x04, 0x21, 0x2b, 0x13, 0x92, 0xe1, 0xe2, 0x0c, 0xc9, 0xcc, 0x4d, - 0x2d, 0x2e, 0x49, 0xcc, 0x2d, 0x90, 0x60, 0x52, 0x60, 0xd4, 0x60, 0x09, 0x42, 0x08, 0x80, 0x64, - 0x83, 0x33, 0xd3, 0xf3, 0x12, 0x4b, 0x4a, 0x8b, 0x52, 0x25, 0x98, 0x15, 0x18, 0x35, 0x78, 0x82, - 0x10, 0x02, 0x5a, 0x4a, 0x28, 0x36, 0x0a, 0x09, 0x73, 0xf1, 0xbb, 0xa7, 0x96, 0xf8, 0xe5, 0xa7, - 0xa4, 0x7a, 0x24, 0x16, 0xa5, 0x94, 0x27, 0x16, 0xa5, 0x0a, 0x30, 0x38, 0x69, 0x45, 0x69, 0xa4, - 0x67, 0x96, 0x64, 0x94, 0x26, 0xe9, 0x25, 0xe7, 0xe7, 0xea, 0x57, 0xe5, 0xe7, 0x27, 0x25, 0x43, - 0x48, 0xdd, 0xe4, 0xfc, 0xa2, 0x54, 0xfd, 0xe4, 0xfc, 0xdc, 0xdc, 0xfc, 0x3c, 0x7d, 0xb0, 0x23, - 0x93, 0xd8, 0xc0, 0xfe, 0x32, 0x06, 0x04, 0x00, 0x00, 0xff, 0xff, 0xaf, 0x46, 0xb7, 0xd7, 0xeb, - 0x00, 0x00, 0x00, + 0x68, 0x29, 0x71, 0x71, 0x07, 0xa5, 0x16, 0x96, 0xa6, 0x16, 0x97, 0x84, 0x54, 0x16, 0xa4, 0x0a, + 0x09, 0x73, 0xf1, 0xbb, 0xa7, 0x96, 0xf8, 0xe5, 0xa7, 0xa4, 0x7a, 0x24, 0x16, 0xa5, 0x94, 0x27, + 0x16, 0xa5, 0x0a, 0x30, 0x38, 0x69, 0x45, 0x69, 0xa4, 0x67, 0x96, 0x64, 0x94, 0x26, 0xe9, 0x25, + 0xe7, 0xe7, 0xea, 0x57, 0xe5, 0xe7, 0x27, 0x25, 0x43, 0x48, 0xdd, 0xe4, 0xfc, 0xa2, 0x54, 0xfd, + 0xe4, 0xfc, 0xdc, 0xdc, 0xfc, 0x3c, 0x7d, 0xb0, 0x79, 0x49, 0x6c, 0x60, 0xd3, 0x8d, 0x01, 0x01, + 0x00, 0x00, 0xff, 0xff, 0x81, 0xae, 0x54, 0x43, 0x71, 0x00, 0x00, 0x00, } diff --git a/common/model/nodeHardware.pb.go b/common/model/nodeHardware.pb.go index 560846165..bf440768b 100644 --- a/common/model/nodeHardware.pb.go +++ b/common/model/nodeHardware.pb.go @@ -60,7 +60,6 @@ func (m *GetNodeHardwareResponse) GetNodeHardware() *NodeHardware { } type GetNodeHardwareRequest struct { - Auth *Auth `protobuf:"bytes,1,opt,name=Auth,proto3" json:"Auth,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` @@ -91,13 +90,6 @@ func (m *GetNodeHardwareRequest) XXX_DiscardUnknown() { var xxx_messageInfo_GetNodeHardwareRequest proto.InternalMessageInfo -func (m *GetNodeHardwareRequest) GetAuth() *Auth { - if m != nil { - return m.Auth - } - return nil -} - type NodeHardware struct { CPUInformation []*CPUInformation `protobuf:"bytes,1,rep,name=CPUInformation,proto3" json:"CPUInformation,omitempty"` MemoryInformation *MemoryInformation `protobuf:"bytes,2,opt,name=MemoryInformation,proto3" json:"MemoryInformation,omitempty"` @@ -526,44 +518,42 @@ func init() { func init() { proto.RegisterFile("model/nodeHardware.proto", fileDescriptor_ce967b26533b171c) } var fileDescriptor_ce967b26533b171c = []byte{ - // 611 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x54, 0xcd, 0x6e, 0xd3, 0x40, - 0x10, 0x96, 0x1d, 0xa7, 0xd4, 0x1b, 0xd4, 0x96, 0x05, 0x82, 0xa9, 0x90, 0x88, 0x7c, 0x40, 0x11, - 0x12, 0x89, 0x54, 0x24, 0x10, 0x07, 0x24, 0x4a, 0xab, 0xd2, 0x1c, 0xda, 0x46, 0x9b, 0xb6, 0x07, - 0x6e, 0x1b, 0x7b, 0xda, 0x58, 0xb2, 0xbd, 0x61, 0xbd, 0x06, 0xda, 0x67, 0xe0, 0x82, 0xe0, 0x09, - 0x78, 0x52, 0xb4, 0xb3, 0xdb, 0xc4, 0xb1, 0xc3, 0x85, 0x8b, 0x35, 0xdf, 0xfc, 0x7c, 0x3b, 0xf3, - 0xcd, 0xae, 0x49, 0x90, 0x89, 0x18, 0xd2, 0x61, 0x2e, 0x62, 0x38, 0xe6, 0x32, 0xfe, 0xc6, 0x25, - 0x0c, 0xe6, 0x52, 0x28, 0x41, 0xdb, 0x18, 0xd9, 0xdd, 0x31, 0x09, 0xbc, 0x54, 0x33, 0x13, 0x08, - 0x19, 0x79, 0xf2, 0x09, 0xd4, 0x69, 0xa5, 0x82, 0x41, 0x31, 0x17, 0x79, 0x01, 0xf4, 0x2d, 0xb9, - 0x5f, 0xf5, 0x07, 0x4e, 0xcf, 0xe9, 0x77, 0xf6, 0x1e, 0x0e, 0x90, 0x63, 0xb0, 0x52, 0xb2, 0x92, - 0x18, 0xbe, 0x23, 0xdd, 0x06, 0xe7, 0x97, 0x12, 0x0a, 0x45, 0x9f, 0x13, 0x6f, 0xbf, 0x54, 0x33, - 0x4b, 0xd5, 0xb1, 0x54, 0xda, 0xc5, 0x30, 0x10, 0xfe, 0x71, 0x57, 0x0f, 0xa5, 0xef, 0xc9, 0xd6, - 0xc1, 0xf8, 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, - 0xbf, 0x99, 0xc3, 0xe2, 0x12, 0x23, 0x5a, 0x36, 0xeb, 0xae, 0x6b, 0xb6, 0x55, 0x69, 0xf6, 0xbf, - 0xda, 0xf9, 0xf8, 0xf2, 0x73, 0xff, 0x3a, 0x51, 0xb3, 0x72, 0x3a, 0x88, 0x44, 0x36, 0xbc, 0x15, - 0x62, 0x1a, 0x99, 0xef, 0xab, 0x48, 0x48, 0x18, 0x46, 0x22, 0xcb, 0x44, 0x3e, 0xc4, 0xc7, 0x39, - 0xdd, 0xc0, 0xdf, 0xe6, 0xeb, 0xbf, 0x01, 0x00, 0x00, 0xff, 0xff, 0x8e, 0x0c, 0x65, 0x14, 0x6b, - 0x05, 0x00, 0x00, + // 586 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x54, 0x4d, 0xaf, 0xd2, 0x4c, + 0x14, 0x4e, 0x4b, 0xe1, 0xa5, 0xc3, 0x1b, 0xae, 0x8e, 0x8a, 0xd5, 0xb8, 0x20, 0x5d, 0x18, 0x62, + 0x22, 0x24, 0xd7, 0x44, 0x57, 0x26, 0x2a, 0x37, 0x78, 0x59, 0xf0, 0x91, 0xe1, 0x72, 0x17, 0xee, + 0x86, 0xf6, 0x5c, 0x68, 0xd2, 0x76, 0x70, 0x3a, 0xa8, 0xf0, 0x1b, 0xdc, 0x18, 0xfd, 0x05, 0xfe, + 0x52, 0x33, 0xa7, 0x05, 0x4a, 0x8b, 0x1b, 0x37, 0xcd, 0x79, 0xce, 0xc7, 0x33, 0xe7, 0x3c, 0x67, + 0xa6, 0xc4, 0x89, 0x84, 0x0f, 0x61, 0x2f, 0x16, 0x3e, 0x5c, 0x73, 0xe9, 0x7f, 0xe5, 0x12, 0xba, + 0x6b, 0x29, 0x94, 0xa0, 0x55, 0x8c, 0xb8, 0x8c, 0x3c, 0xfe, 0x08, 0x6a, 0x9c, 0x8b, 0x33, 0x48, + 0x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 0xc5, 0x62, 0x68, 0xeb, 0x1d, 0xbe, 0xff, 0xc2, 0x83, 0x90, 0x2f, 0x42, 0x40, 0x69, 0x2c, 0x76, + 0x74, 0xe8, 0x0a, 0xbd, 0x30, 0x54, 0xc4, 0x62, 0x68, 0x17, 0xf7, 0x5a, 0x2d, 0xed, 0xd5, 0xfd, + 0x6e, 0x9c, 0x7b, 0x4e, 0x78, 0x89, 0x93, 0x9b, 0xed, 0x1a, 0x0e, 0x97, 0x18, 0xd1, 0xb1, 0x59, + 0xf3, 0x5c, 0xb3, 0x95, 0x5c, 0xb3, 0xff, 0xd4, 0xce, 0x87, 0x17, 0x9f, 0x3a, 0xcb, 0x40, 0xad, + 0x36, 0x8b, 0xae, 0x27, 0xa2, 0xde, 0x4e, 0x88, 0x85, 0x97, 0x7e, 0x5f, 0x7a, 0x42, 0x42, 0xcf, + 0x13, 0x51, 0x24, 0xe2, 0x1e, 0x3e, 0xce, 0x45, 0x0d, 0x7f, 0x8e, 0xaf, 0xfe, 0x04, 0x00, 0x00, + 0xff, 0xff, 0x18, 0x0c, 0x98, 0x0b, 0x38, 0x05, 0x00, 0x00, } From b32fcd539f567d1b8b0250ddaadefaca8fc6b358 Mon Sep 17 00:00:00 2001 From: andy-shi88 Date: Tue, 20 Aug 2019 16:09:12 +0800 Subject: [PATCH 16/20] #159 move interceptor to interceptor package from util --- p2p/native/service/client.go | 3 ++- p2p/native/service/server.go | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/p2p/native/service/client.go b/p2p/native/service/client.go index 77bd87c3a..d86680128 100644 --- a/p2p/native/service/client.go +++ b/p2p/native/service/client.go @@ -2,6 +2,7 @@ package service import ( "context" + "github.com/zoobc/zoobc-core/common/interceptor" "sync" log "github.com/sirupsen/logrus" @@ -51,7 +52,7 @@ func NewPeerServiceClient() PeerServiceClientInterface { conn, err := grpc.Dial( nativeUtil.GetFullAddressPeer(destinationPeer), grpc.WithInsecure(), - grpc.WithUnaryInterceptor(util.NewClientInterceptor(apiLogger)), + grpc.WithUnaryInterceptor(interceptor.NewClientInterceptor(apiLogger)), ) if err != nil { return nil, err diff --git a/p2p/native/service/server.go b/p2p/native/service/server.go index 9a1ec1332..023917ef6 100644 --- a/p2p/native/service/server.go +++ b/p2p/native/service/server.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "github.com/zoobc/zoobc-core/common/interceptor" "net" log "github.com/sirupsen/logrus" @@ -62,7 +63,7 @@ func (ss *ServerService) StartListening(listener net.Listener) error { apiLogger.Info("P2P: Listening to grpc communication...") grpcServer := grpc.NewServer( - grpc.UnaryInterceptor(util.NewServerInterceptor(apiLogger)), + grpc.UnaryInterceptor(interceptor.NewServerInterceptor(apiLogger)), ) service.RegisterP2PCommunicationServer(grpcServer, ss) return grpcServer.Serve(listener) From a06215dca14499696c047e6740929a113d9d8d2c Mon Sep 17 00:00:00 2001 From: andy-shi88 Date: Tue, 20 Aug 2019 16:09:31 +0800 Subject: [PATCH 17/20] #159 move interceptor package --- common/interceptor/interceptor.go | 171 +++++++++++++ common/interceptor/interceptor_test.go | 323 +++++++++++++++++++++++++ 2 files changed, 494 insertions(+) create mode 100644 common/interceptor/interceptor.go create mode 100644 common/interceptor/interceptor_test.go diff --git a/common/interceptor/interceptor.go b/common/interceptor/interceptor.go new file mode 100644 index 000000000..fa1e94b88 --- /dev/null +++ b/common/interceptor/interceptor.go @@ -0,0 +1,171 @@ +package interceptor + +import ( + "context" + "fmt" + "github.com/zoobc/zoobc-core/common/blocker" + "github.com/zoobc/zoobc-core/common/crypto" + "github.com/zoobc/zoobc-core/common/model" + "google.golang.org/grpc/metadata" + "runtime" + "time" + + "github.com/sirupsen/logrus" + + "google.golang.org/grpc" +) + +/* +NewServerInterceptor function can use to inject middlewares like: + - `recover` + - `log` triggered + - validate `authentication` if needed +With `recover()` function can handle re-run the app while got panic or error +*/ +func NewServerInterceptor(logger *logrus.Logger) grpc.UnaryServerInterceptor { + return func( + ctx context.Context, + req interface{}, + info *grpc.UnaryServerInfo, + handler grpc.UnaryHandler, + ) (interface{}, error) { + var ( + errHandler error + resp interface{} + ) + start := time.Now() + fields := logrus.Fields{ + "method": info.FullMethod, + "time": start.String(), + } + + defer func() { + + fields["latency"] = fmt.Sprintf("%d ns", time.Since(start).Nanoseconds()) + err := recover() + if err != nil { + // get stack after panic called and perhaps its first error + _, file, line, _ := runtime.Caller(4) + fields["panic"] = fmt.Sprintf("%s %d", file, line) + } else if errHandler != nil { + fields["error"] = errHandler + } + + if logger != nil { + switch { + case err != nil: + logger.WithFields(fields).Error(fmt.Sprint(err)) + case errHandler != nil: + logger.WithFields(fields).Warning(errHandler) + default: + logger.WithFields(fields).Info("success") + } + } + }() + + resp, errHandler = handler(ctx, req) + return resp, errHandler + } +} + +/* +NewClientInterceptor function can use to inject using grpc client like: + - `recover` + - `log` triggered + - add access token if needed +With `recover()` function can handle re-run the app while got panic +*/ +func NewClientInterceptor(logger *logrus.Logger) grpc.UnaryClientInterceptor { + return func( + ctx context.Context, + method string, + req interface{}, + reply interface{}, + cc *grpc.ClientConn, + invoker grpc.UnaryInvoker, + opts ...grpc.CallOption, + ) error { + var ( + errInvoker error + ) + start := time.Now() + fields := logrus.Fields{ + "method": method, + "time": start.String(), + } + + defer func() { + fields["latency"] = fmt.Sprintf("%d ns", time.Since(start).Nanoseconds()) + err := recover() + if err != nil { + // get stack after panic called and perhaps its first error + _, file, line, _ := runtime.Caller(4) + fields["panic"] = fmt.Sprintf("%s %d", file, line) + } + if logger != nil { + switch { + case err != nil: + logger.WithFields(fields).Error(fmt.Sprint(err)) + case errInvoker != nil: + logger.WithFields(fields).Warning(fmt.Sprint(errInvoker)) + default: + logger.WithFields(fields).Info("success") + } + } + }() + errInvoker = invoker(ctx, method, req, reply, cc, opts...) + return errInvoker + } + +} + +/* +NewNodeAdminAuthStreamInterceptor +validate request against the destination service and the signature with the node owner +*/ +func NewNodeAdminAuthStreamInterceptor(ownerAddress string) grpc.StreamServerInterceptor { + return func( + srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler, + ) error { + var ( + errHandler error + requestType model.RequestType + ) + switch info.FullMethod { + case "/service.NodeHardwareService/GetNodeHardware": + requestType = model.RequestType_GetNodeHardware + default: + // unprotected service, by pass the auth checking + requestType = -1 + } + md, ok := metadata.FromIncomingContext(ss.Context()) + if !ok { + return blocker.NewBlocker( + blocker.AuthErr, + "metadata not provided", + ) + } + authSlice := md.Get("authorization") + if authSlice == nil { + return blocker.NewBlocker( + blocker.AuthErr, + "authorization metadata not provided", + ) + } + if requestType > -1 { + // validate request + // todo: this is verifying against whatever owner address is in the config file, update this + // todo: to follow how `claim` node work. + err := crypto.VerifyAuthAPI( + ownerAddress, + authSlice[0], + requestType) + if err != nil { + return err + } + } + + errHandler = handler(srv, ss) + return errHandler + } +} diff --git a/common/interceptor/interceptor_test.go b/common/interceptor/interceptor_test.go new file mode 100644 index 000000000..88e2d5340 --- /dev/null +++ b/common/interceptor/interceptor_test.go @@ -0,0 +1,323 @@ +package interceptor + +import ( + "bytes" + "context" + "encoding/hex" + "github.com/google/go-cmp/cmp" + "github.com/sirupsen/logrus" + "github.com/zoobc/zoobc-core/common/constant" + "github.com/zoobc/zoobc-core/common/crypto" + rpcModel "github.com/zoobc/zoobc-core/common/model" + "github.com/zoobc/zoobc-core/common/util" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/status" + "testing" + "time" +) + +var ( + mockOwnerAddress = "BCZEGOb3WNx3fDOVf9ZS4EjvOIv_UeW4TVBQJ_6tHKlE" + mockOwnerSeed = "concur vocalist rotten busload gap quote stinging undiluted surfer goofiness deviation starved" +) + +type ( + mockServerStreamSuccess struct{} + mockServerStreamNoAuth struct { + mockServerStreamSuccess + } + mockServerStreamNoMetadata struct { + mockServerStreamSuccess + } + mockServerStreamInvalidAuth struct { + mockServerStreamSuccess + } +) + +func (*mockServerStreamSuccess) SetHeader(metadata.MD) error { return nil } +func (*mockServerStreamSuccess) SendHeader(metadata.MD) error { return nil } +func (*mockServerStreamSuccess) SetTrailer(metadata.MD) {} +func (*mockServerStreamSuccess) Context() context.Context { + currentTime := uint64(time.Now().Unix()) + buffer := bytes.NewBuffer([]byte{}) + buffer.Write(util.ConvertUint32ToBytes(uint32(rpcModel.RequestType_GetNodeHardware))) + buffer.Write(util.ConvertUint64ToBytes(currentTime)) + sig := (crypto.NewSignature()).Sign( + buffer.Bytes(), + constant.NodeSignatureTypeDefault, + mockOwnerSeed, + ) + buffer.Write(sig) + ctx := context.Background() + md := metadata.Pairs("authorization", hex.EncodeToString(buffer.Bytes())) + ctx = metadata.NewIncomingContext(ctx, md) + return ctx +} +func (*mockServerStreamSuccess) SendMsg(m interface{}) error { return nil } +func (*mockServerStreamSuccess) RecvMsg(m interface{}) error { return nil } + +func (*mockServerStreamNoAuth) Context() context.Context { + ctx := context.Background() + md := metadata.Pairs("foo", "bar") + ctx = metadata.NewIncomingContext(ctx, md) + return ctx +} + +func (*mockServerStreamNoMetadata) Context() context.Context { + ctx := context.Background() + return ctx +} + +func (*mockServerStreamInvalidAuth) Context() context.Context { + // sign with invalid request type parameter + currentTime := uint64(time.Now().Unix()) + buffer := bytes.NewBuffer([]byte{}) + buffer.Write(util.ConvertUint32ToBytes(uint32(1435))) + buffer.Write(util.ConvertUint64ToBytes(currentTime)) + sig := (crypto.NewSignature()).Sign( + buffer.Bytes(), + constant.NodeSignatureTypeDefault, + mockOwnerSeed, + ) + buffer.Write(sig) + ctx := context.Background() + md := metadata.Pairs("authorization", hex.EncodeToString(buffer.Bytes())) + ctx = metadata.NewIncomingContext(ctx, md) + return ctx +} + +func TestNewServerInterceptor(t *testing.T) { + type args struct { + logger *logrus.Logger + } + tests := []struct { + name string + args args + want grpc.UnaryServerInterceptor + wantRecover bool + }{ + { + name: "wantRecover", + args: args{ + logger: logrus.New(), + }, + want: func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) { + return nil, status.Errorf(codes.Internal, "there's something wrong") + }, + wantRecover: true, + }, + { + name: "wantNotRecover", + args: args{ + logger: logrus.New(), + }, + want: func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) { + return nil, status.Errorf(codes.Internal, "there's something wrong") + }, + wantRecover: false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := NewServerInterceptor(tt.args.logger) + if cmp.Equal(got, tt.want) { + t.Errorf("NewInterceptor() = %v, want %v", got, tt.want) + } + testServerInterceptor(got, tt.wantRecover) + }) + } +} + +func testServerInterceptor(fn grpc.UnaryServerInterceptor, wantRecover bool) { + var ( + handler grpc.UnaryHandler + ) + if wantRecover { + handler = func(ctx context.Context, req interface{}) (resp interface{}, err error) { + panic(handler) + } + } else { + handler = func(ctx context.Context, req interface{}) (resp interface{}, err error) { + return nil, status.Errorf(codes.Internal, "there's something wrong") + } + } + _, _ = fn(context.Background(), nil, &grpc.UnaryServerInfo{}, handler) +} + +func TestNewClientInterceptor(t *testing.T) { + type args struct { + logger *logrus.Logger + } + tests := []struct { + name string + args args + want grpc.UnaryClientInterceptor + wantRecover bool + }{ + { + name: "wantRecover", + args: args{ + logger: logrus.New(), + }, + want: func( + ctx context.Context, + method string, + req, reply interface{}, + cc *grpc.ClientConn, + invoker grpc.UnaryInvoker, + opts ...grpc.CallOption) error { + return status.Errorf(codes.Internal, "there's something wrong") + }, + wantRecover: false, + }, + { + name: "wantRecover", + args: args{ + logger: logrus.New(), + }, + want: func( + ctx context.Context, + method string, + req, reply interface{}, + cc *grpc.ClientConn, + invoker grpc.UnaryInvoker, + opts ...grpc.CallOption) error { + return status.Errorf(codes.Internal, "there's something wrong") + }, + wantRecover: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := NewClientInterceptor(tt.args.logger) + if cmp.Equal(got, tt.want) { + t.Errorf("NewClientInterceptor() = %v, want %v", got, tt.want) + } + testClientInterceptor(got, tt.wantRecover) + }) + } +} + +func testClientInterceptor(fn grpc.UnaryClientInterceptor, wantRecover bool) { + var ( + invoker grpc.UnaryInvoker + ) + if wantRecover { + invoker = func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, opts ...grpc.CallOption) error { + panic(invoker) + } + } else { + invoker = func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, opts ...grpc.CallOption) error { + return status.Errorf(codes.Internal, "there's something wrong") + } + } + + cc, _ := grpc.Dial("127.0.0.1:8001", grpc.WithInsecure()) + _ = fn(context.Background(), "testMethod", nil, nil, cc, invoker, nil) + +} + +func TestNewNodeAdminAuthStreamInterceptor(t *testing.T) { + + type args struct { + ownerAddress string + fullMethod string + handler grpc.StreamHandler + serverStream grpc.ServerStream + } + tests := []struct { + name string + args args + want grpc.StreamServerInterceptor + wantInnerErr bool + }{ + { + name: "wantErr:noMetadata", + args: args{ + ownerAddress: mockOwnerAddress, + fullMethod: "/service.NodeHardwareService/GetNodeHardware", + serverStream: &mockServerStreamNoMetadata{}, + }, + want: func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) (err error) { + return nil + }, + wantInnerErr: true, + }, + { + name: "wantErr:noAuth", + args: args{ + ownerAddress: mockOwnerAddress, + fullMethod: "/service.NodeHardwareService/GetNodeHardware", + serverStream: &mockServerStreamNoAuth{}, + }, + want: func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) (err error) { + return nil + }, + wantInnerErr: true, + }, + { + name: "wantSuccess:GetNodeHardware", + args: args{ + ownerAddress: mockOwnerAddress, + fullMethod: "/service.NodeHardwareService/GetNodeHardware", + serverStream: &mockServerStreamSuccess{}, + handler: func(srv interface{}, stream grpc.ServerStream) error { + return nil + }, + }, + want: func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) (err error) { + return nil + }, + wantInnerErr: false, + }, + { + name: "wantFail:invalidSignature", + args: args{ + ownerAddress: mockOwnerAddress, + fullMethod: "/service.NodeHardwareService/GetNodeHardware", + serverStream: &mockServerStreamInvalidAuth{}, + handler: func(srv interface{}, stream grpc.ServerStream) error { + return nil + }, + }, + want: func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) (err error) { + return nil + }, + wantInnerErr: true, + }, + { + name: "wantSuccess:unprotectedService", + args: args{ + ownerAddress: mockOwnerAddress, + fullMethod: "/nonProtectedService", + serverStream: &mockServerStreamSuccess{}, + handler: func(srv interface{}, stream grpc.ServerStream) error { + return nil + }, + }, + want: func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) (err error) { + return nil + }, + wantInnerErr: false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := NewNodeAdminAuthStreamInterceptor(tt.args.ownerAddress) + if cmp.Equal(got, tt.want) { + t.Errorf("NewInterceptor() = %v, want %v", got, tt.want) + } + info := &grpc.StreamServerInfo{ + FullMethod: tt.args.fullMethod, + IsClientStream: true, + IsServerStream: true, + } + err := got(nil, tt.args.serverStream, info, tt.args.handler) + if err != nil && tt.wantInnerErr != true { + t.Error("unexpected error occurred") + } + }) + } +} From 0b802aa467eb02fcb6aa2c7fceb05716a59bc57a Mon Sep 17 00:00:00 2001 From: andy-shi88 Date: Tue, 20 Aug 2019 16:10:19 +0800 Subject: [PATCH 18/20] #159 update schema commit --- common/schema | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/common/schema b/common/schema index e58346b7f..db79488ee 160000 --- a/common/schema +++ b/common/schema @@ -1 +1 @@ -Subproject commit e58346b7fcfb50d3dea14b97d1032cb371b9376a +Subproject commit db79488ee35114272ae0e9ad2d51c1783d3b8c68 From f68f4151da32b57dd2d4182ad9fde90a12cadb88 Mon Sep 17 00:00:00 2001 From: andy-shi88 Date: Tue, 20 Aug 2019 16:20:19 +0800 Subject: [PATCH 19/20] #159 initate zoobc postman collection --- ZooBC.postman_collection.json | 90 +++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 ZooBC.postman_collection.json diff --git a/ZooBC.postman_collection.json b/ZooBC.postman_collection.json new file mode 100644 index 000000000..54f8e6f6a --- /dev/null +++ b/ZooBC.postman_collection.json @@ -0,0 +1,90 @@ +{ + "info": { + "_postman_id": "e8cb55b1-5c13-4894-8106-52f4bf019eee", + "name": "ZooBC", + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" + }, + "item": [ + { + "name": "blocks", + "item": [ + { + "name": "GetBlocks", + "request": { + "method": "GET", + "header": [], + "body": { + "mode": "raw", + "raw": "" + }, + "url": { + "raw": "{{host}}/v1/block/GetBlocks?Limit=10&Height=0&Chaintype=0", + "host": [ + "{{host}}" + ], + "path": [ + "v1", + "block", + "GetBlocks" + ], + "query": [ + { + "key": "Limit", + "value": "10" + }, + { + "key": "Height", + "value": "0" + }, + { + "key": "Chaintype", + "value": "0" + } + ] + } + }, + "response": [] + }, + { + "name": "GetBlock", + "request": { + "method": "GET", + "header": [], + "body": { + "mode": "raw", + "raw": "" + }, + "url": { + "raw": "{{host}}/v1/block/GetBlock?ID=-8826204794314169398", + "host": [ + "{{host}}" + ], + "path": [ + "v1", + "block", + "GetBlock" + ], + "query": [ + { + "key": "ID", + "value": "-8826204794314169398" + }, + { + "key": "Height", + "value": "20", + "disabled": true + }, + { + "key": "Chaintype", + "value": "0", + "disabled": true + } + ] + } + }, + "response": [] + } + ] + } + ] +} \ No newline at end of file From 03bdc96356c6e2761010cca8ae2af2fdcd4765e9 Mon Sep 17 00:00:00 2001 From: andy-shi88 Date: Tue, 20 Aug 2019 17:13:56 +0800 Subject: [PATCH 20/20] #159 rename interceptor --- api/api.go | 2 +- common/interceptor/interceptor.go | 4 ++-- common/interceptor/interceptor_test.go | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/api/api.go b/api/api.go index 41d62fdb9..3e65f70b6 100644 --- a/api/api.go +++ b/api/api.go @@ -40,7 +40,7 @@ func startGrpcServer(port int, queryExecutor query.ExecutorInterface, p2pHostSer blockServices map[int32]coreService.BlockServiceInterface, ownerAccountAddress string) { grpcServer := grpc.NewServer( grpc.UnaryInterceptor(interceptor.NewServerInterceptor(apiLogger)), - grpc.StreamInterceptor(interceptor.NewNodeAdminAuthStreamInterceptor(ownerAccountAddress)), + grpc.StreamInterceptor(interceptor.NewStreamInterceptor(ownerAccountAddress)), ) actionTypeSwitcher := &transaction.TypeSwitcher{ Executor: queryExecutor, diff --git a/common/interceptor/interceptor.go b/common/interceptor/interceptor.go index fa1e94b88..47a9c0c50 100644 --- a/common/interceptor/interceptor.go +++ b/common/interceptor/interceptor.go @@ -120,10 +120,10 @@ func NewClientInterceptor(logger *logrus.Logger) grpc.UnaryClientInterceptor { } /* -NewNodeAdminAuthStreamInterceptor +NewStreamInterceptor validate request against the destination service and the signature with the node owner */ -func NewNodeAdminAuthStreamInterceptor(ownerAddress string) grpc.StreamServerInterceptor { +func NewStreamInterceptor(ownerAddress string) grpc.StreamServerInterceptor { return func( srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler, ) error { diff --git a/common/interceptor/interceptor_test.go b/common/interceptor/interceptor_test.go index 88e2d5340..1f920f912 100644 --- a/common/interceptor/interceptor_test.go +++ b/common/interceptor/interceptor_test.go @@ -305,7 +305,7 @@ func TestNewNodeAdminAuthStreamInterceptor(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - got := NewNodeAdminAuthStreamInterceptor(tt.args.ownerAddress) + got := NewStreamInterceptor(tt.args.ownerAddress) if cmp.Equal(got, tt.want) { t.Errorf("NewInterceptor() = %v, want %v", got, tt.want) }