This commit is contained in:
number571 2024-02-18 04:04:38 +07:00
parent 1d2354c43f
commit 4f8518aaa0
33 changed files with 4020 additions and 3985 deletions

View File

@ -6,6 +6,15 @@
*??? ??, ????*
### IMPROVEMENTS
- Update `pkg/network/anonymity/queue`: append random duration
### CHANGES
- Update `cmd/hidden_lake/applications`: delete FaviconPage, change favicon.ico -> favicon.gif
- Update `pkg/network/message`: static salt -> dynamic salt
<!-- ... -->
## v1.6.3

View File

@ -870,8 +870,8 @@ Previously, some applications (such as HL, HLS, HES) were developed separately f
The difference between the old version of Hidden Lake and the new one is in the following details:
1. The new version is based on a model of theoretically provable anonymity (QB networks), while the old version was based on onion routing
2. The old version was a monolith, incorporating both transport logic, anonymizing, and applied. The new version is already based on the micro service architecture
3. The new version is located inside the go-peer framework (in the cmd directory), while the old one used go-peer as a library.
4. The main anonymizing and transport functions in the new version of Hidden Lake (at the level of the go-peer framework) have been covered by tests and verified for security. In the old version, there were no tests at all.
3. The new version is located inside the go-peer framework (in the cmd directory), while the old one used go-peer as a library
4. The main anonymizing and transport functions in the new version of Hidden Lake (at the level of the go-peer framework) have been covered by tests and verified for security. In the old version, there were no tests at all
**[⬆ back to top](#installation)**

View File

@ -9,6 +9,7 @@
7. Append Batch's to database
8. Custom Unmarshal with fields
9. golint: "goerr113,wrapcheck,cyclop,funlen,gocyclo,gocognit"
10. Dynamic cryptographic salt (cAuthSalt, cCipherSalt) in network/conn
### Tests

View File

@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="96" height="20" role="img" aria-label="coverage: 54%"><title>coverage: 54%</title><linearGradient id="s" x2="0" y2="100%"><stop offset="0" stop-color="#bbb" stop-opacity=".1"/><stop offset="1" stop-opacity=".1"/></linearGradient><clipPath id="r"><rect width="96" height="20" rx="3" fill="#fff"/></clipPath><g clip-path="url(#r)"><rect width="61" height="20" fill="#555"/><rect x="61" width="35" height="20" fill="crimson"/><rect width="96" height="20" fill="url(#s)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="315" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="510">coverage</text><text x="315" y="140" transform="scale(.1)" fill="#fff" textLength="510">coverage</text><text aria-hidden="true" x="775" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="250">54%</text><text x="775" y="140" transform="scale(.1)" fill="#fff" textLength="250">54%</text></g></svg>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="96" height="20" role="img" aria-label="coverage: 55%"><title>coverage: 55%</title><linearGradient id="s" x2="0" y2="100%"><stop offset="0" stop-color="#bbb" stop-opacity=".1"/><stop offset="1" stop-opacity=".1"/></linearGradient><clipPath id="r"><rect width="96" height="20" rx="3" fill="#fff"/></clipPath><g clip-path="url(#r)"><rect width="61" height="20" fill="#555"/><rect x="61" width="35" height="20" fill="crimson"/><rect width="96" height="20" fill="url(#s)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="315" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="510">coverage</text><text x="315" y="140" transform="scale(.1)" fill="#fff" textLength="510">coverage</text><text aria-hidden="true" x="775" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="250">55%</text><text x="775" y="140" transform="scale(.1)" fill="#fff" textLength="250">55%</text></g></svg>

Before

Width:  |  Height:  |  Size: 1.1 KiB

After

Width:  |  Height:  |  Size: 1.1 KiB

File diff suppressed because it is too large Load Diff

View File

@ -1,25 +0,0 @@
package handler
import (
"net/http"
http_logger "github.com/number571/go-peer/internal/logger/http"
"github.com/number571/go-peer/pkg/logger"
"github.com/number571/go-peer/cmd/hidden_lake/applications/filesharer/internal/config"
hlf_settings "github.com/number571/go-peer/cmd/hidden_lake/applications/filesharer/pkg/settings"
)
func FaviconPage(pLogger logger.ILogger, pCfg config.IConfig) http.HandlerFunc {
return func(pW http.ResponseWriter, pR *http.Request) {
logBuilder := http_logger.NewLogBuilder(hlf_settings.CServiceName, pR)
if pR.URL.Path != "/favicon.ico" {
NotFoundPage(pLogger, pCfg)(pW, pR)
return
}
pLogger.PushInfo(logBuilder.WithMessage(http_logger.CLogSuccess))
http.Redirect(pW, pR, "/static/img/favicon.ico", http.StatusFound)
}
}

View File

@ -41,7 +41,6 @@ func (p *sApp) initInterfaceServiceHTTP() {
cfgWrapper := config.NewWrapper(p.fConfig)
mux.HandleFunc(hlm_settings.CHandleIndexPath, handler.IndexPage(p.fHTTPLogger, p.fConfig)) // GET, POST
mux.HandleFunc(hlm_settings.CHandleFaviconPath, handler.FaviconPage(p.fHTTPLogger, p.fConfig)) // GET
mux.HandleFunc(hlm_settings.CHandleAboutPath, handler.AboutPage(p.fHTTPLogger, p.fConfig)) // GET
mux.HandleFunc(hlm_settings.CHandleSettingsPath, handler.SettingsPage(p.fHTTPLogger, cfgWrapper)) // GET, PATCH, PUT, POST, DELETE
mux.HandleFunc(hlm_settings.CHandleFriendsPath, handler.FriendsPage(p.fHTTPLogger, p.fConfig)) // GET, POST, DELETE

Binary file not shown.

After

Width:  |  Height:  |  Size: 549 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

View File

@ -5,9 +5,10 @@
<title>{{template "title" .}}</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="/static/img/favicon.gif">
<link href="/static/css/bootstrap.css" type="text/css" rel="stylesheet" />
<script src="/static/js/jquery.js" type="text/javascript" defer></script>
<script src="/static/js/bootstrap.js" type="text/javascript" defer></script>
<link href="/static/css/bootstrap.css" type="text/css" rel="stylesheet" />
</head>
<body class="bg-dark text-white">

View File

@ -1,25 +0,0 @@
package handler
import (
"net/http"
http_logger "github.com/number571/go-peer/internal/logger/http"
"github.com/number571/go-peer/pkg/logger"
"github.com/number571/go-peer/cmd/hidden_lake/applications/messenger/internal/config"
hlm_settings "github.com/number571/go-peer/cmd/hidden_lake/applications/messenger/pkg/settings"
)
func FaviconPage(pLogger logger.ILogger, pCfg config.IConfig) http.HandlerFunc {
return func(pW http.ResponseWriter, pR *http.Request) {
logBuilder := http_logger.NewLogBuilder(hlm_settings.CServiceName, pR)
if pR.URL.Path != "/favicon.ico" {
NotFoundPage(pLogger, pCfg)(pW, pR)
return
}
pLogger.PushInfo(logBuilder.WithMessage(http_logger.CLogSuccess))
http.Redirect(pW, pR, "/static/img/favicon.ico", http.StatusFound)
}
}

View File

@ -38,7 +38,6 @@ func (p *sApp) initInterfaceServiceHTTP(pMsgBroker msgbroker.IMessageBroker) {
cfgWrapper := config.NewWrapper(p.fConfig)
mux.HandleFunc(hlm_settings.CHandleIndexPath, handler.IndexPage(p.fHTTPLogger, p.fConfig)) // GET, POST
mux.HandleFunc(hlm_settings.CHandleFaviconPath, handler.FaviconPage(p.fHTTPLogger, p.fConfig)) // GET
mux.HandleFunc(hlm_settings.CHandleAboutPath, handler.AboutPage(p.fHTTPLogger, p.fConfig)) // GET
mux.HandleFunc(hlm_settings.CHandleSettingsPath, handler.SettingsPage(p.fHTTPLogger, cfgWrapper)) // GET, PATCH, PUT, POST, DELETE
mux.HandleFunc(hlm_settings.CHandleFriendsPath, handler.FriendsPage(p.fHTTPLogger, p.fConfig)) // GET, POST, DELETE

Binary file not shown.

After

Width:  |  Height:  |  Size: 549 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

View File

@ -5,9 +5,10 @@
<title>{{template "title" .}}</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="/static/img/favicon.gif">
<link href="/static/css/bootstrap.css" type="text/css" rel="stylesheet" />
<script src="/static/js/jquery.js" type="text/javascript" defer></script>
<script src="/static/js/bootstrap.js" type="text/javascript" defer></script>
<link href="/static/css/bootstrap.css" type="text/css" rel="stylesheet" />
</head>
<body class="bg-dark text-white">

View File

@ -21,6 +21,7 @@ type SConfigSettings struct {
fMutex sync.Mutex
FMessageSizeBytes uint64 `json:"message_size_bytes" yaml:"message_size_bytes"`
FQueuePeriodMS uint64 `json:"queue_period_ms" yaml:"queue_period_ms"`
FQueueRandPeriodMS uint64 `json:"queue_rand_period_ms" yaml:"queue_rand_period_ms,omitempty"`
FKeySizeBits uint64 `json:"key_size_bits" yaml:"key_size_bits"`
FWorkSizeBits uint64 `json:"work_size_bits,omitempty" yaml:"work_size_bits,omitempty"`
FLimitVoidSizeBytes uint64 `json:"limit_void_size_bytes,omitempty" yaml:"limit_void_size_bytes,omitempty"`
@ -109,6 +110,10 @@ func (p *SConfigSettings) GetQueuePeriodMS() uint64 {
return p.FQueuePeriodMS
}
func (p *SConfigSettings) GetQueueRandPeriodMS() uint64 {
return p.FQueueRandPeriodMS
}
func (p *SConfigSettings) GetLimitVoidSizeBytes() uint64 {
return p.FLimitVoidSizeBytes
}

View File

@ -16,21 +16,22 @@ const (
)
const (
tcLogging = true
tcNetwork = "test_network_key"
tcDownloader = "test_downloader"
tcUploader = "test_uploader"
tcAddressTCP = "test_address_tcp"
tcAddressHTTP = "test_address_http"
tcAddressPPROF = "test_address_pprof"
tcPubKeyAlias1 = "test_alias1"
tcPubKeyAlias2 = "test_alias2"
tcServiceName1 = "test_service1"
tcServiceName2 = "test_service2"
tcMessageSize = (1 << 20)
tcWorkSize = 22
tcQueuePeriod = 1000
tcLimitVoidSize = (1 << 20)
tcLogging = true
tcNetwork = "test_network_key"
tcDownloader = "test_downloader"
tcUploader = "test_uploader"
tcAddressTCP = "test_address_tcp"
tcAddressHTTP = "test_address_http"
tcAddressPPROF = "test_address_pprof"
tcPubKeyAlias1 = "test_alias1"
tcPubKeyAlias2 = "test_alias2"
tcServiceName1 = "test_service1"
tcServiceName2 = "test_service2"
tcMessageSize = (1 << 20)
tcWorkSize = 22
tcQueuePeriod = 1000
tcQueueRandPeriod = 2000
tcLimitVoidSize = (1 << 20)
)
var (
@ -54,6 +55,7 @@ const (
work_size_bits: %d
key_size_bits: %d
queue_period_ms: %d
queue_rand_period_ms: %d
limit_void_size_bytes: %d
network_key: %s
f2f_disabled: true
@ -85,6 +87,7 @@ func testNewConfigString() string {
tcWorkSize,
testutils.TcKeySize,
tcQueuePeriod,
tcQueueRandPeriod,
tcLimitVoidSize,
tcNetwork,
tcAddressTCP,
@ -242,6 +245,11 @@ func TestComplexConfig(t *testing.T) {
return
}
if cfg.GetSettings().GetQueueRandPeriodMS() != tcQueueRandPeriod {
t.Error("settings queue rand period is invalid")
return
}
if cfg.GetSettings().GetLimitVoidSizeBytes() != tcLimitVoidSize {
t.Error("settings limit void size is invalid")
return

View File

@ -25,6 +25,7 @@ func InitConfig(cfgPath string, initCfg *SConfig) (IConfig, error) {
FWorkSizeBits: hls_settings.CDefaultWorkSize,
FKeySizeBits: hls_settings.CDefaultKeySize,
FQueuePeriodMS: hls_settings.CDefaultQueuePeriod,
FQueueRandPeriodMS: hls_settings.CDefaultQueueRandPeriod,
FLimitVoidSizeBytes: hls_settings.CDefaultLimitVoidSize,
FNetworkKey: hls_settings.CDefaultNetworkKey,
FF2FDisabled: hls_settings.CDefaultF2FDisabled,

View File

@ -23,6 +23,8 @@ type IConfigSettings interface {
net_message.ISettings
GetQueuePeriodMS() uint64
GetQueueRandPeriodMS() uint64
GetLimitVoidSizeBytes() uint64
GetF2FDisabled() bool
}

View File

@ -33,6 +33,7 @@ func HandleConfigSettingsAPI(pWrapper config.IWrapper, pLogger logger.ILogger, p
FMessageSizeBytes: sett.GetMessageSizeBytes(),
FWorkSizeBits: sett.GetWorkSizeBits(),
FQueuePeriodMS: sett.GetQueuePeriodMS(),
FQueueRandPeriodMS: sett.GetQueueRandPeriodMS(),
FKeySizeBits: sett.GetKeySizeBits(),
FLimitVoidSizeBytes: sett.GetLimitVoidSizeBytes(),
FNetworkKey: sett.GetNetworkKey(),

View File

@ -25,9 +25,17 @@ func initNode(
pLogger logger.ILogger,
pParallel uint64,
) anonymity.INode {
cfg := pCfgW.GetConfig()
cfgSettings := cfg.GetSettings()
queueDuration := time.Duration(cfgSettings.GetQueuePeriodMS()) * time.Millisecond
var (
cfg = pCfgW.GetConfig()
cfgSettings = cfg.GetSettings()
)
var (
queueDuration = time.Duration(cfgSettings.GetQueuePeriodMS()) * time.Millisecond
queueRandDuration = time.Duration(cfgSettings.GetQueueRandPeriodMS()) * time.Millisecond
queueMaxDuration = queueDuration + queueRandDuration
)
return anonymity.NewNode(
anonymity.NewSettings(&anonymity.SSettings{
FServiceName: pkg_settings.CServiceName,
@ -44,16 +52,16 @@ func initNode(
network.NewSettings(&network.SSettings{
FAddress: cfg.GetAddress().GetTCP(),
FMaxConnects: pkg_settings.CNetworkMaxConns,
FReadTimeout: queueDuration,
FWriteTimeout: queueDuration,
FReadTimeout: queueMaxDuration,
FWriteTimeout: queueMaxDuration,
FConnSettings: conn.NewSettings(&conn.SSettings{
FNetworkKey: cfgSettings.GetNetworkKey(),
FWorkSizeBits: cfgSettings.GetWorkSizeBits(),
FMessageSizeBytes: cfgSettings.GetMessageSizeBytes(),
FLimitVoidSize: cfgSettings.GetLimitVoidSizeBytes(),
FWaitReadDeadline: pkg_settings.CConnWaitReadDeadline,
FReadDeadline: queueDuration,
FWriteDeadline: queueDuration,
FReadDeadline: queueMaxDuration,
FWriteDeadline: queueMaxDuration,
}),
}),
lru.NewLRUCache(
@ -68,6 +76,7 @@ func initNode(
FVoidCapacity: pkg_settings.CQueuePoolCapacity,
FParallel: pParallel,
FDuration: queueDuration,
FRandDuration: queueRandDuration,
}),
client.NewClient(
message.NewSettings(&message.SSettings{

View File

@ -39,13 +39,14 @@ const (
)
const (
CDefaultMessageSize = (8 << 10) // 8KiB
CDefaultWorkSize = 22 // bits
CDefaultKeySize = 4096 // bits
CDefaultQueuePeriod = 5000 // 5 seconds
CDefaultLimitVoidSize = (4 << 10) // 4KiB
CDefaultF2FDisabled = false // friend-to-friend
CDefaultNetworkKey = "default"
CDefaultMessageSize = (8 << 10) // 8KiB
CDefaultWorkSize = 22 // bits
CDefaultKeySize = 4096 // bits
CDefaultQueuePeriod = 5000 // 5 seconds
CDefaultQueueRandPeriod = 0 // 0 seconds
CDefaultLimitVoidSize = (4 << 10) // 4KiB
CDefaultF2FDisabled = false // friend-to-friend
CDefaultNetworkKey = "default"
)
const (

View File

@ -3,11 +3,12 @@ settings:
work_size_bits: 22
key_size_bits: 4096
queue_period_ms: 5000
queue_rand_period_ms: 5000
limit_void_size_bytes: 4096
logging:
- info
- warn
- erro
# logging:
# - info
# - warn
# - erro
services:
hidden-echo-service:
host: localhost:8080

View File

@ -1,9 +1,10 @@
settings:
message_size_bytes: 8192
work_size_bits: 22
queue_period_ms: 5000
limit_void_size_bytes: 4096
key_size_bits: 4096
queue_period_ms: 5000
queue_rand_period_ms: 5000
limit_void_size_bytes: 4096
logging:
- info
- warn

View File

@ -9,6 +9,7 @@ import (
"github.com/number571/go-peer/pkg/client"
"github.com/number571/go-peer/pkg/client/message"
"github.com/number571/go-peer/pkg/crypto/asymmetric"
"github.com/number571/go-peer/pkg/crypto/random"
net_message "github.com/number571/go-peer/pkg/network/message"
"github.com/number571/go-peer/pkg/payload"
"github.com/number571/go-peer/pkg/state"
@ -160,10 +161,14 @@ func (p *sMessageQueue) EnqueueMessage(pMsg message.IMessage) error {
}
func (p *sMessageQueue) DequeueMessage(pCtx context.Context) net_message.IMessage {
randDuration := time.Duration(
random.NewStdPRNG().GetUint64() % uint64(p.fSettings.GetRandDuration()),
)
select {
case <-pCtx.Done():
return nil
case <-time.After(p.fSettings.GetDuration()):
case <-time.After(p.fSettings.GetDuration() + randDuration):
select {
case x := <-p.fMainPool.fQueue:
// the main queue is checked first

View File

@ -147,6 +147,7 @@ func TestQueue(t *testing.T) {
FVoidCapacity: testutils.TCQueueCapacity,
FParallel: 1,
FDuration: 100 * time.Millisecond,
FRandDuration: 100 * time.Millisecond,
}),
client.NewClient(
message.NewSettings(&message.SSettings{
@ -179,7 +180,7 @@ func testQueue(queue IMessageQueue) error {
ctx, cancel := context.WithCancel(context.Background())
defer func() {
cancel()
time.Sleep(100 * time.Millisecond)
time.Sleep(200 * time.Millisecond)
}()
go func() {
@ -202,7 +203,7 @@ func testQueue(queue IMessageQueue) error {
}
// wait minimum one generated message
time.Sleep(200 * time.Millisecond)
time.Sleep(300 * time.Millisecond)
// clear old messages
queue.WithNetworkSettings(

View File

@ -14,6 +14,7 @@ type sSettings struct {
FVoidCapacity uint64
FParallel uint64
FDuration time.Duration
FRandDuration time.Duration
}
func NewSettings(pSett *SSettings) ISettings {
@ -22,6 +23,7 @@ func NewSettings(pSett *SSettings) ISettings {
FVoidCapacity: pSett.FVoidCapacity,
FParallel: pSett.FParallel,
FDuration: pSett.FDuration,
FRandDuration: pSett.FRandDuration,
}).mustNotNull()
}
@ -38,6 +40,11 @@ func (p *sSettings) mustNotNull() ISettings {
if p.FDuration == 0 {
panic(`p.FDuration == 0`)
}
if p.FRandDuration == 0 {
// randDuration=0 == randDuration=1
// randDuration is a mod of calculation
p.FRandDuration = 1
}
return p
}
@ -56,3 +63,7 @@ func (p *sSettings) GetVoidCapacity() uint64 {
func (p *sSettings) GetDuration() time.Duration {
return p.FDuration
}
func (p *sSettings) GetRandDuration() time.Duration {
return p.FRandDuration
}

View File

@ -26,4 +26,5 @@ type ISettings interface {
GetVoidCapacity() uint64
GetParallel() uint64
GetDuration() time.Duration
GetRandDuration() time.Duration
}

View File

@ -17,8 +17,8 @@ import (
)
const (
// IV + Hash + PayloadHead + Proof
cPayloadOverHeadSize = symmetric.CAESBlockSize + hashing.CSHA256Size + 2*encoding.CSizeUint64
// IV + Salt + Hash + PayloadHead + Proof
cPayloadOverHeadSize = symmetric.CAESBlockSize + message.CSaltSize + hashing.CSHA256Size + 2*encoding.CSizeUint64
// IV + Uint64(encMsgSize) + Uint64(voidSize) + HMAC(encMsgSize || voidSize) + HMAC(msgBytes || voidBytes)
cEncryptRecvHeadSize = symmetric.CAESBlockSize + 2*encoding.CSizeUint64 + 2*hashing.CSHA256Size
@ -28,7 +28,7 @@ const (
// first digits of PI
cAuthSalt = "1415926535_8979323846_2643383279_5028841971_6939937510"
// seconds digits of PI
// second digits of PI
cCipherSalt = "5820974944_5923078164_0628620899_8628034825_3421170679"
)

View File

@ -6,13 +6,13 @@ import (
"github.com/number571/go-peer/pkg/crypto/hashing"
"github.com/number571/go-peer/pkg/crypto/keybuilder"
"github.com/number571/go-peer/pkg/crypto/puzzle"
"github.com/number571/go-peer/pkg/crypto/random"
"github.com/number571/go-peer/pkg/encoding"
"github.com/number571/go-peer/pkg/payload"
)
const (
// third digits of PI
cAuthSalt = "8214808651_3282306647_0938446095_5058223172_5359408128"
CSaltSize = 32
)
var (
@ -21,16 +21,19 @@ var (
type sMessage struct {
fProof uint64
fSalt []byte
fHash []byte
fPayload payload.IPayload
}
func NewMessage(pSett ISettings, pPld payload.IPayload, pParallel uint64) IMessage {
hash := getHash(pSett.GetNetworkKey(), pPld.ToBytes())
salt := random.NewStdPRNG().GetBytes(CSaltSize)
hash := getHash(pSett.GetNetworkKey(), salt, pPld.ToBytes())
proof := puzzle.NewPoWPuzzle(pSett.GetWorkSizeBits()).ProofBytes(hash, pParallel)
return &sMessage{
fProof: proof,
fSalt: salt,
fHash: hash,
fPayload: pPld,
}
@ -43,18 +46,19 @@ func LoadMessage(pSett ISettings, pData interface{}) (IMessage, error) {
case []byte:
msgBytes = x
case string:
return LoadMessage(pSett, encoding.HexDecode(x))
msgBytes = encoding.HexDecode(x)
default:
return nil, ErrUnknownType
}
if len(msgBytes) < encoding.CSizeUint64+hashing.CSHA256Size {
if len(msgBytes) < encoding.CSizeUint64+CSaltSize+hashing.CSHA256Size {
return nil, ErrInvalidHeaderSize
}
proofBytes := msgBytes[:encoding.CSizeUint64]
gotHash := msgBytes[encoding.CSizeUint64 : encoding.CSizeUint64+hashing.CSHA256Size]
pldBytes := msgBytes[encoding.CSizeUint64+hashing.CSHA256Size:]
gotSalt := msgBytes[encoding.CSizeUint64 : encoding.CSizeUint64+CSaltSize]
gotHash := msgBytes[encoding.CSizeUint64+CSaltSize : encoding.CSizeUint64+CSaltSize+hashing.CSHA256Size]
pldBytes := msgBytes[encoding.CSizeUint64+CSaltSize+hashing.CSHA256Size:]
proofArray := [encoding.CSizeUint64]byte{}
copy(proofArray[:], proofBytes)
@ -65,7 +69,7 @@ func LoadMessage(pSett ISettings, pData interface{}) (IMessage, error) {
return nil, ErrInvalidProofOfWork
}
if !bytes.Equal(gotHash, getHash(pSett.GetNetworkKey(), pldBytes)) {
if !bytes.Equal(gotHash, getHash(pSett.GetNetworkKey(), gotSalt, pldBytes)) {
return nil, ErrInvalidAuthHash
}
@ -77,6 +81,7 @@ func LoadMessage(pSett ISettings, pData interface{}) (IMessage, error) {
return &sMessage{
fProof: proof,
fSalt: gotSalt,
fHash: gotHash,
fPayload: pld,
}, nil
@ -86,6 +91,10 @@ func (p *sMessage) GetProof() uint64 {
return p.fProof
}
func (p *sMessage) GetSalt() []byte {
return p.fSalt
}
func (p *sMessage) GetHash() []byte {
return p.fHash
}
@ -99,6 +108,7 @@ func (p *sMessage) ToBytes() []byte {
return bytes.Join(
[][]byte{
proofBytes[:],
p.fSalt,
p.fHash,
p.fPayload.ToBytes(),
},
@ -110,7 +120,7 @@ func (p *sMessage) ToString() string {
return encoding.HexEncode(p.ToBytes())
}
func getHash(networkKey string, pBytes []byte) []byte {
authKey := keybuilder.NewKeyBuilder(1, []byte(cAuthSalt)).Build(networkKey)
func getHash(networkKey string, pAuthSalt, pBytes []byte) []byte {
authKey := keybuilder.NewKeyBuilder(1, []byte(pAuthSalt)).Build(networkKey)
return hashing.NewHMACSHA256Hasher(authKey, pBytes).ToBytes()
}

View File

@ -2,7 +2,6 @@ package message
import (
"bytes"
"fmt"
"testing"
"github.com/number571/go-peer/pkg/crypto/hashing"
@ -21,7 +20,6 @@ const (
tcHead = 12345
tcBody = "hello, world!"
tcNetworkKey = "network_key_1"
tcProof = 1359
)
type sInvalidPayload struct{}
@ -53,7 +51,7 @@ func TestMessage(t *testing.T) {
return
}
if !bytes.Equal(msg.GetHash(), getHash(tcNetworkKey, pld.ToBytes())) {
if !bytes.Equal(msg.GetHash(), getHash(tcNetworkKey, msg.GetSalt(), pld.ToBytes())) {
t.Error("payload hash not equal hash of message")
return
}
@ -63,10 +61,21 @@ func TestMessage(t *testing.T) {
return
}
if msg.GetProof() != tcProof {
fmt.Println(msg.GetProof())
t.Error("got invalid proof")
return
for i := 0; i < 10; i++ {
msgN := NewMessage(sett, pld, 1)
if msgN.GetProof() == 0 {
continue
}
msgL, err := LoadMessage(sett, msgN.ToBytes())
if err != nil {
t.Error(err)
return
}
if msgN.GetProof() != msgL.GetProof() {
t.Error("got invalid proof")
return
}
break
}
msg1, err := LoadMessage(sett, msg.ToBytes())
@ -128,7 +137,7 @@ func TestMessage(t *testing.T) {
msgBytes := bytes.Join(
[][]byte{
{}, // pass payload
getHash("_", []byte{}),
getHash("_", []byte{}, []byte{}),
},
[]byte{},
)

View File

@ -9,6 +9,7 @@ type IMessage interface {
types.IConverter
GetProof() uint64
GetSalt() []byte
GetHash() []byte
GetPayload() payload.IPayload
}

File diff suppressed because it is too large Load Diff