This commit is contained in:
number571 2023-03-21 10:54:05 +07:00
parent ac36e6d3db
commit 73c686ef6c
45 changed files with 1442 additions and 1435 deletions

View File

@ -21,7 +21,7 @@ The `go-peer` library contains a large number of functions necessary to ensure t
1. Append comments for functions/variables/constants/etc (doc)
2. Append benchmarks
3. Write tests for coverage > 70%
4. Arguments with prefix 'a'
4. Arguments with prefix 'p'
5. Develop union_blockchain
6. Rename functions in crypto package (Get,Set,...)

View File

@ -27,10 +27,10 @@ type sClient struct {
// Create client by private key as identification.
// Handle function is used when the network exists.
func NewClient(sett ISettings, priv asymmetric.IPrivKey) IClient {
func NewClient(pSett ISettings, pPrivKey asymmetric.IPrivKey) IClient {
client := &sClient{
fSettings: sett,
fPrivKey: priv,
fSettings: pSett,
fPrivKey: pPrivKey,
}
msg := client.encryptWithParams(
client.GetPubKey(),
@ -46,30 +46,30 @@ func NewClient(sett ISettings, priv asymmetric.IPrivKey) IClient {
}
// Get public key from client object.
func (client *sClient) GetPubKey() asymmetric.IPubKey {
return client.GetPrivKey().GetPubKey()
func (p *sClient) GetPubKey() asymmetric.IPubKey {
return p.GetPrivKey().GetPubKey()
}
// Get private key from client object.
func (client *sClient) GetPrivKey() asymmetric.IPrivKey {
return client.fPrivKey
func (p *sClient) GetPrivKey() asymmetric.IPrivKey {
return p.fPrivKey
}
// Get settings from client object.
func (client *sClient) GetSettings() ISettings {
return client.fSettings
func (p *sClient) GetSettings() ISettings {
return p.fSettings
}
// Encrypt message with public key of receiver.
// The message can be decrypted only if private key is known.
func (client *sClient) EncryptPayload(receiver asymmetric.IPubKey, pld payload.IPayload) (message.IMessage, error) {
if receiver.GetSize() != client.GetPubKey().GetSize() {
func (p *sClient) EncryptPayload(pRecv asymmetric.IPubKey, pPld payload.IPayload) (message.IMessage, error) {
if pRecv.GetSize() != p.GetPubKey().GetSize() {
return nil, fmt.Errorf("size of public keys sender and receiver not equal")
}
var (
maxMsgSize = client.GetSettings().GetMessageSize() >> 1 // limit of bytes without hex
resultSize = uint64(client.fVoidMsgSize) + uint64(len(pld.ToBytes()))
maxMsgSize = p.GetSettings().GetMessageSize() >> 1 // limit of bytes without hex
resultSize = uint64(p.fVoidMsgSize) + uint64(len(pPld.ToBytes()))
)
if resultSize > maxMsgSize {
@ -80,28 +80,28 @@ func (client *sClient) EncryptPayload(receiver asymmetric.IPubKey, pld payload.I
)
}
return client.encryptWithParams(
receiver,
pld,
client.GetSettings().GetWorkSize(),
return p.encryptWithParams(
pRecv,
pPld,
p.GetSettings().GetWorkSize(),
maxMsgSize-resultSize,
), nil
}
func (client *sClient) encryptWithParams(receiver asymmetric.IPubKey, pld payload.IPayload, workSize, addPadd uint64) message.IMessage {
func (p *sClient) encryptWithParams(pRecv asymmetric.IPubKey, pPld payload.IPayload, pWorkSize, pPadd uint64) message.IMessage {
var (
rand = random.NewStdPRNG()
salt = rand.GetBytes(symmetric.CAESKeySize)
session = rand.GetBytes(symmetric.CAESKeySize)
)
payloadBytes := pld.ToBytes()
payloadBytes := pPld.ToBytes()
doublePayload := payload.NewPayload(
uint64(len(payloadBytes)),
bytes.Join(
[][]byte{
payloadBytes,
rand.GetBytes(addPadd),
rand.GetBytes(pPadd),
},
[]byte{},
),
@ -109,25 +109,25 @@ func (client *sClient) encryptWithParams(receiver asymmetric.IPubKey, pld payloa
hash := hashing.NewHMACSHA256Hasher(salt, bytes.Join(
[][]byte{
client.GetPubKey().GetAddress().ToBytes(),
receiver.GetAddress().ToBytes(),
p.GetPubKey().GetAddress().ToBytes(),
pRecv.GetAddress().ToBytes(),
doublePayload.ToBytes(),
},
[]byte{},
)).ToBytes()
cipher := symmetric.NewAESCipher(session)
bProof := encoding.Uint64ToBytes(puzzle.NewPoWPuzzle(workSize).ProofBytes(hash))
bProof := encoding.Uint64ToBytes(puzzle.NewPoWPuzzle(pWorkSize).ProofBytes(hash))
return &message.SMessage{
FHead: message.SHeadMessage{
FSender: encoding.HexEncode(cipher.EncryptBytes(client.GetPubKey().ToBytes())),
FSession: encoding.HexEncode(receiver.EncryptBytes(session)),
FSender: encoding.HexEncode(cipher.EncryptBytes(p.GetPubKey().ToBytes())),
FSession: encoding.HexEncode(pRecv.EncryptBytes(session)),
FSalt: encoding.HexEncode(cipher.EncryptBytes(salt)),
},
FBody: message.SBodyMessage{
FPayload: encoding.HexEncode(cipher.EncryptBytes(doublePayload.ToBytes())),
FHash: encoding.HexEncode(hash),
FSign: encoding.HexEncode(cipher.EncryptBytes(client.GetPrivKey().SignBytes(hash))),
FSign: encoding.HexEncode(cipher.EncryptBytes(p.GetPrivKey().SignBytes(hash))),
FProof: encoding.HexEncode(bProof[:]),
},
}
@ -135,32 +135,32 @@ func (client *sClient) encryptWithParams(receiver asymmetric.IPubKey, pld payloa
// Decrypt message with private key of receiver.
// No one else except the sender will be able to decrypt the message.
func (client *sClient) DecryptMessage(msg message.IMessage) (asymmetric.IPubKey, payload.IPayload, error) {
if msg == nil {
func (p *sClient) DecryptMessage(pMsg message.IMessage) (asymmetric.IPubKey, payload.IPayload, error) {
if pMsg == nil {
return nil, nil, fmt.Errorf("msg is nil")
}
// Initial check.
if len(msg.GetBody().GetHash()) != hashing.CSHA256Size {
if len(pMsg.GetBody().GetHash()) != hashing.CSHA256Size {
return nil, nil, fmt.Errorf("msg hash != sha256 size")
}
// Proof of work. Prevent spam.
diff := client.GetSettings().GetWorkSize()
diff := p.GetSettings().GetWorkSize()
puzzle := puzzle.NewPoWPuzzle(diff)
if !puzzle.VerifyBytes(msg.GetBody().GetHash(), msg.GetBody().GetProof()) {
if !puzzle.VerifyBytes(pMsg.GetBody().GetHash(), pMsg.GetBody().GetProof()) {
return nil, nil, fmt.Errorf("invalid proof of msg")
}
// Decrypt session key by private key of receiver.
session := client.GetPrivKey().DecryptBytes(msg.GetHead().GetSession())
session := p.GetPrivKey().DecryptBytes(pMsg.GetHead().GetSession())
if session == nil {
return nil, nil, fmt.Errorf("failed decrypt session key")
}
// Decrypt public key of sender by decrypted session key.
cipher := symmetric.NewAESCipher(session)
publicBytes := cipher.DecryptBytes(msg.GetHead().GetSender())
publicBytes := cipher.DecryptBytes(pMsg.GetHead().GetSender())
if publicBytes == nil {
return nil, nil, fmt.Errorf("failed decrypt public key")
}
@ -170,12 +170,12 @@ func (client *sClient) DecryptMessage(msg message.IMessage) (asymmetric.IPubKey,
if pubKey == nil {
return nil, nil, fmt.Errorf("failed load public key")
}
if pubKey.GetSize() != client.GetPubKey().GetSize() {
if pubKey.GetSize() != p.GetPubKey().GetSize() {
return nil, nil, fmt.Errorf("invalid public key size")
}
// Decrypt main data of message by session key.
doublePayloadBytes := cipher.DecryptBytes(msg.GetBody().GetPayload().ToBytes())
doublePayloadBytes := cipher.DecryptBytes(pMsg.GetBody().GetPayload().ToBytes())
if doublePayloadBytes == nil {
return nil, nil, fmt.Errorf("failed decrypt double payload")
}
@ -185,7 +185,7 @@ func (client *sClient) DecryptMessage(msg message.IMessage) (asymmetric.IPubKey,
}
// Decrypt salt.
salt := cipher.DecryptBytes(msg.GetHead().GetSalt())
salt := cipher.DecryptBytes(pMsg.GetHead().GetSalt())
if salt == nil {
return nil, nil, fmt.Errorf("failed decrypt salt")
}
@ -194,22 +194,22 @@ func (client *sClient) DecryptMessage(msg message.IMessage) (asymmetric.IPubKey,
check := hashing.NewHMACSHA256Hasher(salt, bytes.Join(
[][]byte{
pubKey.GetAddress().ToBytes(),
client.GetPubKey().GetAddress().ToBytes(),
p.GetPubKey().GetAddress().ToBytes(),
doublePayload.ToBytes(),
},
[]byte{},
)).ToBytes()
if !bytes.Equal(check, msg.GetBody().GetHash()) {
if !bytes.Equal(check, pMsg.GetBody().GetHash()) {
return nil, nil, fmt.Errorf("invalid msg hash")
}
// Decrypt sign of message and verify this
// by public key of sender and hash of message.
sign := cipher.DecryptBytes(msg.GetBody().GetSign())
sign := cipher.DecryptBytes(pMsg.GetBody().GetSign())
if sign == nil {
return nil, nil, fmt.Errorf("failed decrypt sign")
}
if !pubKey.VerifyBytes(msg.GetBody().GetHash(), sign) {
if !pubKey.VerifyBytes(pMsg.GetBody().GetHash(), sign) {
return nil, nil, fmt.Errorf("invalid msg sign")
}

View File

@ -35,74 +35,74 @@ type SBodyMessage struct {
}
// Message can be created only with client module.
func LoadMessage(bmsg []byte, params IParams) IMessage {
func LoadMessage(pMsg []byte, pParams IParams) IMessage {
msg := new(SMessage)
if err := json.Unmarshal(bmsg, msg); err != nil {
if err := json.Unmarshal(pMsg, msg); err != nil {
return nil
}
if !msg.IsValid(params) {
if !msg.IsValid(pParams) {
return nil
}
return msg
}
func (msg *SMessage) GetHead() IHead {
return msg.FHead
func (p *SMessage) GetHead() IHead {
return p.FHead
}
func (msg *SMessage) GetBody() IBody {
return msg.FBody
func (p *SMessage) GetBody() IBody {
return p.FBody
}
func (msg *SMessage) ToBytes() []byte {
jsonData, err := json.Marshal(msg)
func (p *SMessage) ToBytes() []byte {
jsonData, err := json.Marshal(p)
if err != nil {
return nil
}
return jsonData
}
func (msg *SMessage) IsValid(params IParams) bool {
if uint64(len(msg.ToBytes())) > params.GetMessageSize() {
func (p *SMessage) IsValid(pParams IParams) bool {
if uint64(len(p.ToBytes())) > pParams.GetMessageSize() {
return false
}
if len(msg.GetBody().GetHash()) != hashing.CSHA256Size {
if len(p.GetBody().GetHash()) != hashing.CSHA256Size {
return false
}
puzzle := puzzle.NewPoWPuzzle(params.GetWorkSize())
return puzzle.VerifyBytes(msg.GetBody().GetHash(), msg.GetBody().GetProof())
puzzle := puzzle.NewPoWPuzzle(pParams.GetWorkSize())
return puzzle.VerifyBytes(p.GetBody().GetHash(), p.GetBody().GetProof())
}
// IHead
func (head SHeadMessage) GetSender() []byte {
return encoding.HexDecode(head.FSender)
func (p SHeadMessage) GetSender() []byte {
return encoding.HexDecode(p.FSender)
}
func (head SHeadMessage) GetSession() []byte {
return encoding.HexDecode(head.FSession)
func (p SHeadMessage) GetSession() []byte {
return encoding.HexDecode(p.FSession)
}
func (head SHeadMessage) GetSalt() []byte {
return encoding.HexDecode(head.FSalt)
func (p SHeadMessage) GetSalt() []byte {
return encoding.HexDecode(p.FSalt)
}
// IBody
func (body SBodyMessage) GetPayload() payload.IPayload {
return payload.LoadPayload(encoding.HexDecode(body.FPayload))
func (p SBodyMessage) GetPayload() payload.IPayload {
return payload.LoadPayload(encoding.HexDecode(p.FPayload))
}
func (body SBodyMessage) GetHash() []byte {
return encoding.HexDecode(body.FHash)
func (p SBodyMessage) GetHash() []byte {
return encoding.HexDecode(p.FHash)
}
func (body SBodyMessage) GetSign() []byte {
return encoding.HexDecode(body.FSign)
func (p SBodyMessage) GetSign() []byte {
return encoding.HexDecode(p.FSign)
}
func (body SBodyMessage) GetProof() uint64 {
bProof := encoding.HexDecode(body.FProof)
func (p SBodyMessage) GetProof() uint64 {
bProof := encoding.HexDecode(p.FProof)
if len(bProof) != encoding.CSizeUint64 {
return 0
}

View File

@ -9,10 +9,10 @@ type sParams struct {
fWorkSize uint64
}
func NewParams(msgSize, workSize uint64) IParams {
func NewParams(pMsgSize, pWorkSize uint64) IParams {
return &sParams{
fMessageSize: msgSize,
fWorkSize: workSize,
fMessageSize: pMsgSize,
fWorkSize: pWorkSize,
}
}

View File

@ -28,57 +28,57 @@ type sPull struct {
fQueue chan message.IMessage
}
func NewMessageQueue(sett ISettings, client client.IClient) IMessageQueue {
func NewMessageQueue(pSett ISettings, pClient client.IClient) IMessageQueue {
return &sMessageQueue{
fSettings: sett,
fClient: client,
fQueue: make(chan message.IMessage, sett.GetCapacity()),
fSettings: pSett,
fClient: pClient,
fQueue: make(chan message.IMessage, pSett.GetCapacity()),
fMsgPull: sPull{
fQueue: make(chan message.IMessage, sett.GetPullCapacity()),
fQueue: make(chan message.IMessage, pSett.GetPullCapacity()),
},
}
}
func (q *sMessageQueue) GetSettings() ISettings {
return q.fSettings
func (p *sMessageQueue) GetSettings() ISettings {
return p.fSettings
}
func (q *sMessageQueue) UpdateClient(c client.IClient) {
q.fMutex.Lock()
defer q.fMutex.Unlock()
func (p *sMessageQueue) UpdateClient(pClient client.IClient) {
p.fMutex.Lock()
defer p.fMutex.Unlock()
q.fClient = c
q.fQueue = make(chan message.IMessage, q.GetSettings().GetCapacity())
p.fClient = pClient
p.fQueue = make(chan message.IMessage, p.GetSettings().GetCapacity())
}
func (q *sMessageQueue) GetClient() client.IClient {
q.fMutex.Lock()
defer q.fMutex.Unlock()
func (p *sMessageQueue) GetClient() client.IClient {
p.fMutex.Lock()
defer p.fMutex.Unlock()
return q.fClient
return p.fClient
}
func (q *sMessageQueue) Run() error {
q.fMutex.Lock()
defer q.fMutex.Unlock()
func (p *sMessageQueue) Run() error {
p.fMutex.Lock()
defer p.fMutex.Unlock()
if q.fIsRun {
if p.fIsRun {
return errors.New("queue already running")
}
q.fIsRun = true
p.fIsRun = true
q.fMsgPull.fSignal = make(chan struct{})
p.fMsgPull.fSignal = make(chan struct{})
go func() {
for {
select {
case <-q.readSignal():
case <-p.readSignal():
return
case <-time.After(q.GetSettings().GetDuration() / 2):
currLen := len(q.fMsgPull.fQueue)
if uint64(currLen) >= q.GetSettings().GetPullCapacity() {
case <-time.After(p.GetSettings().GetDuration() / 2):
currLen := len(p.fMsgPull.fQueue)
if uint64(currLen) >= p.GetSettings().GetPullCapacity() {
continue
}
q.fMsgPull.fQueue <- q.newPseudoMessage()
p.fMsgPull.fQueue <- p.newPseudoMessage()
}
}
}()
@ -86,45 +86,45 @@ func (q *sMessageQueue) Run() error {
return nil
}
func (q *sMessageQueue) Stop() error {
q.fMutex.Lock()
defer q.fMutex.Unlock()
func (p *sMessageQueue) Stop() error {
p.fMutex.Lock()
defer p.fMutex.Unlock()
if !q.fIsRun {
if !p.fIsRun {
return errors.New("queue already closed or not started")
}
q.fIsRun = false
p.fIsRun = false
close(q.fMsgPull.fSignal)
close(p.fMsgPull.fSignal)
return nil
}
func (q *sMessageQueue) EnqueueMessage(msg message.IMessage) error {
q.fMutex.Lock()
defer q.fMutex.Unlock()
func (p *sMessageQueue) EnqueueMessage(pMsg message.IMessage) error {
p.fMutex.Lock()
defer p.fMutex.Unlock()
if uint64(len(q.fQueue)) >= q.GetSettings().GetCapacity() {
if uint64(len(p.fQueue)) >= p.GetSettings().GetCapacity() {
return errors.New("queue already full, need wait and retry")
}
q.fQueue <- msg
p.fQueue <- pMsg
return nil
}
func (q *sMessageQueue) DequeueMessage() <-chan message.IMessage {
func (p *sMessageQueue) DequeueMessage() <-chan message.IMessage {
closed := make(chan bool)
go func() {
select {
case <-q.readSignal():
case <-p.readSignal():
closed <- true
return
case <-time.After(q.GetSettings().GetDuration()):
q.fMutex.Lock()
defer q.fMutex.Unlock()
case <-time.After(p.GetSettings().GetDuration()):
p.fMutex.Lock()
defer p.fMutex.Unlock()
if len(q.fQueue) == 0 {
q.fQueue <- (<-q.fMsgPull.fQueue)
if len(p.fQueue) == 0 {
p.fQueue <- (<-p.fMsgPull.fQueue)
}
closed <- false
}
@ -136,12 +136,12 @@ func (q *sMessageQueue) DequeueMessage() <-chan message.IMessage {
return queue
}
return q.fQueue
return p.fQueue
}
func (q *sMessageQueue) newPseudoMessage() message.IMessage {
msg, err := q.GetClient().EncryptPayload(
q.GetClient().GetPubKey(),
func (p *sMessageQueue) newPseudoMessage() message.IMessage {
msg, err := p.GetClient().EncryptPayload(
p.GetClient().GetPubKey(),
payload.NewPayload(0, []byte{1}),
)
if err != nil {
@ -150,9 +150,9 @@ func (q *sMessageQueue) newPseudoMessage() message.IMessage {
return msg
}
func (q *sMessageQueue) readSignal() <-chan struct{} {
q.fMutex.Lock()
defer q.fMutex.Unlock()
func (p *sMessageQueue) readSignal() <-chan struct{} {
p.fMutex.Lock()
defer p.fMutex.Unlock()
return q.fMsgPull.fSignal
return p.fMsgPull.fSignal
}

View File

@ -21,35 +21,35 @@ type sSettings struct {
FDuration time.Duration
}
func NewSettings(sett *SSettings) ISettings {
func NewSettings(pSett *SSettings) ISettings {
return (&sSettings{
FCapacity: sett.FCapacity,
FPullCapacity: sett.FPullCapacity,
FDuration: sett.FDuration,
FCapacity: pSett.FCapacity,
FPullCapacity: pSett.FPullCapacity,
FDuration: pSett.FDuration,
}).useDefaultValues()
}
func (s *sSettings) useDefaultValues() ISettings {
if s.FCapacity == 0 {
s.FCapacity = cCapacity
func (p *sSettings) useDefaultValues() ISettings {
if p.FCapacity == 0 {
p.FCapacity = cCapacity
}
if s.FPullCapacity == 0 {
s.FPullCapacity = cPullCapacity
if p.FPullCapacity == 0 {
p.FPullCapacity = cPullCapacity
}
if s.FDuration == 0 {
s.FDuration = cDuration
if p.FDuration == 0 {
p.FDuration = cDuration
}
return s
return p
}
func (s *sSettings) GetCapacity() uint64 {
return s.FCapacity
func (p *sSettings) GetCapacity() uint64 {
return p.FCapacity
}
func (s *sSettings) GetPullCapacity() uint64 {
return s.FPullCapacity
func (p *sSettings) GetPullCapacity() uint64 {
return p.FPullCapacity
}
func (s *sSettings) GetDuration() time.Duration {
return s.FDuration
func (p *sSettings) GetDuration() time.Duration {
return p.FDuration
}

View File

@ -15,27 +15,27 @@ type sSettings struct {
FMessageSize uint64
}
func NewSettings(sett *SSettings) ISettings {
func NewSettings(pSett *SSettings) ISettings {
return (&sSettings{
FWorkSize: sett.FWorkSize,
FMessageSize: sett.FMessageSize,
FWorkSize: pSett.FWorkSize,
FMessageSize: pSett.FMessageSize,
}).useDefaultValues()
}
func (s *sSettings) useDefaultValues() ISettings {
if s.FWorkSize == 0 {
s.FWorkSize = cWorkSize
func (p *sSettings) useDefaultValues() ISettings {
if p.FWorkSize == 0 {
p.FWorkSize = cWorkSize
}
if s.FMessageSize == 0 {
s.FMessageSize = cMessageSize
if p.FMessageSize == 0 {
p.FMessageSize = cMessageSize
}
return s
return p
}
func (s *sSettings) GetWorkSize() uint64 {
return s.FWorkSize
func (p *sSettings) GetWorkSize() uint64 {
return p.FWorkSize
}
func (s *sSettings) GetMessageSize() uint64 {
return s.FMessageSize
func (p *sSettings) GetMessageSize() uint64 {
return p.FMessageSize
}

View File

@ -39,24 +39,24 @@ type sRSAPrivKey struct {
fPrivKey *rsa.PrivateKey
}
func newPrivKey(privKey *rsa.PrivateKey) IPrivKey {
func newPrivKey(pPrivKey *rsa.PrivateKey) IPrivKey {
return &sRSAPrivKey{
fPubKey: newPubKey(&privKey.PublicKey),
fPrivKey: privKey,
fPubKey: newPubKey(&pPrivKey.PublicKey),
fPrivKey: pPrivKey,
}
}
// Create private key by number of bits.
func NewRSAPrivKey(bits uint64) IPrivKey {
privKey, err := rsa.GenerateKey(rand.Reader, int(bits))
func NewRSAPrivKey(pBits uint64) IPrivKey {
privKey, err := rsa.GenerateKey(rand.Reader, int(pBits))
if err != nil {
return nil
}
return newPrivKey(privKey)
}
func LoadRSAPrivKey(typePrivKey interface{}) IPrivKey {
switch x := typePrivKey.(type) {
func LoadRSAPrivKey(pPrivKey interface{}) IPrivKey {
switch x := pPrivKey.(type) {
case []byte:
privKey := bytesToPrivateKey(x)
if privKey == nil {
@ -90,37 +90,37 @@ func LoadRSAPrivKey(typePrivKey interface{}) IPrivKey {
}
}
func (key *sRSAPrivKey) DecryptBytes(msg []byte) []byte {
return decryptRSA(key.fPrivKey, msg)
func (p *sRSAPrivKey) DecryptBytes(pMsg []byte) []byte {
return decryptRSA(p.fPrivKey, pMsg)
}
func (key *sRSAPrivKey) SignBytes(msg []byte) []byte {
return sign(key.fPrivKey, hashing.NewSHA256Hasher(msg).ToBytes())
func (p *sRSAPrivKey) SignBytes(pMsg []byte) []byte {
return sign(p.fPrivKey, hashing.NewSHA256Hasher(pMsg).ToBytes())
}
func (key *sRSAPrivKey) GetPubKey() IPubKey {
return key.fPubKey
func (p *sRSAPrivKey) GetPubKey() IPubKey {
return p.fPubKey
}
func (key *sRSAPrivKey) ToBytes() []byte {
return privateKeyToBytes(key.fPrivKey)
func (p *sRSAPrivKey) ToBytes() []byte {
return privateKeyToBytes(p.fPrivKey)
}
func (key *sRSAPrivKey) ToString() string {
return fmt.Sprintf(cPrivKeyPrefixTemplate+"%X"+cKeySuffix, key.GetType(), key.ToBytes())
func (p *sRSAPrivKey) ToString() string {
return fmt.Sprintf(cPrivKeyPrefixTemplate+"%X"+cKeySuffix, p.GetType(), p.ToBytes())
}
func (key *sRSAPrivKey) GetType() string {
func (p *sRSAPrivKey) GetType() string {
return CRSAKeyType
}
func (key *sRSAPrivKey) GetSize() uint64 {
return key.GetPubKey().GetSize()
func (p *sRSAPrivKey) GetSize() uint64 {
return p.GetPubKey().GetSize()
}
// Used PKCS1.
func bytesToPrivateKey(privData []byte) *rsa.PrivateKey {
priv, err := x509.ParsePKCS1PrivateKey(privData)
func bytesToPrivateKey(pPrivData []byte) *rsa.PrivateKey {
priv, err := x509.ParsePKCS1PrivateKey(pPrivData)
if err != nil {
return nil
}
@ -128,8 +128,8 @@ func bytesToPrivateKey(privData []byte) *rsa.PrivateKey {
}
// Used RSA(OAEP).
func decryptRSA(priv *rsa.PrivateKey, data []byte) []byte {
data, err := rsa.DecryptOAEP(sha256.New(), rand.Reader, priv, data, nil)
func decryptRSA(pPrivKey *rsa.PrivateKey, pData []byte) []byte {
data, err := rsa.DecryptOAEP(sha256.New(), rand.Reader, pPrivKey, pData, nil)
if err != nil {
return nil
}
@ -137,12 +137,12 @@ func decryptRSA(priv *rsa.PrivateKey, data []byte) []byte {
}
// Used PKCS1.
func privateKeyToBytes(priv *rsa.PrivateKey) []byte {
return x509.MarshalPKCS1PrivateKey(priv)
func privateKeyToBytes(pPrivKey *rsa.PrivateKey) []byte {
return x509.MarshalPKCS1PrivateKey(pPrivKey)
}
func sign(priv *rsa.PrivateKey, hash []byte) []byte {
signature, err := rsa.SignPSS(rand.Reader, priv, crypto.SHA256, hash, nil)
func sign(pPrivKey *rsa.PrivateKey, pHash []byte) []byte {
signature, err := rsa.SignPSS(rand.Reader, pPrivKey, crypto.SHA256, pHash, nil)
if err != nil {
return nil
}
@ -158,15 +158,15 @@ type sRSAPubKey struct {
fPubKey *rsa.PublicKey
}
func newPubKey(pubKey *rsa.PublicKey) IPubKey {
func newPubKey(pPubKey *rsa.PublicKey) IPubKey {
return &sRSAPubKey{
fAddr: newAddress(pubKey),
fPubKey: pubKey,
fAddr: newAddress(pPubKey),
fPubKey: pPubKey,
}
}
func LoadRSAPubKey(pubkey interface{}) IPubKey {
switch x := pubkey.(type) {
func LoadRSAPubKey(pPubKey interface{}) IPubKey {
switch x := pPubKey.(type) {
case []byte:
pub := bytesToPublicKey(x)
if pub == nil {
@ -200,32 +200,32 @@ func LoadRSAPubKey(pubkey interface{}) IPubKey {
}
}
func (key *sRSAPubKey) EncryptBytes(msg []byte) []byte {
return encryptRSA(key.fPubKey, msg)
func (p *sRSAPubKey) EncryptBytes(pMsg []byte) []byte {
return encryptRSA(p.fPubKey, pMsg)
}
func (key *sRSAPubKey) GetAddress() IAddress {
return key.fAddr
func (p *sRSAPubKey) GetAddress() IAddress {
return p.fAddr
}
func (key *sRSAPubKey) VerifyBytes(msg []byte, sig []byte) bool {
return verify(key.fPubKey, hashing.NewSHA256Hasher(msg).ToBytes(), sig) == nil
func (p *sRSAPubKey) VerifyBytes(pMsg []byte, pSign []byte) bool {
return verify(p.fPubKey, hashing.NewSHA256Hasher(pMsg).ToBytes(), pSign) == nil
}
func (key *sRSAPubKey) ToBytes() []byte {
return publicKeyToBytes(key.fPubKey)
func (p *sRSAPubKey) ToBytes() []byte {
return publicKeyToBytes(p.fPubKey)
}
func (key *sRSAPubKey) ToString() string {
return fmt.Sprintf(cPubKeyPrefixTemplate+"%X"+cKeySuffix, key.GetType(), key.ToBytes())
func (p *sRSAPubKey) ToString() string {
return fmt.Sprintf(cPubKeyPrefixTemplate+"%X"+cKeySuffix, p.GetType(), p.ToBytes())
}
func (key *sRSAPubKey) GetType() string {
func (p *sRSAPubKey) GetType() string {
return CRSAKeyType
}
func (key *sRSAPubKey) GetSize() uint64 {
return uint64(key.fPubKey.N.BitLen())
func (p *sRSAPubKey) GetSize() uint64 {
return uint64(p.fPubKey.N.BitLen())
}
/*
@ -236,33 +236,33 @@ type sAddress struct {
fBytes []byte
}
func newAddress(pubKey *rsa.PublicKey) IAddress {
func newAddress(pPubKey *rsa.PublicKey) IAddress {
return &sAddress{
fBytes: hashing.NewSHA256Hasher(
publicKeyToBytes(pubKey),
publicKeyToBytes(pPubKey),
).ToBytes(),
}
}
func (addr *sAddress) ToBytes() []byte {
return addr.fBytes
func (p *sAddress) ToBytes() []byte {
return p.fBytes
}
func (addr *sAddress) ToString() string {
return fmt.Sprintf("Address(%s){%X}", addr.GetType(), addr.ToBytes())
func (p *sAddress) ToString() string {
return fmt.Sprintf("Address(%s){%X}", p.GetType(), p.ToBytes())
}
func (addr *sAddress) GetType() string {
func (p *sAddress) GetType() string {
return CRSAKeyType
}
func (addr *sAddress) GetSize() uint64 {
func (p *sAddress) GetSize() uint64 {
return hashing.CSHA256Size
}
// Used RSA(OAEP).
func encryptRSA(pub *rsa.PublicKey, data []byte) []byte {
data, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, pub, data, nil)
func encryptRSA(pPubKey *rsa.PublicKey, pData []byte) []byte {
data, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, pPubKey, pData, nil)
if err != nil {
return nil
}
@ -270,8 +270,8 @@ func encryptRSA(pub *rsa.PublicKey, data []byte) []byte {
}
// Used PKCS1.
func bytesToPublicKey(pubData []byte) *rsa.PublicKey {
pub, err := x509.ParsePKCS1PublicKey(pubData)
func bytesToPublicKey(pPubData []byte) *rsa.PublicKey {
pub, err := x509.ParsePKCS1PublicKey(pPubData)
if err != nil {
return nil
}
@ -279,16 +279,17 @@ func bytesToPublicKey(pubData []byte) *rsa.PublicKey {
}
// Used PKCS1.
func publicKeyToBytes(pub *rsa.PublicKey) []byte {
return x509.MarshalPKCS1PublicKey(pub)
func publicKeyToBytes(pPubKey *rsa.PublicKey) []byte {
return x509.MarshalPKCS1PublicKey(pPubKey)
}
// Used RSA(PSS).
func verify(pub *rsa.PublicKey, hash, sign []byte) error {
return rsa.VerifyPSS(pub, crypto.SHA256, hash, sign, nil)
func verify(pPubKey *rsa.PublicKey, pHash, pSign []byte) error {
return rsa.VerifyPSS(pPubKey, crypto.SHA256, pHash, pSign, nil)
}
func skipSpaceChars(s string) string {
func skipSpaceChars(pS string) string {
s := pS
s = strings.ReplaceAll(s, "\n", "")
s = strings.ReplaceAll(s, "\t", "")
s = strings.ReplaceAll(s, " ", "")

View File

@ -21,21 +21,21 @@ func NewListPubKeys() IListPubKeys {
}
// Check the existence of a friend in the list by the public key.
func (l *sListPubKeys) InPubKeys(pub IPubKey) bool {
l.fMutex.Lock()
defer l.fMutex.Unlock()
func (p *sListPubKeys) InPubKeys(pPubKey IPubKey) bool {
p.fMutex.Lock()
defer p.fMutex.Unlock()
_, ok := l.fMapping[pub.GetAddress().ToString()]
_, ok := p.fMapping[pPubKey.GetAddress().ToString()]
return ok
}
// Get a list of friends public keys.
func (l *sListPubKeys) GetPubKeys() []IPubKey {
l.fMutex.Lock()
defer l.fMutex.Unlock()
func (p *sListPubKeys) GetPubKeys() []IPubKey {
p.fMutex.Lock()
defer p.fMutex.Unlock()
var list []IPubKey
for _, pub := range l.fMapping {
for _, pub := range p.fMapping {
list = append(list, pub)
}
@ -43,17 +43,17 @@ func (l *sListPubKeys) GetPubKeys() []IPubKey {
}
// Add public key to list of friends.
func (l *sListPubKeys) AddPubKey(pub IPubKey) {
l.fMutex.Lock()
defer l.fMutex.Unlock()
func (p *sListPubKeys) AddPubKey(pPubKey IPubKey) {
p.fMutex.Lock()
defer p.fMutex.Unlock()
l.fMapping[pub.GetAddress().ToString()] = pub
p.fMapping[pPubKey.GetAddress().ToString()] = pPubKey
}
// Delete public key from list of friends.
func (l *sListPubKeys) DelPubKey(pub IPubKey) {
l.fMutex.Lock()
defer l.fMutex.Unlock()
func (p *sListPubKeys) DelPubKey(pub IPubKey) {
p.fMutex.Lock()
defer p.fMutex.Unlock()
delete(l.fMapping, pub.GetAddress().ToString())
delete(p.fMapping, pub.GetAddress().ToString())
}

View File

@ -15,22 +15,25 @@ type sEntropyBooster struct {
fBits uint64
}
func NewEntropyBooster(bits uint64, salt []byte) IEntropyBooster {
func NewEntropyBooster(pBits uint64, pSalt []byte) IEntropyBooster {
return &sEntropyBooster{
fBits: bits,
fSalt: salt,
fBits: pBits,
fSalt: pSalt,
}
}
// Increase entropy by multiple hashing.
func (e *sEntropyBooster) BoostEntropy(data []byte) []byte {
lim := uint64(1 << e.fBits)
func (p *sEntropyBooster) BoostEntropy(pData []byte) []byte {
var (
lim = uint64(1 << p.fBits)
data = pData
)
for i := uint64(0); i < lim; i++ {
data = hashing.NewSHA256Hasher(bytes.Join(
[][]byte{
data,
e.fSalt,
pData,
p.fSalt,
},
[]byte{},
)).ToBytes()

View File

@ -18,26 +18,26 @@ type sSHA256Hasher struct {
fHash []byte
}
func NewSHA256Hasher(data []byte) IHasher {
func NewSHA256Hasher(pData []byte) IHasher {
h := sha256.New()
h.Write(data)
h.Write(pData)
return &sSHA256Hasher{
fHash: h.Sum(nil),
}
}
func (h *sSHA256Hasher) ToString() string {
return fmt.Sprintf("Hash(%s){%X}", h.GetType(), h.ToBytes())
func (p *sSHA256Hasher) ToString() string {
return fmt.Sprintf("Hash(%s){%X}", p.GetType(), p.ToBytes())
}
func (h *sSHA256Hasher) ToBytes() []byte {
return h.fHash
func (p *sSHA256Hasher) ToBytes() []byte {
return p.fHash
}
func (h *sSHA256Hasher) GetType() string {
func (p *sSHA256Hasher) GetType() string {
return CSHA256KeyType
}
func (h *sSHA256Hasher) GetSize() uint64 {
func (p *sSHA256Hasher) GetSize() uint64 {
return CSHA256Size
}

View File

@ -14,26 +14,26 @@ type sHMACSHA256Hasher struct {
fHash []byte
}
func NewHMACSHA256Hasher(key []byte, data []byte) IHasher {
h := hmac.New(sha256.New, key)
h.Write(data)
func NewHMACSHA256Hasher(pKey []byte, pData []byte) IHasher {
h := hmac.New(sha256.New, pKey)
h.Write(pData)
return &sHMACSHA256Hasher{
fHash: h.Sum(nil),
}
}
func (h *sHMACSHA256Hasher) ToString() string {
return fmt.Sprintf("HMAC(%s){%X}", h.GetType(), h.ToBytes())
func (p *sHMACSHA256Hasher) ToString() string {
return fmt.Sprintf("HMAC(%s){%X}", p.GetType(), p.ToBytes())
}
func (h *sHMACSHA256Hasher) ToBytes() []byte {
return h.fHash
func (p *sHMACSHA256Hasher) ToBytes() []byte {
return p.fHash
}
func (h *sHMACSHA256Hasher) GetType() string {
func (p *sHMACSHA256Hasher) GetType() string {
return CSHA256KeyType
}
func (h *sHMACSHA256Hasher) GetSize() uint64 {
func (p *sHMACSHA256Hasher) GetSize() uint64 {
return CSHA256Size
}

View File

@ -17,20 +17,22 @@ type sPoWPuzzle struct {
fDiff uint8
}
func NewPoWPuzzle(diff uint64) IPuzzle {
return &sPoWPuzzle{uint8(diff)}
func NewPoWPuzzle(pDiff uint64) IPuzzle {
return &sPoWPuzzle{
fDiff: uint8(pDiff),
}
}
// Proof of work by the method of finding the desired hash.
// Hash must start with 'diff' number of zero bits.
func (puzzle *sPoWPuzzle) ProofBytes(packHash []byte) uint64 {
func (p *sPoWPuzzle) ProofBytes(packHash []byte) uint64 {
var (
target = big.NewInt(1)
intHash = big.NewInt(1)
nonce = uint64(0)
hash []byte
)
target.Lsh(target, hashSizeInBits()-uint(puzzle.fDiff))
target.Lsh(target, hashSizeInBits()-uint(p.fDiff))
for nonce < math.MaxUint64 {
bNonce := encoding.Uint64ToBytes(nonce)
hash = hashing.NewSHA256Hasher(bytes.Join(
@ -50,7 +52,7 @@ func (puzzle *sPoWPuzzle) ProofBytes(packHash []byte) uint64 {
}
// Verifies the work of the proof of work function.
func (puzzle *sPoWPuzzle) VerifyBytes(packHash []byte, nonce uint64) bool {
func (p *sPoWPuzzle) VerifyBytes(packHash []byte, nonce uint64) bool {
intHash := big.NewInt(1)
target := big.NewInt(1)
bNonce := encoding.Uint64ToBytes(nonce)
@ -62,7 +64,7 @@ func (puzzle *sPoWPuzzle) VerifyBytes(packHash []byte, nonce uint64) bool {
[]byte{},
)).ToBytes()
intHash.SetBytes(hash)
target.Lsh(target, hashSizeInBits()-uint(puzzle.fDiff))
target.Lsh(target, hashSizeInBits()-uint(p.fDiff))
return intHash.Cmp(target) == -1
}

View File

@ -18,7 +18,7 @@ func NewStdPRNG() IPRNG {
}
// Generates a cryptographically strong pseudo-random bytes.
func (r *sStdPRNG) GetBytes(n uint64) []byte {
func (p *sStdPRNG) GetBytes(n uint64) []byte {
slice := make([]byte, n)
_, err := rand.Read(slice)
if err != nil {
@ -29,18 +29,18 @@ func (r *sStdPRNG) GetBytes(n uint64) []byte {
}
// Generates a cryptographically strong pseudo-random string.
func (r *sStdPRNG) GetString(n uint64) string {
return encoding.HexEncode(r.GetBytes(n))[:n]
func (p *sStdPRNG) GetString(n uint64) string {
return encoding.HexEncode(p.GetBytes(n))[:n]
}
// Generate cryptographically strong pseudo-random uint64 number.
func (r *sStdPRNG) GetUint64() uint64 {
func (p *sStdPRNG) GetUint64() uint64 {
res := [encoding.CSizeUint64]byte{}
copy(res[:], r.GetBytes(8))
copy(res[:], p.GetBytes(8))
return encoding.BytesToUint64(res)
}
// Generate cryptographically strong pseudo-random bool value.
func (r *sStdPRNG) GetBool() bool {
return r.GetBytes(1)[0]%2 == 0
func (p *sStdPRNG) GetBool() bool {
return p.GetBytes(1)[0]%2 == 0
}

View File

@ -23,14 +23,14 @@ type sAESCipher struct {
fKey []byte
}
func NewAESCipher(key []byte) ICipher {
func NewAESCipher(pKey []byte) ICipher {
return &sAESCipher{
fKey: hashing.NewSHA256Hasher(key).ToBytes(),
fKey: hashing.NewSHA256Hasher(pKey).ToBytes(),
}
}
func (cph *sAESCipher) EncryptBytes(msg []byte) []byte {
block, err := aes.NewCipher(cph.fKey)
func (p *sAESCipher) EncryptBytes(pMsg []byte) []byte {
block, err := aes.NewCipher(p.fKey)
if err != nil {
return nil
}
@ -39,43 +39,43 @@ func (cph *sAESCipher) EncryptBytes(msg []byte) []byte {
iv := random.NewStdPRNG().GetBytes(uint64(blockSize))
stream := cipher.NewCTR(block, iv)
result := make([]byte, len(msg)+len(iv))
result := make([]byte, len(pMsg)+len(iv))
copy(result[:blockSize], iv)
stream.XORKeyStream(result[blockSize:], msg)
stream.XORKeyStream(result[blockSize:], pMsg)
return result
}
func (cph *sAESCipher) DecryptBytes(msg []byte) []byte {
block, err := aes.NewCipher(cph.fKey)
func (p *sAESCipher) DecryptBytes(pMsg []byte) []byte {
block, err := aes.NewCipher(p.fKey)
if err != nil {
return nil
}
blockSize := block.BlockSize()
if len(msg) < blockSize {
if len(pMsg) < blockSize {
return nil
}
stream := cipher.NewCTR(block, msg[:blockSize])
result := make([]byte, len(msg)-blockSize)
stream := cipher.NewCTR(block, pMsg[:blockSize])
result := make([]byte, len(pMsg)-blockSize)
stream.XORKeyStream(result, msg[blockSize:])
stream.XORKeyStream(result, pMsg[blockSize:])
return result
}
func (cph *sAESCipher) ToString() string {
return fmt.Sprintf("Key(%s){%X}", cph.GetType(), cph.ToBytes())
func (p *sAESCipher) ToString() string {
return fmt.Sprintf("Key(%s){%X}", p.GetType(), p.ToBytes())
}
func (cph *sAESCipher) ToBytes() []byte {
return cph.fKey
func (p *sAESCipher) ToBytes() []byte {
return p.fKey
}
func (cph *sAESCipher) GetType() string {
func (p *sAESCipher) GetType() string {
return CAESKeyType
}
func (cph *sAESCipher) GetSize() uint64 {
func (p *sAESCipher) GetSize() uint64 {
return CAESKeySize
}

View File

@ -1,9 +1,9 @@
package crypto
type IEncrypter interface {
EncryptBytes(msg []byte) []byte
EncryptBytes(pMsg []byte) []byte
}
type IDecrypter interface {
DecryptBytes(msg []byte) []byte
DecryptBytes(pMsg []byte) []byte
}

View File

@ -14,11 +14,11 @@ const (
)
// Uint64 to slice of bytes by big endian.
func Uint64ToBytes(num uint64) [cSizeUint64]byte {
func Uint64ToBytes(pNum uint64) [cSizeUint64]byte {
res := [CSizeUint64]byte{}
var data = new(bytes.Buffer)
err := binary.Write(data, binary.BigEndian, num)
err := binary.Write(data, binary.BigEndian, pNum)
if err != nil {
panic(err)
}
@ -28,6 +28,6 @@ func Uint64ToBytes(num uint64) [cSizeUint64]byte {
}
// Slice of bytes to uint64 by big endian.
func BytesToUint64(bytes [cSizeUint64]byte) uint64 {
return binary.BigEndian.Uint64(bytes[:])
func BytesToUint64(pBytes [cSizeUint64]byte) uint64 {
return binary.BigEndian.Uint64(pBytes[:])
}

View File

@ -2,12 +2,12 @@ package encoding
import "encoding/hex"
func HexEncode(data []byte) string {
return hex.EncodeToString(data)
func HexEncode(pData []byte) string {
return hex.EncodeToString(pData)
}
func HexDecode(data string) []byte {
result, err := hex.DecodeString(data)
func HexDecode(pData string) []byte {
result, err := hex.DecodeString(pData)
if err != nil {
return nil
}

View File

@ -2,14 +2,14 @@ package encoding
import "encoding/json"
func Serialize(data interface{}) []byte {
res, err := json.MarshalIndent(data, "", "\t")
func Serialize(pData interface{}) []byte {
res, err := json.MarshalIndent(pData, "", "\t")
if err != nil {
return nil
}
return res
}
func Deserialize(data []byte, res interface{}) error {
return json.Unmarshal(data, res)
func Deserialize(pData []byte, pRes interface{}) error {
return json.Unmarshal(pData, pRes)
}

View File

@ -12,25 +12,25 @@ type sFile struct {
fPath string
}
func OpenFile(path string) IFile {
func OpenFile(pPath string) IFile {
return &sFile{
fPath: path,
fPath: pPath,
}
}
func (file *sFile) Read() ([]byte, error) {
data, err := os.ReadFile(file.fPath)
func (p *sFile) Read() ([]byte, error) {
data, err := os.ReadFile(p.fPath)
if err != nil {
return nil, err
}
return data, nil
}
func (file *sFile) Write(data []byte) error {
return os.WriteFile(file.fPath, data, 0644)
func (p *sFile) Write(pData []byte) error {
return os.WriteFile(p.fPath, pData, 0644)
}
func (file *sFile) IsExist() bool {
_, err := os.Stat(file.fPath)
func (p *sFile) IsExist() bool {
_, err := os.Stat(p.fPath)
return !os.IsNotExist(err)
}

View File

@ -23,22 +23,22 @@ const (
colorReset = "\033[0m"
)
func NewLogger(sett ISettings) ILogger {
func NewLogger(pSett ISettings) ILogger {
logger := &sLogger{
fSettings: sett,
fSettings: pSett,
}
infoStream := sett.GetStreamInfo()
infoStream := pSett.GetStreamInfo()
if infoStream != nil {
logger.fInfoOut = log.New(infoStream, fmt.Sprintf("%s[INFO] %s", colorCyan, colorReset), log.LstdFlags)
}
warnStream := sett.GetStreamWarn()
warnStream := pSett.GetStreamWarn()
if warnStream != nil {
logger.fWarnOut = log.New(warnStream, fmt.Sprintf("%s[WARN] %s", colorYellow, colorReset), log.LstdFlags)
}
erroStream := sett.GetStreamErro()
erroStream := pSett.GetStreamErro()
if erroStream != nil {
logger.fErroOut = log.New(erroStream, fmt.Sprintf("%s[ERRO] %s", colorRed, colorReset), log.LstdFlags)
}
@ -46,27 +46,27 @@ func NewLogger(sett ISettings) ILogger {
return logger
}
func (l *sLogger) GetSettings() ISettings {
return l.fSettings
func (p *sLogger) GetSettings() ISettings {
return p.fSettings
}
func (l *sLogger) PushInfo(info string) {
if l.fInfoOut == nil {
func (p *sLogger) PushInfo(info string) {
if p.fInfoOut == nil {
return
}
l.fInfoOut.Println(info)
p.fInfoOut.Println(info)
}
func (l *sLogger) PushWarn(warn string) {
if l.fWarnOut == nil {
func (p *sLogger) PushWarn(warn string) {
if p.fWarnOut == nil {
return
}
l.fWarnOut.Println(warn)
p.fWarnOut.Println(warn)
}
func (l *sLogger) PushErro(erro string) {
if l.fErroOut == nil {
func (p *sLogger) PushErro(erro string) {
if p.fErroOut == nil {
return
}
l.fErroOut.Println(erro)
p.fErroOut.Println(erro)
}

View File

@ -15,27 +15,27 @@ type sSettings struct {
FErro *os.File
}
func NewSettings(sett *SSettings) ISettings {
func NewSettings(pSett *SSettings) ISettings {
return (&sSettings{
FInfo: sett.FInfo,
FWarn: sett.FWarn,
FErro: sett.FErro,
FInfo: pSett.FInfo,
FWarn: pSett.FWarn,
FErro: pSett.FErro,
}).useDefaultValues()
}
func (s *sSettings) useDefaultValues() ISettings {
func (p *sSettings) useDefaultValues() ISettings {
// set nil for void fields
return s
return p
}
func (s *sSettings) GetStreamInfo() *os.File {
return s.FInfo
func (p *sSettings) GetStreamInfo() *os.File {
return p.FInfo
}
func (s *sSettings) GetStreamWarn() *os.File {
return s.FWarn
func (p *sSettings) GetStreamWarn() *os.File {
return p.FWarn
}
func (s *sSettings) GetStreamErro() *os.File {
return s.FErro
func (p *sSettings) GetStreamErro() *os.File {
return p.FErro
}

View File

@ -38,117 +38,117 @@ type sNode struct {
}
func NewNode(
sett ISettings,
log logger.ILogger,
wDB IWrapperDB,
nnode network.INode,
queue queue.IMessageQueue,
friends asymmetric.IListPubKeys,
pSett ISettings,
pLogger logger.ILogger,
pWrapperDB IWrapperDB,
pNetwork network.INode,
pQueue queue.IMessageQueue,
pFriends asymmetric.IListPubKeys,
) INode {
return &sNode{
fSettings: sett,
fLogger: log,
fWrapperDB: wDB,
fNetwork: nnode,
fQueue: queue,
fFriends: friends,
fSettings: pSett,
fLogger: pLogger,
fWrapperDB: pWrapperDB,
fNetwork: pNetwork,
fQueue: pQueue,
fFriends: pFriends,
fHandleRoutes: make(map[uint32]IHandlerF),
fHandleActions: make(map[string]chan []byte),
}
}
func (node *sNode) Run() error {
logger := anon_logger.NewLogger(node.GetSettings().GetServiceName())
func (p *sNode) Run() error {
logger := anon_logger.NewLogger(p.GetSettings().GetServiceName())
if err := node.runQueue(logger); err != nil {
if err := p.runQueue(logger); err != nil {
return err
}
node.GetNetworkNode().HandleFunc(
node.GetSettings().GetNetworkMask(),
node.handleWrapper(logger),
p.GetNetworkNode().HandleFunc(
p.GetSettings().GetNetworkMask(),
p.handleWrapper(logger),
)
return nil
}
func (node *sNode) Stop() error {
node.GetNetworkNode().HandleFunc(node.GetSettings().GetNetworkMask(), nil)
func (p *sNode) Stop() error {
p.GetNetworkNode().HandleFunc(p.GetSettings().GetNetworkMask(), nil)
return types.StopAll([]types.ICommand{
node.GetMessageQueue(),
p.GetMessageQueue(),
})
}
func (node *sNode) GetLogger() logger.ILogger {
return node.fLogger
func (p *sNode) GetLogger() logger.ILogger {
return p.fLogger
}
func (node *sNode) GetSettings() ISettings {
return node.fSettings
func (p *sNode) GetSettings() ISettings {
return p.fSettings
}
func (node *sNode) GetWrapperDB() IWrapperDB {
return node.fWrapperDB
func (p *sNode) GetWrapperDB() IWrapperDB {
return p.fWrapperDB
}
func (node *sNode) GetNetworkNode() network.INode {
return node.fNetwork
func (p *sNode) GetNetworkNode() network.INode {
return p.fNetwork
}
func (node *sNode) GetMessageQueue() queue.IMessageQueue {
return node.fQueue
func (p *sNode) GetMessageQueue() queue.IMessageQueue {
return p.fQueue
}
// Return f2f structure.
func (node *sNode) GetListPubKeys() asymmetric.IListPubKeys {
return node.fFriends
func (p *sNode) GetListPubKeys() asymmetric.IListPubKeys {
return p.fFriends
}
func (node *sNode) HandleFunc(head uint32, handle IHandlerF) INode {
node.setRoute(head, handle)
return node
func (p *sNode) HandleFunc(pHead uint32, pHandle IHandlerF) INode {
p.setRoute(pHead, pHandle)
return p
}
// Send message without response waiting.
func (node *sNode) BroadcastPayload(recv asymmetric.IPubKey, pld payload.IPayload) error {
if len(node.GetNetworkNode().GetConnections()) == 0 {
func (p *sNode) BroadcastPayload(pRecv asymmetric.IPubKey, pPld payload.IPayload) error {
if len(p.GetNetworkNode().GetConnections()) == 0 {
return errors.New("length of connections = 0")
}
msg, err := node.GetMessageQueue().GetClient().EncryptPayload(recv, pld)
msg, err := p.GetMessageQueue().GetClient().EncryptPayload(pRecv, pPld)
if err != nil {
return err
}
return node.send(msg)
return p.send(msg)
}
// Send message with response waiting.
// Payload head must be uint32.
func (node *sNode) FetchPayload(recv asymmetric.IPubKey, pld payload.IPayload) ([]byte, error) {
func (p *sNode) FetchPayload(pRecv asymmetric.IPubKey, pPld payload.IPayload) ([]byte, error) {
headAction := uint32(random.NewStdPRNG().GetUint64())
headRoute := mustBeUint32(pld.GetHead())
headRoute := mustBeUint32(pPld.GetHead())
newPld := payload.NewPayload(
joinHead(headAction, headRoute).Uint64(),
pld.GetBody(),
pPld.GetBody(),
)
actionKey := newActionKey(recv, headAction)
actionKey := newActionKey(pRecv, headAction)
node.setAction(actionKey)
defer node.delAction(actionKey)
p.setAction(actionKey)
defer p.delAction(actionKey)
if err := node.BroadcastPayload(recv, newPld); err != nil {
if err := p.BroadcastPayload(pRecv, newPld); err != nil {
return nil, err
}
return node.recv(actionKey)
return p.recv(actionKey)
}
func (node *sNode) send(msg message.IMessage) error {
for i := uint64(0); i <= node.GetSettings().GetRetryEnqueue(); i++ {
if err := node.GetMessageQueue().EnqueueMessage(msg); err != nil {
time.Sleep(node.GetMessageQueue().GetSettings().GetDuration())
func (p *sNode) send(pMsg message.IMessage) error {
for i := uint64(0); i <= p.GetSettings().GetRetryEnqueue(); i++ {
if err := p.GetMessageQueue().EnqueueMessage(pMsg); err != nil {
time.Sleep(p.GetMessageQueue().GetSettings().GetDuration())
continue
}
return nil
@ -156,8 +156,8 @@ func (node *sNode) send(msg message.IMessage) error {
return fmt.Errorf("failed: enqueue message")
}
func (node *sNode) recv(actionKey string) ([]byte, error) {
action, ok := node.getAction(actionKey)
func (p *sNode) recv(pActionKey string) ([]byte, error) {
action, ok := p.getAction(pActionKey)
if !ok {
return nil, errors.New("action undefined")
}
@ -167,19 +167,19 @@ func (node *sNode) recv(actionKey string) ([]byte, error) {
return nil, errors.New("chan is closed")
}
return result, nil
case <-time.After(node.GetSettings().GetTimeWait()):
case <-time.After(p.GetSettings().GetTimeWait()):
return nil, errors.New("time is over")
}
}
func (node *sNode) runQueue(logger anon_logger.ILogger) error {
if err := node.GetMessageQueue().Run(); err != nil {
func (p *sNode) runQueue(pLogger anon_logger.ILogger) error {
if err := p.GetMessageQueue().Run(); err != nil {
return err
}
go func() {
for {
msg, ok := <-node.GetMessageQueue().DequeueMessage()
msg, ok := <-p.GetMessageQueue().DequeueMessage()
if !ok {
break
}
@ -187,44 +187,44 @@ func (node *sNode) runQueue(logger anon_logger.ILogger) error {
var (
hash = msg.GetBody().GetHash()
proof = msg.GetBody().GetProof()
pubKey = node.GetMessageQueue().GetClient().GetPubKey()
pubKey = p.GetMessageQueue().GetClient().GetPubKey()
)
if err := node.networkBroadcast(logger, msg); err != nil {
node.fLogger.PushErro(logger.GetFmtLog(anon_logger.CLogErroMiddleware, hash, proof, pubKey, nil))
if err := p.networkBroadcast(pLogger, msg); err != nil {
p.fLogger.PushErro(pLogger.GetFmtLog(anon_logger.CLogErroMiddleware, hash, proof, pubKey, nil))
continue
}
node.fLogger.PushInfo(logger.GetFmtLog(anon_logger.CLogBaseBroadcast, hash, proof, pubKey, nil))
p.fLogger.PushInfo(pLogger.GetFmtLog(anon_logger.CLogBaseBroadcast, hash, proof, pubKey, nil))
}
}()
return nil
}
func (node *sNode) handleWrapper(logger anon_logger.ILogger) network.IHandlerF {
return func(_ network.INode, conn conn.IConn, reqBytes []byte) {
func (p *sNode) handleWrapper(pLogger anon_logger.ILogger) network.IHandlerF {
return func(_ network.INode, pConn conn.IConn, pReqBytes []byte) {
msg := message.LoadMessage(
reqBytes,
pReqBytes,
message.NewParams(
node.GetMessageQueue().GetClient().GetSettings().GetMessageSize(),
node.GetMessageQueue().GetClient().GetSettings().GetWorkSize(),
p.GetMessageQueue().GetClient().GetSettings().GetMessageSize(),
p.GetMessageQueue().GetClient().GetSettings().GetWorkSize(),
),
)
if msg == nil {
node.GetLogger().PushWarn(logger.GetFmtLog(anon_logger.CLogWarnMessageNull, nil, 0, nil, conn))
p.GetLogger().PushWarn(pLogger.GetFmtLog(anon_logger.CLogWarnMessageNull, nil, 0, nil, pConn))
return
}
var (
addr = node.GetMessageQueue().GetClient().GetPubKey().GetAddress().ToString()
addr = p.GetMessageQueue().GetClient().GetPubKey().GetAddress().ToString()
hash = msg.GetBody().GetHash()
proof = msg.GetBody().GetProof()
database = node.GetWrapperDB().Get()
database = p.GetWrapperDB().Get()
)
if database == nil {
node.GetLogger().PushErro(logger.GetFmtLog(anon_logger.CLogErroDatabaseGet, hash, proof, nil, conn))
p.GetLogger().PushErro(pLogger.GetFmtLog(anon_logger.CLogErroDatabaseGet, hash, proof, nil, pConn))
return
}
@ -234,36 +234,36 @@ func (node *sNode) handleWrapper(logger anon_logger.ILogger) network.IHandlerF {
// check already received data by hash
hashIsExist := (err == nil)
if hashIsExist && strings.Contains(string(gotAddrs), addr) {
node.GetLogger().PushInfo(logger.GetFmtLog(anon_logger.CLogInfoExist, hash, proof, nil, conn))
p.GetLogger().PushInfo(pLogger.GetFmtLog(anon_logger.CLogInfoExist, hash, proof, nil, pConn))
return
}
// set hash to database
updateAddrs := fmt.Sprintf("%s;%s", string(gotAddrs), addr)
if err := database.Set(hashDB, []byte(updateAddrs)); err != nil {
node.GetLogger().PushErro(logger.GetFmtLog(anon_logger.CLogErroDatabaseSet, hash, proof, nil, conn))
p.GetLogger().PushErro(pLogger.GetFmtLog(anon_logger.CLogErroDatabaseSet, hash, proof, nil, pConn))
return
}
// do not send data if than already received
if !hashIsExist {
// broadcast message to network
if err := node.networkBroadcast(logger, msg); err != nil {
node.GetLogger().PushErro(logger.GetFmtLog(anon_logger.CLogErroMiddleware, hash, proof, nil, conn))
if err := p.networkBroadcast(pLogger, msg); err != nil {
p.GetLogger().PushErro(pLogger.GetFmtLog(anon_logger.CLogErroMiddleware, hash, proof, nil, pConn))
return
}
}
// try decrypt message
sender, pld, err := node.GetMessageQueue().GetClient().DecryptMessage(msg)
sender, pld, err := p.GetMessageQueue().GetClient().DecryptMessage(msg)
if err != nil {
node.GetLogger().PushInfo(logger.GetFmtLog(anon_logger.CLogInfoUndecryptable, hash, proof, nil, conn))
p.GetLogger().PushInfo(pLogger.GetFmtLog(anon_logger.CLogInfoUndecryptable, hash, proof, nil, pConn))
return
}
// check sender in f2f list
if !node.GetListPubKeys().InPubKeys(sender) {
node.GetLogger().PushWarn(logger.GetFmtLog(anon_logger.CLogWarnNotFriend, hash, proof, sender, conn))
if !p.GetListPubKeys().InPubKeys(sender) {
p.GetLogger().PushWarn(pLogger.GetFmtLog(anon_logger.CLogWarnNotFriend, hash, proof, sender, pConn))
return
}
@ -272,102 +272,102 @@ func (node *sNode) handleWrapper(logger anon_logger.ILogger) network.IHandlerF {
// get session by payload head
actionKey := newActionKey(sender, head.GetAction())
action, ok := node.getAction(actionKey)
action, ok := p.getAction(actionKey)
if ok {
node.GetLogger().PushInfo(logger.GetFmtLog(anon_logger.CLogInfoAction, hash, proof, sender, conn))
p.GetLogger().PushInfo(pLogger.GetFmtLog(anon_logger.CLogInfoAction, hash, proof, sender, pConn))
action <- pld.GetBody()
return
}
// get function by payload head
f, ok := node.getRoute(head.GetRoute())
f, ok := p.getRoute(head.GetRoute())
if !ok || f == nil {
node.GetLogger().PushWarn(logger.GetFmtLog(anon_logger.CLogWarnUnknownRoute, hash, proof, sender, conn))
p.GetLogger().PushWarn(pLogger.GetFmtLog(anon_logger.CLogWarnUnknownRoute, hash, proof, sender, pConn))
return
}
// response can be nil
resp := f(node, sender, hash, pld.GetBody())
resp := f(p, sender, hash, pld.GetBody())
if resp == nil {
node.GetLogger().PushInfo(logger.GetFmtLog(anon_logger.CLogInfoWithoutResp, hash, proof, sender, conn))
p.GetLogger().PushInfo(pLogger.GetFmtLog(anon_logger.CLogInfoWithoutResp, hash, proof, sender, pConn))
return
}
// create the message and put this to the queue
if err := node.BroadcastPayload(sender, payload.NewPayload(pld.GetHead(), resp)); err != nil {
node.GetLogger().PushErro(logger.GetFmtLog(anon_logger.CLogBaseEnqueueResp, hash, proof, sender, conn))
if err := p.BroadcastPayload(sender, payload.NewPayload(pld.GetHead(), resp)); err != nil {
p.GetLogger().PushErro(pLogger.GetFmtLog(anon_logger.CLogBaseEnqueueResp, hash, proof, sender, pConn))
return
}
node.GetLogger().PushInfo(logger.GetFmtLog(anon_logger.CLogBaseEnqueueResp, hash, proof, sender, conn))
p.GetLogger().PushInfo(pLogger.GetFmtLog(anon_logger.CLogBaseEnqueueResp, hash, proof, sender, pConn))
}
}
func (node *sNode) networkBroadcast(logger anon_logger.ILogger, msg message.IMessage) error {
hash := msg.GetBody().GetHash()
proof := msg.GetBody().GetProof()
func (p *sNode) networkBroadcast(pLogger anon_logger.ILogger, pMsg message.IMessage) error {
hash := pMsg.GetBody().GetHash()
proof := pMsg.GetBody().GetProof()
// redirect message to another nodes
err := node.GetNetworkNode().BroadcastPayload(
err := p.GetNetworkNode().BroadcastPayload(
payload.NewPayload(
node.GetSettings().GetNetworkMask(),
msg.ToBytes(),
p.GetSettings().GetNetworkMask(),
pMsg.ToBytes(),
),
)
if err != nil {
node.fLogger.PushWarn(logger.GetFmtLog(anon_logger.CLogBaseBroadcast, hash, proof, nil, nil))
p.fLogger.PushWarn(pLogger.GetFmtLog(anon_logger.CLogBaseBroadcast, hash, proof, nil, nil))
// need continue (some of connections may be closed)
}
return nil
}
func (node *sNode) setRoute(head uint32, handle IHandlerF) {
node.fMutex.Lock()
defer node.fMutex.Unlock()
func (p *sNode) setRoute(pHead uint32, pHandle IHandlerF) {
p.fMutex.Lock()
defer p.fMutex.Unlock()
node.fHandleRoutes[head] = handle
p.fHandleRoutes[pHead] = pHandle
}
func (node *sNode) getRoute(head uint32) (IHandlerF, bool) {
node.fMutex.Lock()
defer node.fMutex.Unlock()
func (p *sNode) getRoute(pHead uint32) (IHandlerF, bool) {
p.fMutex.Lock()
defer p.fMutex.Unlock()
f, ok := node.fHandleRoutes[head]
f, ok := p.fHandleRoutes[pHead]
return f, ok
}
func (node *sNode) getAction(actionKey string) (chan []byte, bool) {
node.fMutex.Lock()
defer node.fMutex.Unlock()
func (p *sNode) getAction(pActionKey string) (chan []byte, bool) {
p.fMutex.Lock()
defer p.fMutex.Unlock()
f, ok := node.fHandleActions[actionKey]
f, ok := p.fHandleActions[pActionKey]
return f, ok
}
func (node *sNode) setAction(actionKey string) {
node.fMutex.Lock()
defer node.fMutex.Unlock()
func (p *sNode) setAction(pActionKey string) {
p.fMutex.Lock()
defer p.fMutex.Unlock()
node.fHandleActions[actionKey] = make(chan []byte)
p.fHandleActions[pActionKey] = make(chan []byte)
}
func (node *sNode) delAction(actionKey string) {
node.fMutex.Lock()
defer node.fMutex.Unlock()
func (p *sNode) delAction(pActionKey string) {
p.fMutex.Lock()
defer p.fMutex.Unlock()
delete(node.fHandleActions, actionKey)
delete(p.fHandleActions, pActionKey)
}
func newActionKey(pubKey asymmetric.IPubKey, head uint32) string {
pubKeyAddr := pubKey.GetAddress().ToString()
headString := fmt.Sprintf("%d", head)
func newActionKey(pPubKey asymmetric.IPubKey, pHead uint32) string {
pubKeyAddr := pPubKey.GetAddress().ToString()
headString := fmt.Sprintf("%d", pHead)
return fmt.Sprintf("%s-%s", pubKeyAddr, headString)
}
func mustBeUint32(v uint64) uint32 {
if v > math.MaxUint32 {
func mustBeUint32(pValue uint64) uint32 {
if pValue > math.MaxUint32 {
panic("v > math.MaxUint32")
}
return uint32(v)
return uint32(pValue)
}

View File

@ -9,22 +9,22 @@ var (
// B used for route
type sHead uint64
func loadHead(n uint64) iHead {
return sHead(n)
func loadHead(pN uint64) iHead {
return sHead(pN)
}
func joinHead(action, route uint32) iHead {
return sHead((uint64(action) << 32) | uint64(route))
func joinHead(pAction, pRoute uint32) iHead {
return sHead((uint64(pAction) << 32) | uint64(pRoute))
}
func (k sHead) GetRoute() uint32 {
return uint32(k & 0x00000000FFFFFFFF)
func (p sHead) GetRoute() uint32 {
return uint32(p & 0x00000000FFFFFFFF)
}
func (k sHead) GetAction() uint32 {
return uint32(k >> 32)
func (p sHead) GetAction() uint32 {
return uint32(p >> 32)
}
func (k sHead) Uint64() uint64 {
return uint64(k)
func (p sHead) Uint64() uint64 {
return uint64(p)
}

View File

@ -16,27 +16,27 @@ type sLogger struct {
fService string
}
func NewLogger(service string) ILogger {
if len(service) != 3 {
func NewLogger(pService string) ILogger {
if len(pService) != 3 {
return nil
}
return &sLogger{
fService: service,
fService: pService,
}
}
func (l *sLogger) GetFmtLog(lType ILogType, msgHash []byte, proof uint64, pubKey asymmetric.IPubKey, netConn conn.IConn) string {
func (p *sLogger) GetFmtLog(pType ILogType, pMsgHash []byte, pProof uint64, pPubKey asymmetric.IPubKey, pNetConn conn.IConn) string {
conn := "127.0.0.1:"
if netConn != nil {
conn = netConn.GetSocket().RemoteAddr().String()
if pNetConn != nil {
conn = pNetConn.GetSocket().RemoteAddr().String()
}
addr := make([]byte, hashing.CSHA256Size)
if pubKey != nil {
addr = pubKey.GetAddress().ToBytes()
if pPubKey != nil {
addr = pPubKey.GetAddress().ToBytes()
}
hash := make([]byte, hashing.CSHA256Size)
if msgHash != nil {
hash = msgHash
if pMsgHash != nil {
hash = pMsgHash
}
return fmt.Sprintf(cLogTemplate, l.fService, lType, hash[:4], hash[28:], addr[:4], addr[28:], proof, conn)
return fmt.Sprintf(cLogTemplate, p.fService, pType, hash[:4], hash[28:], addr[:4], addr[28:], pProof, conn)
}

View File

@ -2,6 +2,6 @@ package anonymity
import "github.com/number571/go-peer/pkg/payload"
func NewPayload(head uint32, body []byte) payload.IPayload {
return payload.NewPayload(uint64(head), body)
func NewPayload(pHead uint32, pBody []byte) payload.IPayload {
return payload.NewPayload(uint64(pHead), pBody)
}

View File

@ -22,40 +22,40 @@ type sSettings struct {
FTimeWait time.Duration
}
func NewSettings(sett *SSettings) ISettings {
func NewSettings(pSett *SSettings) ISettings {
return (&sSettings{
FServiceName: sett.FServiceName,
FRetryEnqueue: sett.FRetryEnqueue,
FNetworkMask: sett.FNetworkMask,
FTimeWait: sett.FTimeWait,
FServiceName: pSett.FServiceName,
FRetryEnqueue: pSett.FRetryEnqueue,
FNetworkMask: pSett.FNetworkMask,
FTimeWait: pSett.FTimeWait,
}).useDefaultValue()
}
func (s *sSettings) useDefaultValue() ISettings {
if s.FServiceName == "" {
s.FServiceName = cServiceName
func (p *sSettings) useDefaultValue() ISettings {
if p.FServiceName == "" {
p.FServiceName = cServiceName
}
if s.FNetworkMask == 0 {
s.FNetworkMask = cMaskNetwork
if p.FNetworkMask == 0 {
p.FNetworkMask = cMaskNetwork
}
if s.FTimeWait == 0 {
s.FTimeWait = cTimeWait
if p.FTimeWait == 0 {
p.FTimeWait = cTimeWait
}
return s
return p
}
func (s *sSettings) GetServiceName() string {
return s.FServiceName
func (p *sSettings) GetServiceName() string {
return p.FServiceName
}
func (s *sSettings) GetTimeWait() time.Duration {
return s.FTimeWait
func (p *sSettings) GetTimeWait() time.Duration {
return p.FTimeWait
}
func (s *sSettings) GetNetworkMask() uint64 {
return s.FNetworkMask
func (p *sSettings) GetNetworkMask() uint64 {
return p.FNetworkMask
}
func (s *sSettings) GetRetryEnqueue() uint64 {
return s.FRetryEnqueue
func (p *sSettings) GetRetryEnqueue() uint64 {
return p.FRetryEnqueue
}

View File

@ -20,27 +20,27 @@ func NewWrapperDB() IWrapperDB {
return &sWrapperDB{fWrapper: wrapper.NewWrapper()}
}
func (w *sWrapperDB) Get() database.IKeyValueDB {
db, ok := w.fWrapper.Get().(database.IKeyValueDB)
func (p *sWrapperDB) Get() database.IKeyValueDB {
db, ok := p.fWrapper.Get().(database.IKeyValueDB)
if !ok {
return nil
}
return db
}
func (w *sWrapperDB) Set(db database.IKeyValueDB) IWrapperDB {
w.fMutex.Lock()
defer w.fMutex.Unlock()
func (p *sWrapperDB) Set(pDB database.IKeyValueDB) IWrapperDB {
p.fMutex.Lock()
defer p.fMutex.Unlock()
w.fWrapper.Set(db)
return w
p.fWrapper.Set(pDB)
return p
}
func (w *sWrapperDB) Close() error {
w.fMutex.Lock()
defer w.fMutex.Unlock()
func (p *sWrapperDB) Close() error {
p.fMutex.Lock()
defer p.fMutex.Unlock()
db, ok := w.fWrapper.Get().(database.IKeyValueDB)
db, ok := p.fWrapper.Get().(database.IKeyValueDB)
if !ok {
return nil
}

View File

@ -22,39 +22,39 @@ type sConn struct {
fSettings ISettings
}
func NewConn(sett ISettings, address string) (IConn, error) {
conn, err := net.Dial("tcp", address)
func NewConn(pSett ISettings, pAddr string) (IConn, error) {
conn, err := net.Dial("tcp", pAddr)
if err != nil {
return nil, err
}
return LoadConn(sett, conn), nil
return LoadConn(pSett, conn), nil
}
func LoadConn(sett ISettings, conn net.Conn) IConn {
func LoadConn(pSett ISettings, pConn net.Conn) IConn {
return &sConn{
fSettings: sett,
fSocket: conn,
fSettings: pSett,
fSocket: pConn,
}
}
func (conn *sConn) GetSettings() ISettings {
return conn.fSettings
func (p *sConn) GetSettings() ISettings {
return p.fSettings
}
func (conn *sConn) GetSocket() net.Conn {
return conn.fSocket
func (p *sConn) GetSocket() net.Conn {
return p.fSocket
}
func (conn *sConn) FetchPayload(pld payload.IPayload) (payload.IPayload, error) {
func (p *sConn) FetchPayload(pPld payload.IPayload) (payload.IPayload, error) {
var (
chPld = make(chan payload.IPayload)
timeWait = conn.fSettings.GetTimeWait()
timeWait = p.fSettings.GetTimeWait()
)
if err := conn.WritePayload(pld); err != nil {
if err := p.WritePayload(pPld); err != nil {
return nil, err
}
go readPayload(conn, chPld)
go readPayload(p, chPld)
select {
case rpld := <-chPld:
@ -67,22 +67,22 @@ func (conn *sConn) FetchPayload(pld payload.IPayload) (payload.IPayload, error)
}
}
func (conn *sConn) Close() error {
return conn.GetSocket().Close()
func (p *sConn) Close() error {
return p.GetSocket().Close()
}
func (conn *sConn) WritePayload(pld payload.IPayload) error {
conn.fMutex.Lock()
defer conn.fMutex.Unlock()
func (p *sConn) WritePayload(pPld payload.IPayload) error {
p.fMutex.Lock()
defer p.fMutex.Unlock()
var (
msgBytes = message.NewMessage(pld, []byte(conn.fSettings.GetNetworkKey())).GetBytes()
msgBytes = message.NewMessage(pPld, []byte(p.fSettings.GetNetworkKey())).GetBytes()
packBytes = payload.NewPayload(uint64(len(msgBytes)), msgBytes).ToBytes()
packPtr = len(packBytes)
)
for {
n, err := conn.GetSocket().Write(packBytes[:packPtr])
n, err := p.GetSocket().Write(packBytes[:packPtr])
if err != nil {
return err
}
@ -98,21 +98,21 @@ func (conn *sConn) WritePayload(pld payload.IPayload) error {
return nil
}
func (conn *sConn) ReadPayload() payload.IPayload {
func (p *sConn) ReadPayload() payload.IPayload {
chPld := make(chan payload.IPayload)
go readPayload(conn, chPld)
go readPayload(p, chPld)
return <-chPld
}
func readPayload(conn *sConn, chPld chan payload.IPayload) {
func readPayload(pConn *sConn, pChPld chan payload.IPayload) {
var pld payload.IPayload
defer func() {
chPld <- pld
pChPld <- pld
}()
// bufLen = Size[u64] in bytes
bufLen := make([]byte, encoding.CSizeUint64)
length, err := conn.GetSocket().Read(bufLen)
length, err := pConn.GetSocket().Read(bufLen)
if err != nil {
return
}
@ -125,14 +125,14 @@ func readPayload(conn *sConn, chPld chan payload.IPayload) {
copy(arrLen[:], bufLen)
mustLen := encoding.BytesToUint64(arrLen)
if mustLen > conn.fSettings.GetMessageSize() {
if mustLen > pConn.fSettings.GetMessageSize() {
return
}
msgRaw := make([]byte, 0, mustLen)
for {
buffer := make([]byte, mustLen)
n, err := conn.GetSocket().Read(buffer)
n, err := pConn.GetSocket().Read(buffer)
if err != nil {
return
}
@ -154,7 +154,7 @@ func readPayload(conn *sConn, chPld chan payload.IPayload) {
// try unpack message from bytes
msg := message.LoadMessage(
msgRaw,
[]byte(conn.fSettings.GetNetworkKey()),
[]byte(pConn.fSettings.GetNetworkKey()),
)
if msg == nil {
return

View File

@ -19,35 +19,35 @@ type sSettings struct {
FTimeWait time.Duration
}
func NewSettings(sett *SSettings) ISettings {
func NewSettings(pSett *SSettings) ISettings {
return (&sSettings{
FNetworkKey: sett.FNetworkKey,
FMessageSize: sett.FMessageSize,
FTimeWait: sett.FTimeWait,
FNetworkKey: pSett.FNetworkKey,
FMessageSize: pSett.FMessageSize,
FTimeWait: pSett.FTimeWait,
}).useDefaultValues()
}
func (s *sSettings) useDefaultValues() ISettings {
if s.FNetworkKey == "" {
s.FNetworkKey = cNetworkKey
func (p *sSettings) useDefaultValues() ISettings {
if p.FNetworkKey == "" {
p.FNetworkKey = cNetworkKey
}
if s.FMessageSize == 0 {
s.FMessageSize = cMessageSize
if p.FMessageSize == 0 {
p.FMessageSize = cMessageSize
}
if s.FTimeWait == 0 {
s.FTimeWait = cTimeWait
if p.FTimeWait == 0 {
p.FTimeWait = cTimeWait
}
return s
return p
}
func (s *sSettings) GetNetworkKey() string {
return s.FNetworkKey
func (p *sSettings) GetNetworkKey() string {
return p.FNetworkKey
}
func (s *sSettings) GetMessageSize() uint64 {
return s.FMessageSize
func (p *sSettings) GetMessageSize() uint64 {
return p.FMessageSize
}
func (s *sSettings) GetTimeWait() time.Duration {
return s.FTimeWait
func (p *sSettings) GetTimeWait() time.Duration {
return p.FTimeWait
}

View File

@ -20,40 +20,40 @@ type sConnKeeper struct {
fSettings ISettings
}
func NewConnKeeper(sett ISettings, node network.INode) IConnKeeper {
func NewConnKeeper(pSett ISettings, pNode network.INode) IConnKeeper {
return &sConnKeeper{
fNode: node,
fSettings: sett,
fNode: pNode,
fSettings: pSett,
}
}
func (connKeeper *sConnKeeper) GetNetworkNode() network.INode {
return connKeeper.fNode
func (p *sConnKeeper) GetNetworkNode() network.INode {
return p.fNode
}
func (connKeeper *sConnKeeper) GetSettings() ISettings {
return connKeeper.fSettings
func (p *sConnKeeper) GetSettings() ISettings {
return p.fSettings
}
func (connKeeper *sConnKeeper) Run() error {
connKeeper.fMutex.Lock()
defer connKeeper.fMutex.Unlock()
func (p *sConnKeeper) Run() error {
p.fMutex.Lock()
defer p.fMutex.Unlock()
if connKeeper.fIsRun {
if p.fIsRun {
return errors.New("conn keeper already started")
}
connKeeper.fIsRun = true
p.fIsRun = true
connKeeper.fSignal = make(chan struct{})
connKeeper.tryConnectToAll()
p.fSignal = make(chan struct{})
p.tryConnectToAll()
go func() {
for {
select {
case <-connKeeper.readSignal():
case <-p.readSignal():
return
case <-time.After(connKeeper.GetSettings().GetDuration()):
connKeeper.tryConnectToAll()
case <-time.After(p.GetSettings().GetDuration()):
p.tryConnectToAll()
}
}
}()
@ -61,34 +61,35 @@ func (connKeeper *sConnKeeper) Run() error {
return nil
}
func (connKeeper *sConnKeeper) Stop() error {
connKeeper.fMutex.Lock()
defer connKeeper.fMutex.Unlock()
func (p *sConnKeeper) Stop() error {
p.fMutex.Lock()
defer p.fMutex.Unlock()
if !connKeeper.fIsRun {
if !p.fIsRun {
return errors.New("conn keeper already closed or not started")
}
connKeeper.fIsRun = false
p.fIsRun = false
close(connKeeper.fSignal)
close(p.fSignal)
return nil
}
func (connKeeper *sConnKeeper) tryConnectToAll() {
func (p *sConnKeeper) tryConnectToAll() {
NEXT:
for _, address := range connKeeper.GetSettings().GetConnections() {
for addr := range connKeeper.fNode.GetConnections() {
for _, address := range p.GetSettings().GetConnections() {
for addr := range p.fNode.GetConnections() {
if addr == address {
// no need add connect
continue NEXT
}
}
connKeeper.fNode.AddConnect(address)
p.fNode.AddConnect(address)
}
}
func (connKeeper *sConnKeeper) readSignal() <-chan struct{} {
connKeeper.fMutex.Lock()
defer connKeeper.fMutex.Unlock()
func (p *sConnKeeper) readSignal() <-chan struct{} {
p.fMutex.Lock()
defer p.fMutex.Unlock()
return connKeeper.fSignal
return p.fSignal
}

View File

@ -20,27 +20,27 @@ type sSettings struct {
FDuration time.Duration
}
func NewSettings(sett *SSettings) ISettings {
func NewSettings(pSett *SSettings) ISettings {
return (&sSettings{
FConnections: sett.FConnections,
FDuration: sett.FDuration,
FConnections: pSett.FConnections,
FDuration: pSett.FDuration,
}).useDefaultValue()
}
func (s *sSettings) useDefaultValue() ISettings {
if s.FDuration == 0 {
s.FDuration = cDuration
func (p *sSettings) useDefaultValue() ISettings {
if p.FDuration == 0 {
p.FDuration = cDuration
}
if s.FConnections == nil {
s.FConnections = gConnections
if p.FConnections == nil {
p.FConnections = gConnections
}
return s
return p
}
func (s *sSettings) GetConnections() []string {
return s.FConnections()
func (p *sSettings) GetConnections() []string {
return p.FConnections()
}
func (s *sSettings) GetDuration() time.Duration {
return s.FDuration
func (p *sSettings) GetDuration() time.Duration {
return p.FDuration
}

View File

@ -16,28 +16,28 @@ type sMessage struct {
fPayload payload.IPayload
}
func NewMessage(pld payload.IPayload, key []byte) IMessage {
func NewMessage(pPld payload.IPayload, pKey []byte) IMessage {
return &sMessage{
fHash: hashing.NewHMACSHA256Hasher(
key,
pld.ToBytes(),
pKey,
pPld.ToBytes(),
).ToBytes(),
fPayload: pld,
fPayload: pPld,
}
}
func LoadMessage(packData, key []byte) IMessage {
func LoadMessage(pData, pKey []byte) IMessage {
// check Hash[uN]
if len(packData) < hashing.CSHA256Size {
if len(pData) < hashing.CSHA256Size {
return nil
}
hashRecv := packData[:hashing.CSHA256Size]
payloadBytes := packData[hashing.CSHA256Size:]
hashRecv := pData[:hashing.CSHA256Size]
payloadBytes := pData[hashing.CSHA256Size:]
if !bytes.Equal(
hashRecv,
hashing.NewHMACSHA256Hasher(
key,
pKey,
payloadBytes,
).ToBytes(),
) {
@ -56,19 +56,19 @@ func LoadMessage(packData, key []byte) IMessage {
}
}
func (msg *sMessage) GetHash() []byte {
return msg.fHash
func (p *sMessage) GetHash() []byte {
return p.fHash
}
func (msg *sMessage) GetPayload() payload.IPayload {
return msg.fPayload
func (p *sMessage) GetPayload() payload.IPayload {
return p.fPayload
}
func (msg *sMessage) GetBytes() []byte {
func (p *sMessage) GetBytes() []byte {
return bytes.Join(
[][]byte{
msg.fHash,
msg.fPayload.ToBytes(),
p.fHash,
p.fPayload.ToBytes(),
},
[]byte{},
)

View File

@ -28,28 +28,28 @@ type sNode struct {
// Creating a node object managed by connections with multiple nodes.
// Saves hashes of received messages to a buffer to prevent network cycling.
// Redirects messages to handle routers by keys.
func NewNode(sett ISettings) INode {
func NewNode(pSett ISettings) INode {
return &sNode{
fSettings: sett,
fHashMapping: storage.NewMemoryStorage(sett.GetCapacity()),
fSettings: pSett,
fHashMapping: storage.NewMemoryStorage(pSett.GetCapacity()),
fConnections: make(map[string]conn.IConn),
fHandleRoutes: make(map[uint64]IHandlerF),
}
}
// Return settings interface.
func (node *sNode) GetSettings() ISettings {
return node.fSettings
func (p *sNode) GetSettings() ISettings {
return p.fSettings
}
// Puts the hash of the message in the buffer and sends the message to all connections of the node.
func (node *sNode) BroadcastPayload(pld payload.IPayload) error {
hasher := hashing.NewSHA256Hasher(pld.ToBytes())
node.inMappingWithSet(hasher.ToBytes())
func (p *sNode) BroadcastPayload(pPld payload.IPayload) error {
hasher := hashing.NewSHA256Hasher(pPld.ToBytes())
p.inMappingWithSet(hasher.ToBytes())
var err error
for _, conn := range node.GetConnections() {
e := conn.WritePayload(pld)
for _, conn := range p.GetConnections() {
e := conn.WritePayload(pPld)
if e != nil {
err = e
}
@ -61,32 +61,32 @@ func (node *sNode) BroadcastPayload(pld payload.IPayload) error {
// Opens a tcp connection to receive data from outside.
// Checks the number of valid connections.
// Redirects connections to the handle router.
func (node *sNode) Run() error {
listener, err := net.Listen("tcp", node.GetSettings().GetAddress())
func (p *sNode) Run() error {
listener, err := net.Listen("tcp", p.GetSettings().GetAddress())
if err != nil {
return err
}
go func(l net.Listener) {
defer l.Close()
node.setListener(l)
go func(pListener net.Listener) {
defer pListener.Close()
p.setListener(pListener)
for {
tconn, err := node.getListener().Accept()
tconn, err := p.getListener().Accept()
if err != nil {
break
}
if node.hasMaxConnSize() {
if p.hasMaxConnSize() {
tconn.Close()
continue
}
sett := node.GetSettings().GetConnSettings()
sett := p.GetSettings().GetConnSettings()
conn := conn.LoadConn(sett, tconn)
address := tconn.RemoteAddr().String()
node.setConnection(address, conn)
go node.handleConn(address, conn)
p.setConnection(address, conn)
go p.handleConn(address, conn)
}
}(listener)
@ -94,39 +94,39 @@ func (node *sNode) Run() error {
}
// Closes the listener and all connections.
func (node *sNode) Stop() error {
node.fMutex.Lock()
defer node.fMutex.Unlock()
func (p *sNode) Stop() error {
p.fMutex.Lock()
defer p.fMutex.Unlock()
toClose := make([]types.ICloser, 0, len(node.fConnections)+1)
if node.fListener != nil {
toClose = append(toClose, node.fListener)
toClose := make([]types.ICloser, 0, len(p.fConnections)+1)
if p.fListener != nil {
toClose = append(toClose, p.fListener)
}
for id, conn := range node.fConnections {
for id, conn := range p.fConnections {
toClose = append(toClose, conn)
delete(node.fConnections, id)
delete(p.fConnections, id)
}
return types.CloseAll(toClose)
}
// Saves the function to the map by key for subsequent redirection.
func (node *sNode) HandleFunc(head uint64, handle IHandlerF) INode {
node.fMutex.Lock()
defer node.fMutex.Unlock()
func (p *sNode) HandleFunc(pHead uint64, pHandle IHandlerF) INode {
p.fMutex.Lock()
defer p.fMutex.Unlock()
node.fHandleRoutes[head] = handle
return node
p.fHandleRoutes[pHead] = pHandle
return p
}
// Retrieves the entire list of connections with addresses.
func (node *sNode) GetConnections() map[string]conn.IConn {
node.fMutex.Lock()
defer node.fMutex.Unlock()
func (p *sNode) GetConnections() map[string]conn.IConn {
p.fMutex.Lock()
defer p.fMutex.Unlock()
var mapping = make(map[string]conn.IConn, len(node.fConnections))
for addr, conn := range node.fConnections {
var mapping = make(map[string]conn.IConn, len(p.fConnections))
for addr, conn := range p.fConnections {
mapping[addr] = conn
}
@ -135,42 +135,42 @@ func (node *sNode) GetConnections() map[string]conn.IConn {
// Connects to the node at the specified address and automatically starts reading all incoming messages.
// Checks the number of connections.
func (node *sNode) AddConnect(address string) error {
if node.hasMaxConnSize() {
func (p *sNode) AddConnect(pAddress string) error {
if p.hasMaxConnSize() {
return fmt.Errorf("has max connections size")
}
sett := node.GetSettings().GetConnSettings()
conn, err := conn.NewConn(sett, address)
sett := p.GetSettings().GetConnSettings()
conn, err := conn.NewConn(sett, pAddress)
if err != nil {
return err
}
node.setConnection(address, conn)
go node.handleConn(address, conn)
p.setConnection(pAddress, conn)
go p.handleConn(pAddress, conn)
return nil
}
// Disables the connection at the address and removes the connection from the connection list.
func (node *sNode) DelConnect(address string) error {
node.fMutex.Lock()
defer node.fMutex.Unlock()
func (p *sNode) DelConnect(pAddress string) error {
p.fMutex.Lock()
defer p.fMutex.Unlock()
conn, ok := node.fConnections[address]
conn, ok := p.fConnections[pAddress]
if !ok {
return nil
}
delete(node.fConnections, address)
delete(p.fConnections, pAddress)
return conn.Close()
}
// Processes the received data from the connection.
func (node *sNode) handleConn(address string, conn conn.IConn) {
defer node.DelConnect(address)
func (p *sNode) handleConn(pAddress string, pConn conn.IConn) {
defer p.DelConnect(pAddress)
for {
ok := node.handleMessage(conn, conn.ReadPayload())
ok := p.handleMessage(pConn, pConn.ReadPayload())
if !ok {
break
}
@ -180,83 +180,83 @@ func (node *sNode) handleConn(address string, conn conn.IConn) {
// Processes the message for correctness and redirects it to the handler function.
// Returns true if the message was successfully redirected to the handler function
// > or if the message already existed in the hash value store.
func (node *sNode) handleMessage(conn conn.IConn, pld payload.IPayload) bool {
func (p *sNode) handleMessage(pConn conn.IConn, pPld payload.IPayload) bool {
// null message from connection is error
if pld == nil {
if pPld == nil {
return false
}
// check message in mapping by hash
hash := hashing.NewSHA256Hasher(pld.ToBytes()).ToBytes()
if node.inMappingWithSet(hash) {
hash := hashing.NewSHA256Hasher(pPld.ToBytes()).ToBytes()
if p.inMappingWithSet(hash) {
return true
}
// get function by head
f, ok := node.getFunction(pld.GetHead())
f, ok := p.getFunction(pPld.GetHead())
if !ok || f == nil {
return false
}
f(node, conn, pld.GetBody())
f(p, pConn, pPld.GetBody())
return true
}
// Checks the current number of connections with the limit.
func (node *sNode) hasMaxConnSize() bool {
node.fMutex.Lock()
defer node.fMutex.Unlock()
func (p *sNode) hasMaxConnSize() bool {
p.fMutex.Lock()
defer p.fMutex.Unlock()
maxConns := node.GetSettings().GetMaxConnects()
return uint64(len(node.fConnections)) > maxConns
maxConns := p.GetSettings().GetMaxConnects()
return uint64(len(p.fConnections)) > maxConns
}
// Checks the hash of the message for existence in the hash store.
// Returns true if the hash already existed, otherwise false.
func (node *sNode) inMappingWithSet(hash []byte) bool {
node.fMutex.Lock()
defer node.fMutex.Unlock()
func (p *sNode) inMappingWithSet(pHash []byte) bool {
p.fMutex.Lock()
defer p.fMutex.Unlock()
// skey already exists
_, err := node.fHashMapping.Get(hash)
_, err := p.fHashMapping.Get(pHash)
if err == nil {
return true
}
// push skey to mapping
node.fHashMapping.Set(hash, []byte{1})
p.fHashMapping.Set(pHash, []byte{1})
return false
}
// Saves the connection to the map.
func (node *sNode) setConnection(address string, conn conn.IConn) {
node.fMutex.Lock()
defer node.fMutex.Unlock()
func (p *sNode) setConnection(pAddress string, pConn conn.IConn) {
p.fMutex.Lock()
defer p.fMutex.Unlock()
node.fConnections[address] = conn
p.fConnections[pAddress] = pConn
}
// Gets the handler function by key.
func (node *sNode) getFunction(head uint64) (IHandlerF, bool) {
node.fMutex.Lock()
defer node.fMutex.Unlock()
func (p *sNode) getFunction(pHead uint64) (IHandlerF, bool) {
p.fMutex.Lock()
defer p.fMutex.Unlock()
f, ok := node.fHandleRoutes[head]
f, ok := p.fHandleRoutes[pHead]
return f, ok
}
// Sets the listener.
func (node *sNode) setListener(listener net.Listener) {
node.fMutex.Lock()
defer node.fMutex.Unlock()
func (p *sNode) setListener(pListener net.Listener) {
p.fMutex.Lock()
defer p.fMutex.Unlock()
node.fListener = listener
p.fListener = pListener
}
// Gets the listener.
func (node *sNode) getListener() net.Listener {
node.fMutex.Lock()
defer node.fMutex.Unlock()
func (p *sNode) getListener() net.Listener {
p.fMutex.Lock()
defer p.fMutex.Unlock()
return node.fListener
return p.fListener
}

View File

@ -20,43 +20,43 @@ type sSettings struct {
FConnSettings conn.ISettings
}
func NewSettings(sett *SSettings) ISettings {
func NewSettings(pSett *SSettings) ISettings {
return (&sSettings{
FAddress: sett.FAddress,
FCapacity: sett.FCapacity,
FMaxConnects: sett.FMaxConnects,
FConnSettings: sett.FConnSettings,
FAddress: pSett.FAddress,
FCapacity: pSett.FCapacity,
FMaxConnects: pSett.FMaxConnects,
FConnSettings: pSett.FConnSettings,
}).useDefaultValues()
}
func (s *sSettings) useDefaultValues() ISettings {
if s.FAddress == "" {
s.FAddress = cAddress
func (p *sSettings) useDefaultValues() ISettings {
if p.FAddress == "" {
p.FAddress = cAddress
}
if s.FCapacity == 0 {
s.FCapacity = cCapacity
if p.FCapacity == 0 {
p.FCapacity = cCapacity
}
if s.FMaxConnects == 0 {
s.FMaxConnects = cMaxConnects
if p.FMaxConnects == 0 {
p.FMaxConnects = cMaxConnects
}
if s.FConnSettings == nil {
s.FConnSettings = conn.NewSettings(&conn.SSettings{})
if p.FConnSettings == nil {
p.FConnSettings = conn.NewSettings(&conn.SSettings{})
}
return s
return p
}
func (s *sSettings) GetAddress() string {
return s.FAddress
func (p *sSettings) GetAddress() string {
return p.FAddress
}
func (s *sSettings) GetCapacity() uint64 {
return s.FCapacity
func (p *sSettings) GetCapacity() uint64 {
return p.FCapacity
}
func (s *sSettings) GetMaxConnects() uint64 {
return s.FMaxConnects
func (p *sSettings) GetMaxConnects() uint64 {
return p.FMaxConnects
}
func (s *sSettings) GetConnSettings() conn.ISettings {
return s.FConnSettings
func (p *sSettings) GetConnSettings() conn.ISettings {
return p.FConnSettings
}

View File

@ -12,31 +12,31 @@ var (
type sPayload []byte
func NewPayload(head uint64, data []byte) IPayload {
bHead := encoding.Uint64ToBytes(head)
func NewPayload(pHead uint64, pData []byte) IPayload {
bHead := encoding.Uint64ToBytes(pHead)
return sPayload(bytes.Join([][]byte{
bHead[:],
data,
pData,
}, []byte{}))
}
func LoadPayload(payloadBytes []byte) IPayload {
if len(payloadBytes) < encoding.CSizeUint64 {
func LoadPayload(pPayloadBytes []byte) IPayload {
if len(pPayloadBytes) < encoding.CSizeUint64 {
return nil
}
return sPayload(payloadBytes)
return sPayload(pPayloadBytes)
}
func (payload sPayload) GetHead() uint64 {
func (p sPayload) GetHead() uint64 {
bHead := [encoding.CSizeUint64]byte{}
copy(bHead[:], payload[:encoding.CSizeUint64])
copy(bHead[:], p[:encoding.CSizeUint64])
return encoding.BytesToUint64(bHead)
}
func (payload sPayload) GetBody() []byte {
return payload[encoding.CSizeUint64:]
func (p sPayload) GetBody() []byte {
return p[encoding.CSizeUint64:]
}
func (payload sPayload) ToBytes() []byte {
return payload[:]
func (p sPayload) ToBytes() []byte {
return p[:]
}

View File

@ -29,14 +29,14 @@ type storageData struct {
FSecrets map[string][]byte `json:"secrets"`
}
func NewCryptoStorage(path string, key []byte, workSize uint64) (IKeyValueStorage, error) {
func NewCryptoStorage(pPath string, pKey []byte, pWorkSize uint64) (IKeyValueStorage, error) {
store := &sCryptoStorage{
fPath: path,
fWorkSize: workSize,
fPath: pPath,
fWorkSize: pWorkSize,
}
if store.exists() {
encdata, err := filesystem.OpenFile(path).Read()
encdata, err := filesystem.OpenFile(pPath).Read()
if err != nil {
return nil, err
}
@ -46,7 +46,7 @@ func NewCryptoStorage(path string, key []byte, workSize uint64) (IKeyValueStorag
}
entropy := entropy.NewEntropyBooster(store.fWorkSize, store.fSalt)
store.fCipher = symmetric.NewAESCipher(entropy.BoostEntropy(key))
store.fCipher = symmetric.NewAESCipher(entropy.BoostEntropy(pKey))
if !store.exists() {
store.Set(nil, nil)
@ -60,9 +60,9 @@ func NewCryptoStorage(path string, key []byte, workSize uint64) (IKeyValueStorag
return store, nil
}
func (store *sCryptoStorage) Set(key, value []byte) error {
store.fMutex.Lock()
defer store.fMutex.Unlock()
func (p *sCryptoStorage) Set(pKey, pValue []byte) error {
p.fMutex.Lock()
defer p.fMutex.Unlock()
var (
mapping storageData
@ -70,8 +70,8 @@ func (store *sCryptoStorage) Set(key, value []byte) error {
)
// Open and decrypt storage
if store.exists() {
mapping, err = store.decrypt()
if p.exists() {
mapping, err = p.decrypt()
if err != nil {
return err
}
@ -80,34 +80,34 @@ func (store *sCryptoStorage) Set(key, value []byte) error {
}
// Encrypt and save private key into storage
entropy := entropy.NewEntropyBooster(store.fWorkSize, store.fSalt)
ekey := entropy.BoostEntropy(key)
entropy := entropy.NewEntropyBooster(p.fWorkSize, p.fSalt)
ekey := entropy.BoostEntropy(pKey)
hash := hashing.NewSHA256Hasher(ekey).ToString()
cipher := symmetric.NewAESCipher(ekey)
mapping.FSecrets[hash] = cipher.EncryptBytes(value)
mapping.FSecrets[hash] = cipher.EncryptBytes(pValue)
return store.encrypt(&mapping)
return p.encrypt(&mapping)
}
func (store *sCryptoStorage) Get(key []byte) ([]byte, error) {
store.fMutex.Lock()
defer store.fMutex.Unlock()
func (p *sCryptoStorage) Get(pKey []byte) ([]byte, error) {
p.fMutex.Lock()
defer p.fMutex.Unlock()
// If storage not exists.
if !store.exists() {
if !p.exists() {
return nil, fmt.Errorf("error: storage undefined")
}
// Open and decrypt storage
mapping, err := store.decrypt()
mapping, err := p.decrypt()
if err != nil {
return nil, err
}
// Open and decrypt private key
entropy := entropy.NewEntropyBooster(store.fWorkSize, store.fSalt)
ekey := entropy.BoostEntropy(key)
entropy := entropy.NewEntropyBooster(p.fWorkSize, p.fSalt)
ekey := entropy.BoostEntropy(pKey)
hash := hashing.NewSHA256Hasher(ekey).ToString()
encsecret, ok := mapping.FSecrets[hash]
@ -121,24 +121,24 @@ func (store *sCryptoStorage) Get(key []byte) ([]byte, error) {
return secret, nil
}
func (store *sCryptoStorage) Del(key []byte) error {
store.fMutex.Lock()
defer store.fMutex.Unlock()
func (p *sCryptoStorage) Del(pKey []byte) error {
p.fMutex.Lock()
defer p.fMutex.Unlock()
// If storage not exists.
if !store.exists() {
if !p.exists() {
return fmt.Errorf("error: storage undefined")
}
// Open and decrypt storage
mapping, err := store.decrypt()
mapping, err := p.decrypt()
if err != nil {
return err
}
// Open and decrypt private key
entropy := entropy.NewEntropyBooster(store.fWorkSize, store.fSalt)
hash := hashing.NewSHA256Hasher(entropy.BoostEntropy(key)).ToString()
entropy := entropy.NewEntropyBooster(p.fWorkSize, p.fSalt)
hash := hashing.NewSHA256Hasher(entropy.BoostEntropy(pKey)).ToString()
_, ok := mapping.FSecrets[hash]
if !ok {
@ -146,23 +146,23 @@ func (store *sCryptoStorage) Del(key []byte) error {
}
delete(mapping.FSecrets, hash)
return store.encrypt(&mapping)
return p.encrypt(&mapping)
}
func (store *sCryptoStorage) exists() bool {
return filesystem.OpenFile(store.fPath).IsExist()
func (p *sCryptoStorage) exists() bool {
return filesystem.OpenFile(p.fPath).IsExist()
}
func (store *sCryptoStorage) encrypt(mapping *storageData) error {
func (p *sCryptoStorage) encrypt(pMapping *storageData) error {
// Encrypt and save storage
data, err := json.Marshal(mapping)
data, err := json.Marshal(pMapping)
if err != nil {
return err
}
err = filesystem.OpenFile(store.fPath).Write(
err = filesystem.OpenFile(p.fPath).Write(
bytes.Join(
[][]byte{store.fSalt, store.fCipher.EncryptBytes(data)},
[][]byte{p.fSalt, p.fCipher.EncryptBytes(data)},
[]byte{},
),
)
@ -173,15 +173,15 @@ func (store *sCryptoStorage) encrypt(mapping *storageData) error {
return nil
}
func (store *sCryptoStorage) decrypt() (storageData, error) {
func (p *sCryptoStorage) decrypt() (storageData, error) {
var mapping storageData
encdata, err := filesystem.OpenFile(store.fPath).Read()
encdata, err := filesystem.OpenFile(p.fPath).Read()
if err != nil {
return storageData{}, err
}
data := store.fCipher.DecryptBytes(encdata[symmetric.CAESKeySize:])
data := p.fCipher.DecryptBytes(encdata[symmetric.CAESKeySize:])
err = json.Unmarshal(data, &mapping)
if err != nil {
return storageData{}, err

View File

@ -32,106 +32,106 @@ type sLevelDBIterator struct {
fCipher symmetric.ICipher
}
func NewLevelDB(sett ISettings) IKeyValueDB {
db, err := leveldb.OpenFile(sett.GetPath(), nil)
func NewLevelDB(pSett ISettings) IKeyValueDB {
db, err := leveldb.OpenFile(pSett.GetPath(), nil)
if err != nil {
return nil
}
salt, err := db.Get(sett.GetSaltKey(), nil)
salt, err := db.Get(pSett.GetSaltKey(), nil)
if err != nil {
salt = random.NewStdPRNG().GetBytes(symmetric.CAESKeySize)
if err := db.Put(sett.GetSaltKey(), salt, nil); err != nil {
if err := db.Put(pSett.GetSaltKey(), salt, nil); err != nil {
return nil
}
}
return &sLevelDB{
fSalt: salt,
fDB: db,
fSettings: sett,
fCipher: symmetric.NewAESCipher(sett.GetCipherKey()),
fSettings: pSett,
fCipher: symmetric.NewAESCipher(pSett.GetCipherKey()),
}
}
func (db *sLevelDB) GetSettings() ISettings {
return db.fSettings
func (p *sLevelDB) GetSettings() ISettings {
return p.fSettings
}
func (db *sLevelDB) Set(key []byte, value []byte) error {
db.fMutex.Lock()
defer db.fMutex.Unlock()
func (p *sLevelDB) Set(pKey []byte, pValue []byte) error {
p.fMutex.Lock()
defer p.fMutex.Unlock()
return db.fDB.Put(
db.tryHash(key),
doEncrypt(db.fCipher, value),
return p.fDB.Put(
p.tryHash(pKey),
doEncrypt(p.fCipher, pValue),
nil,
)
}
func (db *sLevelDB) Get(key []byte) ([]byte, error) {
db.fMutex.Lock()
defer db.fMutex.Unlock()
func (p *sLevelDB) Get(pKey []byte) ([]byte, error) {
p.fMutex.Lock()
defer p.fMutex.Unlock()
encBytes, err := db.fDB.Get(db.tryHash(key), nil)
encBytes, err := p.fDB.Get(p.tryHash(pKey), nil)
if err != nil {
return nil, err
}
return tryDecrypt(
db.fCipher,
p.fCipher,
encBytes,
)
}
func (db *sLevelDB) Del(key []byte) error {
db.fMutex.Lock()
defer db.fMutex.Unlock()
func (p *sLevelDB) Del(pKey []byte) error {
p.fMutex.Lock()
defer p.fMutex.Unlock()
return db.fDB.Delete(db.tryHash(key), nil)
return p.fDB.Delete(p.tryHash(pKey), nil)
}
func (db *sLevelDB) Close() error {
db.fMutex.Lock()
defer db.fMutex.Unlock()
func (p *sLevelDB) Close() error {
p.fMutex.Lock()
defer p.fMutex.Unlock()
return db.fDB.Close()
return p.fDB.Close()
}
// Storage in hashing mode can't iterates
func (db *sLevelDB) GetIterator(prefix []byte) IIterator {
db.fMutex.Lock()
defer db.fMutex.Unlock()
func (p *sLevelDB) GetIterator(pPrefix []byte) IIterator {
p.fMutex.Lock()
defer p.fMutex.Unlock()
if db.fSettings.GetHashing() {
if p.fSettings.GetHashing() {
return nil
}
return &sLevelDBIterator{
fIter: db.fDB.NewIterator(util.BytesPrefix(prefix), nil),
fCipher: db.fCipher,
fIter: p.fDB.NewIterator(util.BytesPrefix(pPrefix), nil),
fCipher: p.fCipher,
}
}
func (iter *sLevelDBIterator) Next() bool {
iter.fMutex.Lock()
defer iter.fMutex.Unlock()
func (p *sLevelDBIterator) Next() bool {
p.fMutex.Lock()
defer p.fMutex.Unlock()
return iter.fIter.Next()
return p.fIter.Next()
}
func (iter *sLevelDBIterator) GetKey() []byte {
iter.fMutex.Lock()
defer iter.fMutex.Unlock()
func (p *sLevelDBIterator) GetKey() []byte {
p.fMutex.Lock()
defer p.fMutex.Unlock()
return iter.fIter.Key()
return p.fIter.Key()
}
func (iter *sLevelDBIterator) GetValue() []byte {
iter.fMutex.Lock()
defer iter.fMutex.Unlock()
func (p *sLevelDBIterator) GetValue() []byte {
p.fMutex.Lock()
defer p.fMutex.Unlock()
decBytes, err := tryDecrypt(
iter.fCipher,
iter.fIter.Value(),
p.fCipher,
p.fIter.Value(),
)
if err != nil {
return nil
@ -139,40 +139,40 @@ func (iter *sLevelDBIterator) GetValue() []byte {
return decBytes
}
func (iter *sLevelDBIterator) Close() error {
iter.fMutex.Lock()
defer iter.fMutex.Unlock()
func (p *sLevelDBIterator) Close() error {
p.fMutex.Lock()
defer p.fMutex.Unlock()
iter.fIter.Release()
p.fIter.Release()
return nil
}
func doEncrypt(cipher symmetric.ICipher, dataBytes []byte) []byte {
func doEncrypt(pCipher symmetric.ICipher, pDataBytes []byte) []byte {
return bytes.Join(
[][]byte{
hashing.NewHMACSHA256Hasher(
cipher.ToBytes(),
dataBytes,
pCipher.ToBytes(),
pDataBytes,
).ToBytes(),
cipher.EncryptBytes(dataBytes),
pCipher.EncryptBytes(pDataBytes),
},
[]byte{},
)
}
func tryDecrypt(cipher symmetric.ICipher, encBytes []byte) ([]byte, error) {
if len(encBytes) < hashing.CSHA256Size+symmetric.CAESBlockSize {
func tryDecrypt(pCipher symmetric.ICipher, pEncBytes []byte) ([]byte, error) {
if len(pEncBytes) < hashing.CSHA256Size+symmetric.CAESBlockSize {
return nil, fmt.Errorf("incorrect size of encrypted data")
}
decBytes := cipher.DecryptBytes(encBytes[hashing.CSHA256Size:])
decBytes := pCipher.DecryptBytes(pEncBytes[hashing.CSHA256Size:])
if decBytes == nil {
return nil, fmt.Errorf("failed decrypt message")
}
gotHashed := encBytes[:hashing.CSHA256Size]
gotHashed := pEncBytes[:hashing.CSHA256Size]
newHashed := hashing.NewHMACSHA256Hasher(
cipher.ToBytes(),
pCipher.ToBytes(),
decBytes,
).ToBytes()
@ -183,14 +183,14 @@ func tryDecrypt(cipher symmetric.ICipher, encBytes []byte) ([]byte, error) {
return decBytes, nil
}
func (db *sLevelDB) tryHash(key []byte) []byte {
if !db.fSettings.GetHashing() {
return key
func (p *sLevelDB) tryHash(pKey []byte) []byte {
if !p.fSettings.GetHashing() {
return pKey
}
saltWithKey := bytes.Join(
[][]byte{
db.fSalt,
key,
p.fSalt,
pKey,
},
[]byte{},
)

View File

@ -18,40 +18,40 @@ type sSettings struct {
FCipherKey []byte
}
func NewSettings(sett *SSettings) ISettings {
func NewSettings(pSett *SSettings) ISettings {
return (&sSettings{
FPath: sett.FPath,
FHashing: sett.FHashing,
FSaltKey: sett.FSaltKey,
FCipherKey: sett.FCipherKey,
FPath: pSett.FPath,
FHashing: pSett.FHashing,
FSaltKey: pSett.FSaltKey,
FCipherKey: pSett.FCipherKey,
}).useDefaultValues()
}
func (s *sSettings) useDefaultValues() ISettings {
if s.FPath == "" {
s.FPath = cPath
func (p *sSettings) useDefaultValues() ISettings {
if p.FPath == "" {
p.FPath = cPath
}
if s.FSaltKey == nil {
s.FSaltKey = []byte(cSaltKey)
if p.FSaltKey == nil {
p.FSaltKey = []byte(cSaltKey)
}
if s.FCipherKey == nil {
s.FCipherKey = []byte(cCipherKey)
if p.FCipherKey == nil {
p.FCipherKey = []byte(cCipherKey)
}
return s
return p
}
func (s *sSettings) GetPath() string {
return s.FPath
func (p *sSettings) GetPath() string {
return p.FPath
}
func (s *sSettings) GetSaltKey() []byte {
return s.FSaltKey
func (p *sSettings) GetSaltKey() []byte {
return p.FSaltKey
}
func (s *sSettings) GetHashing() bool {
return s.FHashing
func (p *sSettings) GetHashing() bool {
return p.FHashing
}
func (s *sSettings) GetCipherKey() []byte {
return s.FCipherKey
func (p *sSettings) GetCipherKey() []byte {
return p.FCipherKey
}

View File

@ -18,35 +18,35 @@ type sMemoryStorage struct {
fMapping map[string][]byte
}
func NewMemoryStorage(max uint64) IKeyValueStorage {
func NewMemoryStorage(pMaximum uint64) IKeyValueStorage {
return &sMemoryStorage{
fMaximum: max,
fKeyQueue: make([]string, 0, max),
fMapping: make(map[string][]byte, max),
fMaximum: pMaximum,
fKeyQueue: make([]string, 0, pMaximum),
fMapping: make(map[string][]byte, pMaximum),
}
}
func (store *sMemoryStorage) Set(key, value []byte) error {
store.fMutex.Lock()
defer store.fMutex.Unlock()
func (p *sMemoryStorage) Set(pKey, pValue []byte) error {
p.fMutex.Lock()
defer p.fMutex.Unlock()
if uint64(len(store.fMapping)) >= store.fMaximum {
delete(store.fMapping, store.fKeyQueue[0])
store.fKeyQueue = store.fKeyQueue[1:]
if uint64(len(p.fMapping)) >= p.fMaximum {
delete(p.fMapping, p.fKeyQueue[0])
p.fKeyQueue = p.fKeyQueue[1:]
}
newKey := encoding.HexEncode(key)
newKey := encoding.HexEncode(pKey)
store.fKeyQueue = append(store.fKeyQueue, newKey)
store.fMapping[newKey] = value
p.fKeyQueue = append(p.fKeyQueue, newKey)
p.fMapping[newKey] = pValue
return nil
}
func (store *sMemoryStorage) Get(key []byte) ([]byte, error) {
store.fMutex.Lock()
defer store.fMutex.Unlock()
func (p *sMemoryStorage) Get(pKey []byte) ([]byte, error) {
p.fMutex.Lock()
defer p.fMutex.Unlock()
value, ok := store.fMapping[encoding.HexEncode(key)]
value, ok := p.fMapping[encoding.HexEncode(pKey)]
if !ok {
return nil, fmt.Errorf("undefined value by key")
}
@ -54,15 +54,15 @@ func (store *sMemoryStorage) Get(key []byte) ([]byte, error) {
return value, nil
}
func (store *sMemoryStorage) Del(key []byte) error {
store.fMutex.Lock()
defer store.fMutex.Unlock()
func (p *sMemoryStorage) Del(pKey []byte) error {
p.fMutex.Lock()
defer p.fMutex.Unlock()
_, ok := store.fMapping[encoding.HexEncode(key)]
_, ok := p.fMapping[encoding.HexEncode(pKey)]
if !ok {
return fmt.Errorf("undefined value by key")
}
delete(store.fMapping, encoding.HexEncode(key))
delete(p.fMapping, encoding.HexEncode(pKey))
return nil
}

View File

@ -1,9 +1,9 @@
package types
// returns last error from slice
func CloseAll(cs []ICloser) error {
func CloseAll(pClosers []ICloser) error {
var lastErr error
for _, c := range cs {
for _, c := range pClosers {
if err := c.Close(); err != nil {
lastErr = err
}

View File

@ -1,9 +1,9 @@
package types
// returns last error from slice
func StopAll(cs []ICommand) error {
func StopAll(pCommands []ICommand) error {
var lastErr error
for _, c := range cs {
for _, c := range pCommands {
if err := c.Stop(); err != nil {
lastErr = err
}

View File

@ -17,17 +17,17 @@ func NewWrapper() IWrapper {
return &sWrapper{fValue: new(interface{})}
}
func (w *sWrapper) Get() interface{} {
w.fMutex.Lock()
defer w.fMutex.Unlock()
func (p *sWrapper) Get() interface{} {
p.fMutex.Lock()
defer p.fMutex.Unlock()
return (*w.fValue)
return (*p.fValue)
}
func (w *sWrapper) Set(v interface{}) IWrapper {
w.fMutex.Lock()
defer w.fMutex.Unlock()
func (p *sWrapper) Set(pValue interface{}) IWrapper {
p.fMutex.Lock()
defer p.fMutex.Unlock()
(*w.fValue) = v
return w
(*p.fValue) = pValue
return p
}

File diff suppressed because it is too large Load Diff

View File

@ -1,60 +1,60 @@
ok github.com/number571/go-peer/cmd/hidden_lake/adapters/common 0.025s coverage: [no statements]
ok github.com/number571/go-peer/cmd/hidden_lake/adapters/common/recv 0.038s coverage: 3.7% of statements
ok github.com/number571/go-peer/cmd/hidden_lake/adapters/common/send 0.030s coverage: 0.0% of statements
ok github.com/number571/go-peer/cmd/hidden_lake/adapters/common/service 0.046s coverage: 4.3% of statements
ok github.com/number571/go-peer/cmd/hidden_lake/messenger/cmd/hlm 0.024s coverage: 0.0% of statements
ok github.com/number571/go-peer/cmd/hidden_lake/messenger/internal/app 0.059s coverage: 0.0% of statements
ok github.com/number571/go-peer/cmd/hidden_lake/messenger/internal/app/state 0.048s coverage: 0.0% of statements
ok github.com/number571/go-peer/cmd/hidden_lake/messenger/internal/chat_queue 0.051s coverage: 0.0% of statements
ok github.com/number571/go-peer/cmd/hidden_lake/messenger/internal/config 0.044s coverage: 67.5% of statements
ok github.com/number571/go-peer/cmd/hidden_lake/messenger/internal/database 0.041s coverage: 0.0% of statements
ok github.com/number571/go-peer/cmd/hidden_lake/messenger/internal/handler 0.040s coverage: 0.0% of statements
ok github.com/number571/go-peer/cmd/hidden_lake/messenger/internal/settings 0.052s coverage: [no statements]
ok github.com/number571/go-peer/cmd/hidden_lake/messenger/web 0.042s coverage: 0.0% of statements
ok github.com/number571/go-peer/cmd/hidden_lake/service/cmd/hls 0.051s coverage: 0.0% of statements
ok github.com/number571/go-peer/cmd/hidden_lake/adapters/common 0.037s coverage: [no statements]
ok github.com/number571/go-peer/cmd/hidden_lake/adapters/common/recv 0.056s coverage: 3.7% of statements
ok github.com/number571/go-peer/cmd/hidden_lake/adapters/common/send 0.035s coverage: 0.0% of statements
ok github.com/number571/go-peer/cmd/hidden_lake/adapters/common/service 0.056s coverage: 4.3% of statements
ok github.com/number571/go-peer/cmd/hidden_lake/messenger/cmd/hlm 0.026s coverage: 0.0% of statements
ok github.com/number571/go-peer/cmd/hidden_lake/messenger/internal/app 0.081s coverage: 0.0% of statements
ok github.com/number571/go-peer/cmd/hidden_lake/messenger/internal/app/state 0.076s coverage: 0.0% of statements
ok github.com/number571/go-peer/cmd/hidden_lake/messenger/internal/chat_queue 0.070s coverage: 0.0% of statements
ok github.com/number571/go-peer/cmd/hidden_lake/messenger/internal/config 0.074s coverage: 67.5% of statements
ok github.com/number571/go-peer/cmd/hidden_lake/messenger/internal/database 0.105s coverage: 0.0% of statements
ok github.com/number571/go-peer/cmd/hidden_lake/messenger/internal/handler 0.082s coverage: 0.0% of statements
ok github.com/number571/go-peer/cmd/hidden_lake/messenger/internal/settings 0.105s coverage: [no statements]
ok github.com/number571/go-peer/cmd/hidden_lake/messenger/web 0.066s coverage: 0.0% of statements
ok github.com/number571/go-peer/cmd/hidden_lake/service/cmd/hls 0.071s coverage: 0.0% of statements
? github.com/number571/go-peer/pkg/wrapper [no test files]
ok github.com/number571/go-peer/cmd/hidden_lake/service/internal/app 6.157s coverage: 75.4% of statements
ok github.com/number571/go-peer/cmd/hidden_lake/service/internal/config 0.034s coverage: 55.6% of statements
ok github.com/number571/go-peer/cmd/hidden_lake/service/internal/handler 6.891s coverage: 65.1% of statements
ok github.com/number571/go-peer/cmd/hidden_lake/service/pkg/client 0.032s coverage: 0.0% of statements
ok github.com/number571/go-peer/cmd/hidden_lake/service/pkg/request 0.031s coverage: 100.0% of statements
ok github.com/number571/go-peer/cmd/hidden_lake/service/pkg/settings 0.034s coverage: 0.0% of statements
ok github.com/number571/go-peer/cmd/hidden_lake/traffic/cmd/hlt 0.036s coverage: 0.0% of statements
ok github.com/number571/go-peer/cmd/hidden_lake/traffic/internal/app 6.119s coverage: 56.7% of statements
ok github.com/number571/go-peer/cmd/hidden_lake/traffic/internal/config 0.031s coverage: 75.7% of statements
ok github.com/number571/go-peer/cmd/hidden_lake/traffic/internal/database 0.606s coverage: 68.7% of statements
ok github.com/number571/go-peer/cmd/hidden_lake/traffic/internal/handler 1.270s coverage: 62.8% of statements
ok github.com/number571/go-peer/cmd/hidden_lake/traffic/pkg/client 0.032s coverage: 0.0% of statements
ok github.com/number571/go-peer/cmd/hidden_lake/traffic/pkg/settings 0.031s coverage: [no statements]
ok github.com/number571/go-peer/cmd/union_blockchain 0.034s coverage: 0.0% of statements
ok github.com/number571/go-peer/cmd/union_blockchain/kernel 0.032s coverage: [no statements]
ok github.com/number571/go-peer/cmd/union_blockchain/kernel/block 0.288s coverage: 71.4% of statements
ok github.com/number571/go-peer/cmd/union_blockchain/kernel/chain 6.948s coverage: 79.7% of statements
ok github.com/number571/go-peer/cmd/union_blockchain/kernel/mempool 0.315s coverage: 73.9% of statements
ok github.com/number571/go-peer/cmd/union_blockchain/kernel/transaction 0.045s coverage: 68.6% of statements
ok github.com/number571/go-peer/internal/api 0.037s coverage: 0.0% of statements
ok github.com/number571/go-peer/internal/logger 0.035s coverage: 88.9% of statements
ok github.com/number571/go-peer/internal/pprof 0.040s coverage: 0.0% of statements
ok github.com/number571/go-peer/pkg/client 0.651s coverage: 73.6% of statements
ok github.com/number571/go-peer/pkg/client/message 0.045s coverage: 78.8% of statements
ok github.com/number571/go-peer/pkg/client/queue 6.661s coverage: 90.0% of statements
ok github.com/number571/go-peer/pkg/crypto 0.030s coverage: [no statements]
ok github.com/number571/go-peer/pkg/crypto/asymmetric 0.416s coverage: 84.8% of statements
ok github.com/number571/go-peer/pkg/crypto/entropy 0.024s coverage: 100.0% of statements
ok github.com/number571/go-peer/pkg/crypto/hashing 0.028s coverage: 85.7% of statements
ok github.com/number571/go-peer/pkg/crypto/puzzle 0.026s coverage: 94.7% of statements
ok github.com/number571/go-peer/pkg/crypto/random 0.027s coverage: 81.8% of statements
ok github.com/number571/go-peer/pkg/crypto/symmetric 0.025s coverage: 72.0% of statements
ok github.com/number571/go-peer/cmd/hidden_lake/service/internal/app 6.211s coverage: 75.4% of statements
ok github.com/number571/go-peer/cmd/hidden_lake/service/internal/config 0.045s coverage: 55.6% of statements
ok github.com/number571/go-peer/cmd/hidden_lake/service/internal/handler 6.589s coverage: 65.1% of statements
ok github.com/number571/go-peer/cmd/hidden_lake/service/pkg/client 0.036s coverage: 0.0% of statements
ok github.com/number571/go-peer/cmd/hidden_lake/service/pkg/request 0.043s coverage: 100.0% of statements
ok github.com/number571/go-peer/cmd/hidden_lake/service/pkg/settings 0.038s coverage: 0.0% of statements
ok github.com/number571/go-peer/cmd/hidden_lake/traffic/cmd/hlt 0.038s coverage: 0.0% of statements
ok github.com/number571/go-peer/cmd/hidden_lake/traffic/internal/app 6.116s coverage: 56.7% of statements
ok github.com/number571/go-peer/cmd/hidden_lake/traffic/internal/config 0.065s coverage: 75.7% of statements
ok github.com/number571/go-peer/cmd/hidden_lake/traffic/internal/database 0.617s coverage: 68.7% of statements
ok github.com/number571/go-peer/cmd/hidden_lake/traffic/internal/handler 1.376s coverage: 62.8% of statements
ok github.com/number571/go-peer/cmd/hidden_lake/traffic/pkg/client 0.055s coverage: 0.0% of statements
ok github.com/number571/go-peer/cmd/hidden_lake/traffic/pkg/settings 0.067s coverage: [no statements]
ok github.com/number571/go-peer/cmd/union_blockchain 0.063s coverage: 0.0% of statements
ok github.com/number571/go-peer/cmd/union_blockchain/kernel 0.030s coverage: [no statements]
ok github.com/number571/go-peer/cmd/union_blockchain/kernel/block 0.287s coverage: 71.4% of statements
ok github.com/number571/go-peer/cmd/union_blockchain/kernel/chain 7.730s coverage: 79.7% of statements
ok github.com/number571/go-peer/cmd/union_blockchain/kernel/mempool 0.375s coverage: 73.9% of statements
ok github.com/number571/go-peer/cmd/union_blockchain/kernel/transaction 0.066s coverage: 68.6% of statements
ok github.com/number571/go-peer/internal/api 0.056s coverage: 0.0% of statements
ok github.com/number571/go-peer/internal/logger 0.061s coverage: 88.9% of statements
ok github.com/number571/go-peer/internal/pprof 0.028s coverage: 0.0% of statements
ok github.com/number571/go-peer/pkg/client 0.783s coverage: 73.6% of statements
ok github.com/number571/go-peer/pkg/client/message 0.052s coverage: 78.8% of statements
ok github.com/number571/go-peer/pkg/client/queue 6.768s coverage: 90.0% of statements
ok github.com/number571/go-peer/pkg/crypto 0.040s coverage: [no statements]
ok github.com/number571/go-peer/pkg/crypto/asymmetric 0.319s coverage: 84.9% of statements
ok github.com/number571/go-peer/pkg/crypto/entropy 0.044s coverage: 100.0% of statements
ok github.com/number571/go-peer/pkg/crypto/hashing 0.025s coverage: 85.7% of statements
ok github.com/number571/go-peer/pkg/crypto/puzzle 0.039s coverage: 94.7% of statements
ok github.com/number571/go-peer/pkg/crypto/random 0.030s coverage: 81.8% of statements
ok github.com/number571/go-peer/pkg/crypto/symmetric 0.027s coverage: 72.0% of statements
ok github.com/number571/go-peer/pkg/encoding 0.027s coverage: 83.3% of statements
ok github.com/number571/go-peer/pkg/filesystem 0.028s coverage: 100.0% of statements
ok github.com/number571/go-peer/pkg/logger 0.024s coverage: 84.6% of statements
ok github.com/number571/go-peer/pkg/network 5.833s coverage: 91.5% of statements
ok github.com/number571/go-peer/pkg/network/anonymity 11.830s coverage: 80.5% of statements
ok github.com/number571/go-peer/pkg/network/anonymity/logger 0.031s coverage: 92.3% of statements
ok github.com/number571/go-peer/pkg/network/conn 0.047s coverage: 84.5% of statements
ok github.com/number571/go-peer/pkg/network/conn_keeper 1.051s coverage: 100.0% of statements
ok github.com/number571/go-peer/pkg/network/message 0.037s coverage: 71.4% of statements
ok github.com/number571/go-peer/pkg/payload 0.038s coverage: 90.0% of statements
ok github.com/number571/go-peer/pkg/storage 0.072s coverage: 84.8% of statements
ok github.com/number571/go-peer/pkg/storage/database 0.254s coverage: 94.5% of statements
ok github.com/number571/go-peer/pkg/types 0.037s coverage: 100.0% of statements
ok github.com/number571/go-peer/pkg/filesystem 0.065s coverage: 100.0% of statements
ok github.com/number571/go-peer/pkg/logger 0.031s coverage: 84.6% of statements
ok github.com/number571/go-peer/pkg/network 6.805s coverage: 91.5% of statements
ok github.com/number571/go-peer/pkg/network/anonymity 12.855s coverage: 80.5% of statements
ok github.com/number571/go-peer/pkg/network/anonymity/logger 0.053s coverage: 92.3% of statements
ok github.com/number571/go-peer/pkg/network/conn 0.067s coverage: 84.5% of statements
ok github.com/number571/go-peer/pkg/network/conn_keeper 1.072s coverage: 100.0% of statements
ok github.com/number571/go-peer/pkg/network/message 0.060s coverage: 71.4% of statements
ok github.com/number571/go-peer/pkg/payload 0.039s coverage: 90.0% of statements
ok github.com/number571/go-peer/pkg/storage 0.134s coverage: 84.8% of statements
ok github.com/number571/go-peer/pkg/storage/database 0.249s coverage: 94.5% of statements
ok github.com/number571/go-peer/pkg/types 0.050s coverage: 100.0% of statements