diff --git a/bindings/README.md b/bindings/README.md index d9522bdbc0a6d3e9c8018f6782673b4149aafd46..13a38eea9924777b1f9228cd013327244c0d1ee8 100644 --- a/bindings/README.md +++ b/bindings/README.md @@ -3,18 +3,20 @@ ## Allowed Types > At present, only a subset of Go types are supported. -> +> > All exported symbols in the package must have types that are supported. Supported types include: -> +> > - Signed integer and floating point types. > - String and boolean types. > - Byte slice types. Note that byte slices are passed by reference, and support mutation. -> - Any function type all of whose parameters and results have supported types. Functions must return either no results, one result, or two results where the type of the second is the built-in 'error' type. +> - Any function type all of whose parameters and results have supported types. Functions must return either no results, + one result, or two results where the type of the second is the built-in 'error' type. > - Any interface type, all of whose exported methods have supported function types. -> - Any struct type, all of whose exported methods have supported function types and all of whose exported fields have supported types. Unexported symbols have no effect on the cross-language interface, and as such are not restricted. -> +> - Any struct type, all of whose exported methods have supported function types and all of whose exported fields have + supported types. Unexported symbols have no effect on the cross-language interface, and as such are not restricted. +> > The set of supported types will eventually be expanded to cover more Go types, but this is a work in progress. -> +> > Exceptions and panics are not yet supported. If either pass a language boundary, the program will exit. **Source:** https://pkg.go.dev/golang.org/x/mobile/cmd/gobind under *Type restrictions* heading \ No newline at end of file diff --git a/bindings/authenticatedConnection.go b/bindings/authenticatedConnection.go index 95f60c71ad58c6abb031ae054f7c1be350b58096..9f3ceb9fcba7a87c9624c91f4f1fe5d94d8e3d7e 100644 --- a/bindings/authenticatedConnection.go +++ b/bindings/authenticatedConnection.go @@ -16,8 +16,8 @@ import ( "gitlab.com/elixxir/crypto/contact" ) -//connection tracker singleton, used to track connections so they can be -//referenced by id back over the bindings +// authenticatedConnectionTrackerSingleton is used to track connections so that +// they can be referenced by ID back over the bindings. var authenticatedConnectionTrackerSingleton = &authenticatedConnectionTracker{ connections: make(map[int]*AuthenticatedConnection), count: 0, @@ -31,7 +31,7 @@ func (_ *AuthenticatedConnection) IsAuthenticated() bool { return true } -// ConnectWithAuthentication is called by the client (i.e. the one establishing +// ConnectWithAuthentication is called by the client (i.e., the one establishing // connection with the server). Once a connect.Connection has been established // with the server and then authenticate their identity to the server. // accepts a marshalled ReceptionIdentity and contact.Contact object @@ -62,9 +62,8 @@ func (c *Cmix) ConnectWithAuthentication(e2eId int, recipientContact, return authenticatedConnectionTrackerSingleton.make(connection), err } -// connectionTracker is a singleton used to keep track of extant clients, allowing -// for race condition free passing over the bindings - +// authenticatedConnectionTracker is a singleton used to keep track of extant +// clients, allowing for race condition-free passing over the bindings. type authenticatedConnectionTracker struct { connections map[int]*AuthenticatedConnection count int @@ -72,7 +71,8 @@ type authenticatedConnectionTracker struct { } // make makes a client from an API client, assigning it a unique ID -func (act *authenticatedConnectionTracker) make(c connect.AuthenticatedConnection) *AuthenticatedConnection { +func (act *authenticatedConnectionTracker) make( + c connect.AuthenticatedConnection) *AuthenticatedConnection { act.mux.Lock() defer act.mux.Unlock() @@ -89,21 +89,22 @@ func (act *authenticatedConnectionTracker) make(c connect.AuthenticatedConnectio return act.connections[id] } -//get returns a client given its ID -func (act *authenticatedConnectionTracker) get(id int) (*AuthenticatedConnection, error) { +// get returns a client given its ID. +func (act *authenticatedConnectionTracker) get(id int) ( + *AuthenticatedConnection, error) { act.mux.RLock() defer act.mux.RUnlock() c, exist := act.connections[id] if !exist { - return nil, errors.Errorf("Cannot get client for id %d, client "+ + return nil, errors.Errorf("Cannot get client for ID %d, client "+ "does not exist", id) } return c, nil } -//deletes a client if it exists +// delete deletes a client, if it exists. func (act *authenticatedConnectionTracker) delete(id int) { act.mux.Lock() defer act.mux.Unlock() diff --git a/bindings/cmix.go b/bindings/cmix.go index f37b778dd30299b66e8a3641c1d6f88461325c3a..fc74005a9562041efedd8e227c2c59a1789846c1 100644 --- a/bindings/cmix.go +++ b/bindings/cmix.go @@ -8,7 +8,6 @@ package bindings import ( - "fmt" "sync" "github.com/pkg/errors" @@ -16,21 +15,21 @@ import ( "gitlab.com/elixxir/client/xxdk" ) -// init sets the log level +// init sets the log level to INFO. func init() { jww.SetLogThreshold(jww.LevelInfo) jww.SetStdoutThreshold(jww.LevelInfo) } -// cmixTrackerSingleton is used to track Cmix objects so that -// they can be referenced by id back over the bindings +// cmixTrackerSingleton is used to track Cmix objects so that they can be +// referenced by ID back over the bindings. var cmixTrackerSingleton = &cmixTracker{ clients: make(map[int]*Cmix), count: 0, } -// Cmix wraps the xxdk.Cmix struct, implementing additional functions -// to support the gomobile Cmix interface +// Cmix wraps the xxdk.Cmix struct, implementing additional functions to support +// the bindings Cmix interface. type Cmix struct { api *xxdk.Cmix id int @@ -43,24 +42,25 @@ type Cmix struct { // // Users of this function should delete the storage directory on error. func NewCmix(ndfJSON, storageDir string, password []byte, registrationCode string) error { - if err := xxdk.NewCmix(ndfJSON, storageDir, password, registrationCode); err != nil { - return errors.New(fmt.Sprintf("Failed to create new client: %+v", - err)) + err := xxdk.NewCmix(ndfJSON, storageDir, password, registrationCode) + if err != nil { + return errors.Errorf("Failed to create new client: %+v", err) } return nil } -// LoadCmix will load an existing client from the storageDir -// using the password. This will fail if the client doesn't exist or -// the password is incorrect. -// The password is passed as a byte array so that it can be cleared from -// memory and stored as securely as possible using the memguard library. -// LoadCmix does not block on network connection, and instead loads and -// starts subprocesses to perform network operations. +// LoadCmix will load an existing client from the storageDir using the password. +// This will fail if the client does not exist or the password is incorrect. +// +// The password is passed as a byte array so that it can be cleared from memory +// and stored as securely as possible using the MemGuard library. +// +// LoadCmix does not block on network connection and instead loads and starts +// subprocesses to perform network operations. func LoadCmix(storageDir string, password []byte, cmixParamsJSON []byte) (*Cmix, error) { if len(cmixParamsJSON) == 0 { - jww.WARN.Printf("cmix params not specified, using defaults...") + jww.WARN.Printf("cMix params not specified, using defaults...") cmixParamsJSON = GetDefaultCMixParams() } @@ -71,26 +71,27 @@ func LoadCmix(storageDir string, password []byte, cmixParamsJSON []byte) (*Cmix, client, err := xxdk.LoadCmix(storageDir, password, params) if err != nil { - return nil, errors.New(fmt.Sprintf("LoadCmix failed: %+v", err)) + return nil, errors.Errorf("LoadCmix failed: %+v", err) } return cmixTrackerSingleton.make(client), nil } +// GetID returns the ID for this Cmix in the cmixTracker. func (c *Cmix) GetID() int { return c.id } // cmixTracker is a singleton used to keep track of extant Cmix objects, -// preventing race conditions created by passing it over the bindings +// preventing race conditions created by passing it over the bindings. type cmixTracker struct { clients map[int]*Cmix count int mux sync.RWMutex } -// make a Cmix from an xxdk.Cmix, assigns it a unique ID, -// and adds it to the cmixTracker +// make creates a Cmix from a xxdk.Cmix, assigns it a unique ID,and adds it to +// the cmixTracker. func (ct *cmixTracker) make(c *xxdk.Cmix) *Cmix { ct.mux.Lock() defer ct.mux.Unlock() @@ -106,21 +107,21 @@ func (ct *cmixTracker) make(c *xxdk.Cmix) *Cmix { return ct.clients[id] } -// get a Cmix from the cmixTracker given its ID +// get returns a Cmix from the cmixTracker given its ID. func (ct *cmixTracker) get(id int) (*Cmix, error) { ct.mux.RLock() defer ct.mux.RUnlock() c, exist := ct.clients[id] if !exist { - return nil, errors.Errorf("Cannot get client for id %d, client "+ - "does not exist", id) + return nil, errors.Errorf( + "Cannot get client for ID %d, client does not exist", id) } return c, nil } -// delete a Cmix if it exists in the cmixTracker +// delete a Cmix from the cmixTracker. func (ct *cmixTracker) delete(id int) { ct.mux.Lock() defer ct.mux.Unlock() diff --git a/bindings/connect.go b/bindings/connect.go index 85c25b4ee96f37d100c61d8449658d836da53729..bccc8d267f64ac53e5d7e1522f89dffb17b5e682 100644 --- a/bindings/connect.go +++ b/bindings/connect.go @@ -19,31 +19,36 @@ import ( "gitlab.com/elixxir/crypto/contact" ) -// connectionTrackerSingleton is used to track connections so they can be -// referenced by id back over the bindings +// connectionTrackerSingleton is used to track connections so that they can be +// referenced by ID back over the bindings. var connectionTrackerSingleton = &connectionTracker{ connections: make(map[int]*Connection), count: 0, } -// Connection is the bindings representation of a connect.Connection object that can be tracked by id +// Connection is the bindings' representation of a connect.Connection object +// that can be tracked by ID. type Connection struct { connection connect.Connection id int params xxdk.E2EParams } -// GetId returns the Connection.id +// GetId returns the Connection ID. func (c *Connection) GetId() int { return c.id } -// Connect performs auth key negotiation with the given recipient, -// and returns a Connection object for the newly-created partner.Manager +// Connect performs auth key negotiation with the given recipient and returns a +// Connection object for the newly created partner.Manager. +// // This function is to be used sender-side and will block until the // partner.Manager is confirmed. -// recipientContact - marshalled contact.Contact object -// myIdentity - marshalled ReceptionIdentity object +// +// Parameters: +// - e2eId - ID of the E2E object in the e2e tracker +// - recipientContact - marshalled contact.Contact object +// - myIdentity - marshalled ReceptionIdentity object func (c *Cmix) Connect(e2eId int, recipientContact, e2eParamsJSON []byte) ( *Connection, error) { if len(e2eParamsJSON) == 0 { @@ -73,8 +78,8 @@ func (c *Cmix) Connect(e2eId int, recipientContact, e2eParamsJSON []byte) ( return connectionTrackerSingleton.make(connection, p), nil } -// SendE2E is a wrapper for sending specifically to the Connection's partner.Manager -// Returns marshalled E2ESendReport +// SendE2E is a wrapper for sending specifically to the Connection's +// partner.Manager. Returns a marshalled E2ESendReport. func (c *Connection) SendE2E(mt int, payload []byte) ([]byte, error) { rounds, mid, ts, err := c.connection.SendE2E(catalog.MessageType(mt), payload, c.params.Base) @@ -93,36 +98,35 @@ func (c *Connection) SendE2E(mt int, payload []byte) ([]byte, error) { return json.Marshal(&sr) } -// Close deletes this Connection's partner.Manager and releases resources +// Close deletes this Connection's partner.Manager and releases resources. func (c *Connection) Close() error { return c.connection.Close() } -// GetPartner returns the partner.Manager for this Connection +// GetPartner returns the partner.Manager for this Connection. func (c *Connection) GetPartner() []byte { return c.connection.GetPartner().PartnerId().Marshal() } -// RegisterListener is used for E2E reception -// and allows for reading data sent from the partner.Manager -// Returns marshalled ListenerID +// RegisterListener is used for E2E reception and allows for reading data sent +// from the partner.Manager. func (c *Connection) RegisterListener(messageType int, newListener Listener) error { - _, err := c.connection.RegisterListener(catalog.MessageType(messageType), listener{l: newListener}) + _, err := c.connection.RegisterListener( + catalog.MessageType(messageType), listener{l: newListener}) return err } -// connectionTracker is a singleton used to keep track of extant clients, allowing -// for race condition free passing over the bindings - +// connectionTracker is a singleton used to keep track of extant connections, +// allowing for race condition-free passing over the bindings. type connectionTracker struct { connections map[int]*Connection count int mux sync.RWMutex } -// make makes a client from an API client, assigning it a unique ID -func (ct *connectionTracker) make(c connect.Connection, - params xxdk.E2EParams) *Connection { +// make makes a Connection, assigning it a unique ID. +func (ct *connectionTracker) make( + c connect.Connection, params xxdk.E2EParams) *Connection { ct.mux.Lock() defer ct.mux.Unlock() @@ -138,21 +142,21 @@ func (ct *connectionTracker) make(c connect.Connection, return ct.connections[id] } -//get returns a client given its ID +// get returns a Connection given its ID. func (ct *connectionTracker) get(id int) (*Connection, error) { ct.mux.RLock() defer ct.mux.RUnlock() c, exist := ct.connections[id] if !exist { - return nil, errors.Errorf("Cannot get client for id %d, client "+ + return nil, errors.Errorf("Cannot get client for ID %d, client "+ "does not exist", id) } return c, nil } -//deletes a client if it exists +// delete deletes a Connection. func (ct *connectionTracker) delete(id int) { ct.mux.Lock() defer ct.mux.Unlock() diff --git a/bindings/connect_test.go b/bindings/connect_test.go index f6152c768365d15cd5e29476af00dd2b587c02f3..c23027b103f3261023fff389b458562047e2da04 100644 --- a/bindings/connect_test.go +++ b/bindings/connect_test.go @@ -21,7 +21,7 @@ import ( func TestE2ESendReport_JSON(t *testing.T) { rng := csprng.NewSystemRNG() mid := e2e.MessageID{} - rng.Read(mid[:]) + _, _ = rng.Read(mid[:]) origRL := []id.Round{1, 5, 9} rl := makeRoundsList(origRL) mrl, _ := json.Marshal(&rl) @@ -40,6 +40,7 @@ func TestE2ESendReport_JSON(t *testing.T) { t.Errorf("Failed to unmarshal rounds list from e2esendreport: %+v", err) } if !reflect.DeepEqual(unmarshalled, origRL) { - t.Errorf("Did not receive expected rounds list\n\tExpected: %+v\n\tReceived: %+v\n", rl.Rounds, unmarshalled) + t.Errorf("Did not receive expected rounds list"+ + "\nexpected: %+v\nreceived: %+v", rl.Rounds, unmarshalled) } } diff --git a/bindings/delivery.go b/bindings/delivery.go index 0efa3e636f61a6520c6e34e8d15efd68d15c36ca..a160813bf10f9f4483a0d7f75db287f1784fc070 100644 --- a/bindings/delivery.go +++ b/bindings/delivery.go @@ -9,7 +9,6 @@ package bindings import ( "encoding/json" - "fmt" "time" "github.com/pkg/errors" @@ -18,17 +17,21 @@ import ( "gitlab.com/xx_network/primitives/id" ) +// RoundsList contains a list of round IDs. +// // Example marshalled roundList object: -// [1001,1003,1006] +// [1001,1003,1006] type RoundsList struct { Rounds []int } +// Marshal JSON marshals the RoundsList. func (rl RoundsList) Marshal() ([]byte, error) { return json.Marshal(&rl) } -// unmarshalRoundsList accepts a marshalled E2ESendReport object & unmarshalls it into a RoundsList object, returning a list of id.Round +// unmarshalRoundsList accepts a marshalled E2ESendReport object and unmarshalls +// it into a RoundsList object, returning a list of id.Round. func unmarshalRoundsList(marshaled []byte) ([]id.Round, error) { sr := RoundsList{} err := json.Unmarshal(marshaled, &sr) @@ -56,8 +59,11 @@ func makeRoundsList(rounds []id.Round) RoundsList { // MessageDeliveryCallback gets called on the determination if all events // related to a message send were successful. +// // If delivered == true, timedOut == false && roundResults != nil +// // If delivered == false, roundResults == nil +// // If timedOut == true, delivered == false && roundResults == nil type MessageDeliveryCallback interface { EventCallback(delivered, timedOut bool, roundResults []byte) @@ -65,35 +71,32 @@ type MessageDeliveryCallback interface { // WaitForMessageDelivery allows the caller to get notified if the rounds a // message was sent in successfully completed. Under the hood, this uses an API -// which uses the internal round data, network historical round lookup, and +// that uses the internal round data, network historical round lookup, and // waiting on network events to determine what has (or will) occur. // -// The callbacks will return at timeoutMS if no state update occurs +// The callbacks will return at timeoutMS if no state update occurs. // // This function takes the marshaled send report to ensure a memory leak does // not occur as a result of both sides of the bindings holding a reference to // the same pointer. -func (c *Cmix) WaitForMessageDelivery(roundList []byte, - mdc MessageDeliveryCallback, timeoutMS int) error { - jww.INFO.Printf("WaitForMessageDelivery(%v, _, %v)", - roundList, timeoutMS) +func (c *Cmix) WaitForMessageDelivery( + roundList []byte, mdc MessageDeliveryCallback, timeoutMS int) error { + jww.INFO.Printf("WaitForMessageDelivery(%v, _, %v)", roundList, timeoutMS) rl, err := unmarshalRoundsList(roundList) if err != nil { - return errors.New(fmt.Sprintf("Failed to "+ - "WaitForMessageDelivery callback due to bad Send Report: %+v", err)) + return errors.Errorf("Failed to WaitForMessageDelivery callback due "+ + "to bad Send Report: %+v", err) } if rl == nil || len(rl) == 0 { - return errors.New(fmt.Sprintf("Failed to "+ - "WaitForMessageDelivery callback due to invalid Send Report "+ - "unmarshal: %s", string(roundList))) + return errors.Errorf("Failed to WaitForMessageDelivery callback due "+ + "to invalid Send Report unmarshal: %s", roundList) } f := func(allRoundsSucceeded, timedOut bool, rounds map[id.Round]cmix.RoundResult) { results := make([]byte, len(rl)) jww.INFO.Printf("Processing WaitForMessageDelivery report "+ - "success: %v, timedout: %v", allRoundsSucceeded, - timedOut) + "success: %v, timeout: %v", allRoundsSucceeded, timedOut) for i, r := range rl { if result, exists := rounds[r]; exists { results[i] = byte(result.Status) diff --git a/bindings/e2e.go b/bindings/e2e.go index 32dacd40d9acc4bdc01ec3b9459731d88395dbb0..eab868feda8ff288a82ec6653756b8b99e1f3563 100644 --- a/bindings/e2e.go +++ b/bindings/e2e.go @@ -18,28 +18,29 @@ import ( "gitlab.com/elixxir/crypto/contact" ) -// e2eTrackerSingleton is used to track E2e objects so that -// they can be referenced by id back over the bindings +// e2eTrackerSingleton is used to track E2e objects so that they can be +// referenced by ID back over the bindings. var e2eTrackerSingleton = &e2eTracker{ clients: make(map[int]*E2e), count: 0, } // E2e BindingsClient wraps the xxdk.E2e, implementing additional functions -// to support the gomobile E2e interface +// to support the bindings E2e interface. type E2e struct { api *xxdk.E2e id int } -// GetID returns the e2eTracker ID for the E2e object +// GetID returns the e2eTracker ID for the E2e object. func (e *E2e) GetID() int { return e.id } -// Login creates and returns a new E2e object and adds it to the e2eTrackerSingleton -// identity should be created via MakeReceptionIdentity() and passed in here -// If callbacks is left nil, a default auth.Callbacks will be used +// Login creates and returns a new E2e object and adds it to the +// e2eTrackerSingleton. identity should be created via +// Cmix.MakeReceptionIdentity and passed in here. If callbacks is left nil, a +// default auth.Callbacks will be used. func Login(cmixId int, callbacks AuthCallbacks, identity, e2eParamsJSON []byte) (*E2e, error) { if len(e2eParamsJSON) == 0 { @@ -77,9 +78,10 @@ func Login(cmixId int, callbacks AuthCallbacks, identity, return e2eTrackerSingleton.make(newE2e), nil } -// LoginEphemeral creates and returns a new ephemeral E2e object and adds it to the e2eTrackerSingleton -// identity should be created via MakeReceptionIdentity() or MakeLegacyReceptionIdentity() and passed in here -// If callbacks is left nil, a default auth.Callbacks will be used +// LoginEphemeral creates and returns a new ephemeral E2e object and adds it to +// the e2eTrackerSingleton. identity should be created via +// Cmix.MakeReceptionIdentity or Cmix.MakeLegacyReceptionIdentity and passed in +// here. If callbacks is left nil, a default auth.Callbacks will be used. func LoginEphemeral(cmixId int, callbacks AuthCallbacks, identity, e2eParamsJSON []byte) (*E2e, error) { if len(e2eParamsJSON) == 0 { @@ -117,7 +119,8 @@ func LoginEphemeral(cmixId int, callbacks AuthCallbacks, identity, return e2eTrackerSingleton.make(newE2e), nil } -// GetContact returns a marshalled contact.Contact object for the E2e ReceptionIdentity +// GetContact returns a marshalled contact.Contact object for the E2e +// ReceptionIdentity. func (e *E2e) GetContact() []byte { return e.api.GetReceptionIdentity().GetContact().Marshal() } @@ -129,16 +132,16 @@ type AuthCallbacks interface { Reset(contact, receptionId []byte, ephemeralId, roundId int64) } -// authCallback implements AuthCallbacks as a way of obtaining -// an auth.Callbacks over the bindings +// authCallback implements AuthCallbacks as a way of obtaining an auth.Callbacks +// over the bindings. type authCallback struct { bindingsCbs AuthCallbacks } -// convertAuthCallbacks turns an auth.Callbacks into an AuthCallbacks +// convertAuthCallbacks turns an auth.Callbacks into an AuthCallbacks. func convertAuthCallbacks(requestor contact.Contact, - receptionID receptionID.EphemeralIdentity, - round rounds.Round) (contact []byte, receptionId []byte, ephemeralId int64, roundId int64) { + receptionID receptionID.EphemeralIdentity, round rounds.Round) ( + contact []byte, receptionId []byte, ephemeralId int64, roundId int64) { contact = requestor.Marshal() receptionId = receptionID.Source.Marshal() @@ -166,7 +169,7 @@ func (a *authCallback) Reset(partner contact.Contact, } // e2eTracker is a singleton used to keep track of extant E2e objects, -// preventing race conditions created by passing it over the bindings +// preventing race conditions created by passing it over the bindings. type e2eTracker struct { // TODO: Key on Identity.ID to prevent duplication clients map[int]*E2e @@ -174,8 +177,8 @@ type e2eTracker struct { mux sync.RWMutex } -// make a E2e from an xxdk.E2e, assigns it a unique ID, -// and adds it to the e2eTracker +// make create an E2e from a xxdk.E2e, assigns it a unique ID, and adds it to +// the e2eTracker. func (ct *e2eTracker) make(c *xxdk.E2e) *E2e { ct.mux.Lock() defer ct.mux.Unlock() @@ -191,21 +194,21 @@ func (ct *e2eTracker) make(c *xxdk.E2e) *E2e { return ct.clients[id] } -// get an E2e from the e2eTracker given its ID +// get an E2e from the e2eTracker given its ID. func (ct *e2eTracker) get(id int) (*E2e, error) { ct.mux.RLock() defer ct.mux.RUnlock() c, exist := ct.clients[id] if !exist { - return nil, errors.Errorf("Cannot get client for id %d, client "+ + return nil, errors.Errorf("Cannot get client for ID %d, client "+ "does not exist", id) } return c, nil } -// delete an E2e if it exists in the e2eTracker +// delete an E2e from the e2eTracker. func (ct *e2eTracker) delete(id int) { ct.mux.Lock() defer ct.mux.Unlock() diff --git a/bindings/e2eAuth.go b/bindings/e2eAuth.go index 77083daa290bfcd1dbd27ffe714e2d456624475d..77df3f8b10aeb6add590cf9886f5dcc557e60558 100644 --- a/bindings/e2eAuth.go +++ b/bindings/e2eAuth.go @@ -14,23 +14,28 @@ import ( "gitlab.com/xx_network/primitives/id" ) -// Request sends a contact request from the user identity in the imported e2e -// structure to the passed contact, as well as the passed facts (will error if -// they are too long). -// The other party must accept the request by calling Confirm in order to be -// able to send messages using e2e.Handler.SendE2E. When the other party does -// so, the "confirm" callback will get called. +// Request sends a contact request from the user identity in the imported E2e +// structure to the passed contact, as well as the passed facts (it will error +// if they are too long). +// +// The other party must accept the request by calling Confirm to be able to send +// messages using E2e.SendE2E. When the other party does so, the "confirm" +// callback will get called. +// // The round the request is initially sent on will be returned, but the request // will be listed as a critical message, so the underlying cMix client will auto // resend it in the event of failure. +// // A request cannot be sent for a contact who has already received a request or // who is already a partner. -// The request sends as a critical message, if the round send on fails, it will -// be auto resent by the cMix client. +// +// The request sends as a critical message, if the round it sends on fails, it +// will be auto resent by the cMix client. // // Parameters: // - partnerContact - the marshalled bytes of the contact.Contact object. // - myFacts - stringified list of fact.FactList. +// // Returns: // - int64 - ID of the round (convert to uint64) func (e *E2e) Request(partnerContact []byte, myFactsString string) (int64, error) { @@ -52,18 +57,22 @@ func (e *E2e) Request(partnerContact []byte, myFactsString string) (int64, error // Confirm sends a confirmation for a received request. It can only be called // once. This both sends keying material to the other party and creates a // channel in the e2e handler, after which e2e messages can be sent to the -// partner using e2e.Handler.SendE2E. +// partner using E2e.SendE2E. +// // The round the request is initially sent on will be returned, but the request // will be listed as a critical message, so the underlying cMix client will auto // resend it in the event of failure. -// A confirm cannot be sent for a contact who has not sent a request or who is -// already a partner. This can only be called once for a specific contact. -// The confirm sends as a critical message; if the round it sends on fails, it -// will be auto resend by the cMix client. -// If the confirm must be resent, use ReplayConfirm. +// +// A confirmation cannot be sent for a contact who has not sent a request or who +// is already a partner. This can only be called once for a specific contact. +// The confirmation sends as a critical message; if the round it sends on fails, +// it will be auto resent by the cMix client. +// +// If the confirmation must be resent, use ReplayConfirm. // // Parameters: // - partnerContact - the marshalled bytes of the contact.Contact object. +// // Returns: // - int64 - ID of the round (convert to uint64) func (e *E2e) Confirm(partnerContact []byte) (int64, error) { @@ -80,16 +89,20 @@ func (e *E2e) Confirm(partnerContact []byte) (int64, error) { // Reset sends a contact reset request from the user identity in the imported // e2e structure to the passed contact, as well as the passed facts (it will // error if they are too long). +// // This deletes all traces of the relationship with the partner from e2e and // create a new relationship from scratch. +// // The round the reset is initially sent on will be returned, but the request // will be listed as a critical message, so the underlying cMix client will auto // resend it in the event of failure. +// // A request cannot be sent for a contact who has already received a request or // who is already a partner. // // Parameters: // - partnerContact - the marshalled bytes of the contact.Contact object. +// // Returns: // - int64 - ID of the round (convert to uint64) func (e *E2e) Reset(partnerContact []byte) (int64, error) { @@ -103,14 +116,17 @@ func (e *E2e) Reset(partnerContact []byte) (int64, error) { return int64(roundID), err } -// ReplayConfirm resends a confirm to the partner. It will fail to send if the -// send relationship with the partner has already ratcheted. -// The confirm sends as a critical message; if the round it sends on fails, it -// will be auto resend by the cMix client. +// ReplayConfirm resends a confirmation to the partner. It will fail to send if +// the send relationship with the partner has already ratcheted. +// +// The confirmation sends as a critical message; if the round it sends on fails, +// it will be auto resent by the cMix client. +// // This will not be useful if either side has ratcheted. // // Parameters: // - partnerID - the marshalled bytes of the id.ID object. +// // Returns: // - int64 - ID of the round (convert to uint64) func (e *E2e) ReplayConfirm(partnerID []byte) (int64, error) { @@ -153,15 +169,17 @@ func (e *E2e) DeleteSentRequests() error { return e.api.GetAuth().DeleteSentRequests() } -// DeleteReceiveRequests clears all received requests from client's auth storage. +// DeleteReceiveRequests clears all received requests from client's auth +// storage. func (e *E2e) DeleteReceiveRequests() error { return e.api.GetAuth().DeleteReceiveRequests() } -// GetReceivedRequest returns a contact if there's a received request for it. +// GetReceivedRequest returns a contact if there is a received request for it. // // Parameters: // - partnerID - the marshalled bytes of the id.ID object. +// // Returns: // - []byte - the marshalled bytes of the contact.Contact object. func (e *E2e) GetReceivedRequest(partnerID []byte) ([]byte, error) { diff --git a/bindings/e2eHandler.go b/bindings/e2eHandler.go index 5114f46ee96bade011fc1c5c90e335f6c529de1d..11b14e0e3888ae017973dd4010fb331c69daec6b 100644 --- a/bindings/e2eHandler.go +++ b/bindings/e2eHandler.go @@ -19,31 +19,35 @@ import ( "gitlab.com/xx_network/primitives/id" ) -// IdList is a wrapper for a list of marshalled id.ID objects +// IdList is a wrapper for a list of marshalled id.ID objects. type IdList struct { Ids [][]byte } -// E2ESendReport is the bindings representation of the return values of SendE2E +// E2ESendReport is the bindings' representation of the return values of +// SendE2E. +// // Example E2ESendReport: -// {"Rounds":[1,5,9], -// "MessageID":"51Yy47uZbP0o2Y9B/kkreDLTB6opUol3M3mYiY2dcdQ=", -// "Timestamp":1653582683183384000} +// {"Rounds":[1,5,9], +// "MessageID":"51Yy47uZbP0o2Y9B/kkreDLTB6opUol3M3mYiY2dcdQ=", +// "Timestamp":1653582683183384000} type E2ESendReport struct { RoundsList MessageID []byte Timestamp int64 } -// GetReceptionID returns the marshalled default IDs +// GetReceptionID returns the marshalled default IDs. +// // Returns: // - []byte - the marshalled bytes of the id.ID object. func (e *E2e) GetReceptionID() []byte { return e.api.GetE2E().GetReceptionID().Marshal() } -// GetAllPartnerIDs returns a marshalled list of all partner IDs that the user has -// an E2E relationship with. +// GetAllPartnerIDs returns a marshalled list of all partner IDs that the user +// has an E2E relationship with. +// // Returns: // - []byte - the marshalled bytes of the IdList object. func (e *E2e) GetAllPartnerIDs() ([]byte, error) { @@ -55,39 +59,40 @@ func (e *E2e) GetAllPartnerIDs() ([]byte, error) { return json.Marshal(IdList{Ids: convertedIds}) } -// PayloadSize Returns the max payload size for a partitionable E2E -// message +// PayloadSize returns the max payload size for a partitionable E2E message. func (e *E2e) PayloadSize() int { return int(e.api.GetE2E().PayloadSize()) } -// SecondPartitionSize returns the max partition payload size for all -// payloads after the first payload +// SecondPartitionSize returns the max partition payload size for all payloads +// after the first payload. func (e *E2e) SecondPartitionSize() int { return int(e.api.GetE2E().SecondPartitionSize()) } -// PartitionSize returns the partition payload size for the given -// payload index. The first payload is index 0. +// PartitionSize returns the partition payload size for the given payload index. +// The first payload is index 0. func (e *E2e) PartitionSize(payloadIndex int) int { return int(e.api.GetE2E().PartitionSize(uint(payloadIndex))) } -// FirstPartitionSize returns the max partition payload size for the -// first payload +// FirstPartitionSize returns the max partition payload size for the first +// payload. func (e *E2e) FirstPartitionSize() int { return int(e.api.GetE2E().FirstPartitionSize()) } -// GetHistoricalDHPrivkey returns the user's marshalled Historical DH Private Key +// GetHistoricalDHPrivkey returns the user's marshalled historical DH private +// key. +// // Returns: // - []byte - the marshalled bytes of the cyclic.Int object. func (e *E2e) GetHistoricalDHPrivkey() ([]byte, error) { return e.api.GetE2E().GetHistoricalDHPrivkey().MarshalJSON() } -// GetHistoricalDHPubkey returns the user's marshalled Historical DH -// Public Key +// GetHistoricalDHPubkey returns the user's marshalled historical DH public key. +// // Returns: // - []byte - the marshalled bytes of the cyclic.Int object. func (e *E2e) GetHistoricalDHPubkey() ([]byte, error) { @@ -95,7 +100,8 @@ func (e *E2e) GetHistoricalDHPubkey() ([]byte, error) { } // HasAuthenticatedChannel returns true if an authenticated channel with the -// partner exists, otherwise returns false +// partner exists, otherwise returns false. +// // Parameters: // - partnerId - the marshalled bytes of the id.ID object. func (e *E2e) HasAuthenticatedChannel(partnerId []byte) (bool, error) { @@ -106,23 +112,23 @@ func (e *E2e) HasAuthenticatedChannel(partnerId []byte) (bool, error) { return e.api.GetE2E().HasAuthenticatedChannel(partner), nil } -// RemoveService removes all services for the given tag +// RemoveService removes all services for the given tag. func (e *E2e) RemoveService(tag string) error { return e.api.GetE2E().RemoveService(tag) } -// SendE2E send a message containing the payload to the -// recipient of the passed message type, per the given -// parameters - encrypted with end-to-end encryption. -// Default parameters can be retrieved through +// SendE2E send a message containing the payload to the recipient of the passed +// message type, per the given parameters--encrypted with end-to-end encryption. +// // Parameters: // - recipientId - the marshalled bytes of the id.ID object. // - e2eParams - the marshalled bytes of the e2e.Params object. +// // Returns: // - []byte - the marshalled bytes of the E2ESendReport object. func (e *E2e) SendE2E(messageType int, recipientId, payload, e2eParams []byte) ([]byte, error) { - // Note that specifically these are the .Base params from xxdk.E2EParams + // Note that specifically these are the Base params from xxdk.E2EParams params := e2e.GetDefaultParams() err := params.UnmarshalJSON(e2eParams) if err != nil { @@ -133,7 +139,8 @@ func (e *E2e) SendE2E(messageType int, recipientId, payload, return nil, err } - roundIds, messageId, ts, err := e.api.GetE2E().SendE2E(catalog.MessageType(messageType), recipient, payload, params) + roundIds, messageId, ts, err := e.api.GetE2E().SendE2E( + catalog.MessageType(messageType), recipient, payload, params) if err != nil { return nil, err } @@ -146,17 +153,17 @@ func (e *E2e) SendE2E(messageType int, recipientId, payload, return json.Marshal(result) } -// AddService adds a service for all partners of the given -// tag, which will call back on the given processor. These can -// be sent to using the tag fields in the Params Object -// Passing nil for the processor allows you to create a -// service which is never called but will be visible by -// notifications. Processes added this way are generally not -// end-to-end encrypted messages themselves, but other -// protocols which piggyback on e2e relationships to start -// communication +// AddService adds a service for all partners of the given tag, which will call +// back on the given processor. These can be sent to using the tag fields in the +// Params object. +// +// Passing nil for the processor allows you to create a service that is never +// called but will be visible by notifications. Processes added this way are +// generally not end-to-end encrypted messages themselves, but other protocols +// that piggyback on e2e relationships to start communication. func (e *E2e) AddService(tag string, processor Processor) error { - return e.api.GetE2E().AddService(tag, &messageProcessor{bindingsCbs: processor}) + return e.api.GetE2E().AddService( + tag, &messageProcessor{bindingsCbs: processor}) } // Processor is the bindings-specific interface for message.Processor methods. @@ -165,16 +172,16 @@ type Processor interface { fmt.Stringer } -// messageProcessor implements Processor as a way of obtaining -// a message.Processor over the bindings +// messageProcessor implements Processor as a way of obtaining a +// message.Processor over the bindings. type messageProcessor struct { bindingsCbs Processor } // convertAuthCallbacks turns an auth.Callbacks into an AuthCallbacks func convertProcessor(msg format.Message, - receptionID receptionID.EphemeralIdentity, - round rounds.Round) (message []byte, receptionId []byte, ephemeralId int64, roundId int64) { + receptionID receptionID.EphemeralIdentity, round rounds.Round) ( + message []byte, receptionId []byte, ephemeralId int64, roundId int64) { message = msg.Marshal() receptionId = receptionID.Source.Marshal() @@ -185,17 +192,18 @@ func convertProcessor(msg format.Message, // Process decrypts and hands off the message to its internal down stream // message processing system. -// CRITICAL: Fingerprints should never be used twice. Process must denote, -// in long term storage, usage of a fingerprint and that fingerprint must -// not be added again during application load. -// It is a security vulnerability to reuse a fingerprint. It leaks privacy -// and can lead to compromise of message contents and integrity. +// +// CRITICAL: Fingerprints should never be used twice. Process must denote, in +// long-term storage, usage of a fingerprint and that fingerprint must not be +// added again during application load. It is a security vulnerability to reuse +// a fingerprint. It leaks privacy and can lead to compromise of message +// contents and integrity. func (m *messageProcessor) Process(msg format.Message, receptionID receptionID.EphemeralIdentity, roundId rounds.Round) { m.bindingsCbs.Process(convertProcessor(msg, receptionID, roundId)) } -// Stringer interface for debugging +// String prints a name for debugging. func (m *messageProcessor) String() string { return m.bindingsCbs.String() } diff --git a/bindings/fileTransfer.go b/bindings/fileTransfer.go index b9d3e802be559af4c83ad131b967228be00c759c..7be3a93b91ebd935baadeacd0bc19d0af030d712 100644 --- a/bindings/fileTransfer.go +++ b/bindings/fileTransfer.go @@ -18,83 +18,115 @@ import ( "gitlab.com/xx_network/primitives/id" ) -/* File Transfer Structs and Interfaces */ +//////////////////////////////////////////////////////////////////////////////// +// File Transfer Structs and Interfaces // +//////////////////////////////////////////////////////////////////////////////// -// FileTransfer object is a bindings-layer struct which wraps a fileTransfer.FileTransfer interface +// FileTransfer object is a bindings-layer struct which wraps a +// fileTransfer.FileTransfer interface. type FileTransfer struct { ft fileTransfer.FileTransfer e2eCl *E2e } -// ReceivedFile is a public struct which represents the contents of an incoming file +// ReceivedFile is a public struct that contains the metadata of a new file +// transfer. +// // Example JSON: -// { -// "TransferID":"B4Z9cwU18beRoGbk5xBjbcd5Ryi9ZUFA2UBvi8FOHWo=", // ID of the incoming transfer for receiving -// "SenderID":"emV6aW1hAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD", // ID of sender of incoming file -// "Preview":"aXQncyBtZSBhIHByZXZpZXc=", // Preview of the incoming file -// "Name":"testfile.txt", // Name of incoming file -// "Type":"text file", // Incoming file type -// "Size":2048 // Incoming file size -// } +// { +// "TransferID":"B4Z9cwU18beRoGbk5xBjbcd5Ryi9ZUFA2UBvi8FOHWo=", +// "SenderID":"emV6aW1hAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD", +// "Preview":"aXQncyBtZSBhIHByZXZpZXc=", +// "Name":"testfile.txt", +// "Type":"text file", +// "Size":2048 +// } type ReceivedFile struct { - TransferID []byte - SenderID []byte - Preview []byte - Name string - Type string - Size int + TransferID []byte // ID of the file transfer + SenderID []byte // ID of the file sender + Preview []byte // A preview of the file + Name string // Name of the file + Type string // String that indicates type of file + Size int // The size of the file, in bytes } -// FileSend is a public struct which represents a file to be transferred -// { -// "Name":"testfile.txt", // File name -// "Type":"text file", // File type -// "Preview":"aXQncyBtZSBhIHByZXZpZXc=", // Preview of contents -// "Contents":"VGhpcyBpcyB0aGUgZnVsbCBjb250ZW50cyBvZiB0aGUgZmlsZSBpbiBieXRlcw==" // Full contents of the file -// } +// FileSend is a public struct that contains the file contents and its name, +// type, and preview. +// { +// "Name":"testfile.txt", +// "Type":"text file", +// "Preview":"aXQncyBtZSBhIHByZXZpZXc=", +// "Contents":"VGhpcyBpcyB0aGUgZnVsbCBjb250ZW50cyBvZiB0aGUgZmlsZSBpbiBieXRlcw==" +// } type FileSend struct { - Name string - Type string - Preview []byte - Contents []byte + Name string // Name of the file + Type string // String that indicates type of file + Preview []byte // A preview of the file + Contents []byte // Full contents of the file } -// Progress is a public struct which represents the progress of an in-progress file transfer +// Progress is a public struct that represents the progress of an in-progress +// file transfer. +// // Example JSON: -// {"Completed":false, // Status of transfer (true if done) -// "Transmitted":128, // Bytes transferred so far -// "Total":2048, // Total size of file -// "Err":null // Error status (if any) -// } +// { +// "Completed":false, +// "Transmitted":128, +// "Total":2048, +// "Err":null +// } type Progress struct { - Completed bool - Transmitted int - Total int - Err error + Completed bool // Status of transfer (true if done) + Transmitted int // Number of file parts sent/received + Total int // Total number of file parts + Err error // Error status (if any) } -// ReceiveFileCallback is a bindings-layer interface which is called when a file is received -// Accepts the result of calling json.Marshal on a ReceivedFile struct +// ReceiveFileCallback is a bindings-layer interface that contains a callback +// that is called when a file is received. type ReceiveFileCallback interface { + // Callback is called when a new file transfer is received. + // + // Parameters: + // - payload - the JSON marshalled bytes of a ReceivedFile object. + // - err - any errors that occurred during reception Callback(payload []byte, err error) } -// FileTransferSentProgressCallback is a bindings-layer interface which is called with the progress of a sending file -// Accepts the result of calling json.Marshal on a Progress struct & a FilePartTracker interface +// FileTransferSentProgressCallback is a bindings-layer interface that contains +// a callback that is called when the sent progress updates. type FileTransferSentProgressCallback interface { + // Callback is called when a file part is sent or an error occurs. + // + // Parameters: + // - payload - the JSON marshalled bytes of a Progress object. + // - t - tracker that allows the lookup of the status of any file part + // - err - any errors that occurred during sending Callback(payload []byte, t *FilePartTracker, err error) } -// FileTransferReceiveProgressCallback is a bindings-layer interface which is called with the progress of a received file -// Accepts the result of calling json.Marshal on a Progress struct & a FilePartTracker interface +// FileTransferReceiveProgressCallback is a bindings-layer interface that is +// called with the progress of a received file. +// type FileTransferReceiveProgressCallback interface { + // Callback is called when a file part is sent or an error occurs. + // + // Parameters: + // - payload - the JSON marshalled bytes of a Progress object. + // - t - tracker that allows the lookup of the status of any file part + // - err - any errors that occurred during sending Callback(payload []byte, t *FilePartTracker, err error) } -/* Main functions */ +//////////////////////////////////////////////////////////////////////////////// +// Main functions // +//////////////////////////////////////////////////////////////////////////////// -// InitFileTransfer creates a bindings-level File Transfer manager -// Accepts e2e client ID and marshalled params JSON +// InitFileTransfer creates a bindings-level file transfer manager. +// +// Parameters: +// - e2eID - e2e client ID +// - paramsJSON - JSON marshalled fileTransfer.Params func InitFileTransfer(e2eID int, paramsJSON []byte) (*FileTransfer, error) { // Get bindings client from singleton @@ -126,16 +158,20 @@ func InitFileTransfer(e2eID int, paramsJSON []byte) (*FileTransfer, error) { return &FileTransfer{ft: m, e2eCl: e2eCl}, nil } -// Send is the bindings-level function for sending a File -// Accepts: -// FileSend JSON payload -// Marshalled recipient ID -// Marshalled e2e Params JSON -// Number of retries allowed -// Limit on duration between retries -// FileTransferSentProgressCallback interface +// Send is the bindings-level function for sending a file. +// +// Parameters: +// - payload - JSON marshalled FileSend +// - recipientID - marshalled recipient id.ID +// - paramsJSON - JSON marshalled e2e.Params +// - retry - number of retries allowed +// - callback - callback that reports file sending progress +// - period - duration to wait between progress callbacks triggering +// +// Returns: +// - []byte - unique file transfer ID func (f *FileTransfer) Send(payload, recipientID, paramsJSON []byte, retry float32, - period string, callback FileTransferSentProgressCallback) ([]byte, error) { + callback FileTransferSentProgressCallback, period string) ([]byte, error) { // Unmarshal recipient ID recipient, err := id.Unmarshal(recipientID) if err != nil { @@ -184,37 +220,49 @@ func (f *FileTransfer) Send(payload, recipientID, paramsJSON []byte, retry float return ftID.Bytes(), nil } -// Receive returns the full file on the completion of the transfer. -// It deletes internal references to the data and unregisters any attached -// progress callback. Returns an error if the transfer is not complete, the -// full file cannot be verified, or if the transfer cannot be found. +// Receive returns the full file on the completion of the transfer. It deletes +// internal references to the data and unregisters any attached progress +// callbacks. Returns an error if the transfer is not complete, the full file +// cannot be verified, or if the transfer cannot be found. // // Receive can only be called once the progress callback returns that the // file transfer is complete. +// +// Parameters: +// - tidBytes - file transfer ID func (f *FileTransfer) Receive(tidBytes []byte) ([]byte, error) { tid := ftCrypto.UnmarshalTransferID(tidBytes) return f.ft.Receive(&tid) } // CloseSend deletes a file from the internal storage once a transfer has -// completed or reached the retry limit. Returns an error if the transfer -// has not run out of retries. +// completed or reached the retry limit. Returns an error if the transfer has +// not run out of retries. +// +// This function should be called once a transfer completes or errors out (as +// reported by the progress callback). // -// This function should be called once a transfer completes or errors out -// (as reported by the progress callback). +// Parameters: +// - tidBytes - file transfer ID func (f *FileTransfer) CloseSend(tidBytes []byte) error { tid := ftCrypto.UnmarshalTransferID(tidBytes) return f.ft.CloseSend(&tid) } -/* Callback registration functions */ +//////////////////////////////////////////////////////////////////////////////// +// Callback Registration Functions // +//////////////////////////////////////////////////////////////////////////////// // RegisterSentProgressCallback allows for the registration of a callback to // track the progress of an individual sent file transfer. +// // SentProgressCallback is auto registered on Send; this function should be // called when resuming clients or registering extra callbacks. -// Accepts ID of the transfer, callback for transfer progress, -// and period between retries +// +// Parameters: +// - tidBytes - file transfer ID +// - callback - callback that reports file reception progress +// - period - duration to wait between progress callbacks triggering func (f *FileTransfer) RegisterSentProgressCallback(tidBytes []byte, callback FileTransferSentProgressCallback, period string) error { cb := func(completed bool, arrived, total uint16, @@ -237,12 +285,17 @@ func (f *FileTransfer) RegisterSentProgressCallback(tidBytes []byte, return f.ft.RegisterSentProgressCallback(&tid, cb, p) } -// RegisterReceivedProgressCallback allows for the registration of a -// callback to track the progress of an individual received file transfer. -// This should be done when a new transfer is received on the -// ReceiveCallback. -// Accepts ID of the transfer, callback for transfer progress and period between retries -func (f *FileTransfer) RegisterReceivedProgressCallback(tidBytes []byte, callback FileTransferReceiveProgressCallback, period string) error { +// RegisterReceivedProgressCallback allows for the registration of a callback to +// track the progress of an individual received file transfer. +// +// This should be done when a new transfer is received on the ReceiveCallback. +// +// Parameters: +// - tidBytes - file transfer ID +// - callback - callback that reports file reception progress +// - period - duration to wait between progress callbacks triggering +func (f *FileTransfer) RegisterReceivedProgressCallback(tidBytes []byte, + callback FileTransferReceiveProgressCallback, period string) error { cb := func(completed bool, received, total uint16, rt fileTransfer.ReceivedTransfer, t fileTransfer.FilePartTracker, err error) { prog := &Progress{ @@ -262,20 +315,26 @@ func (f *FileTransfer) RegisterReceivedProgressCallback(tidBytes []byte, callbac return f.ft.RegisterReceivedProgressCallback(&tid, cb, p) } -/* Utility Functions */ +//////////////////////////////////////////////////////////////////////////////// +// Utility Functions // +//////////////////////////////////////////////////////////////////////////////// +// MaxFileNameLen returns the max number of bytes allowed for a file name. func (f *FileTransfer) MaxFileNameLen() int { return f.ft.MaxFileNameLen() } +// MaxFileTypeLen returns the max number of bytes allowed for a file type. func (f *FileTransfer) MaxFileTypeLen() int { return f.ft.MaxFileTypeLen() } +// MaxFileSize returns the max number of bytes allowed for a file. func (f *FileTransfer) MaxFileSize() int { return f.ft.MaxFileSize() } +// MaxPreviewSize returns the max number of bytes allowed for a file preview. func (f *FileTransfer) MaxPreviewSize() int { return f.ft.MaxPreviewSize() } @@ -284,17 +343,18 @@ func (f *FileTransfer) MaxPreviewSize() int { // File Part Tracker // //////////////////////////////////////////////////////////////////////////////// -// FilePartTracker contains the interfaces.FilePartTracker. +// FilePartTracker contains the fileTransfer.FilePartTracker. type FilePartTracker struct { m fileTransfer.FilePartTracker } // GetPartStatus returns the status of the file part with the given part number. +// // The possible values for the status are: -// 0 = unsent -// 1 = sent (sender has sent a part, but it has not arrived) -// 2 = arrived (sender has sent a part, and it has arrived) -// 3 = received (receiver has received a part) +// - 0 < Part does not exist +// - 0 = unsent +// - 1 = arrived (sender has sent a part, and it has arrived) +// - 2 = received (receiver has received a part) func (fpt FilePartTracker) GetPartStatus(partNum int) int { return int(fpt.m.GetPartStatus(uint16(partNum))) } @@ -308,13 +368,16 @@ func (fpt FilePartTracker) GetNumParts() int { // Event Reporter // //////////////////////////////////////////////////////////////////////////////// -// EventReport is a public struct which represents the contents of an event report +// EventReport is a public struct which represents the contents of an event +// report. +// // Example JSON: -// {"Priority":1, -// "Category":"Test Events", -// "EventType":"Ping", -// "Details":"This is an example of an event report" -// } +// { +// "Priority":1, +// "Category":"Test Events", +// "EventType":"Ping", +// "Details":"This is an example of an event report" +// } type EventReport struct { Priority int Category string @@ -322,19 +385,22 @@ type EventReport struct { Details string } -// ReporterFunc is a bindings-layer interface which receives info from the Event Manager -// Accepts result of json.Marshal on an EventReport object +// ReporterFunc is a bindings-layer interface that receives info from the Event +// Manager. +// +// Parameters: +// - payload - JSON marshalled EventReport object type ReporterFunc interface { Report(payload []byte, err error) } -// reporter is the internal struct to match the event.Reporter interface +// reporter is the internal struct to match the event.Reporter interface. type reporter struct { r ReporterFunc } -// Report matches the event.Reporter interface, wraps the info in an EventReport struct -// and passes the marshalled struct to the internal callback +// Report matches the event.Reporter interface, wraps the info in an EventReport +// struct, and passes the marshalled struct to the internal callback. func (r *reporter) Report(priority int, category, evtType, details string) { rep := &EventReport{ Priority: priority, diff --git a/bindings/follow.go b/bindings/follow.go index 874882c813bc478711786e87fdff380935020462..d90dfc8001492c1c02c9870bb3985065d9d0b599 100644 --- a/bindings/follow.go +++ b/bindings/follow.go @@ -15,42 +15,48 @@ import ( "gitlab.com/xx_network/primitives/netTime" ) -// StartNetworkFollower kicks off the tracking of the network. It starts -// long running network client threads and returns an object for checking -// state and stopping those threads. -// Call this when returning from sleep and close when going back to -// sleep. +// StartNetworkFollower kicks off the tracking of the network. It starts long- +// running network client threads and returns an object for checking state and +// stopping those threads. +// +// Call this when returning from sleep and close when going back to sleep. +// // These threads may become a significant drain on battery when offline, ensure -// they are stopped if there is no internet access +// they are stopped if there is no internet access. +// // Threads Started: // - Network Follower (/network/follow.go) -// tracks the network events and hands them off to workers for handling +// tracks the network events and hands them off to workers for handling. // - Historical Round Retrieval (/network/rounds/historical.go) -// Retrieves data about rounds which are too old to be stored by the client +// retrieves data about rounds that are too old to be stored by the client. // - Message Retrieval Worker Group (/network/rounds/retrieve.go) -// Requests all messages in a given round from the gateway of the last nodes +// requests all messages in a given round from the gateway of the last +// nodes. // - Message Handling Worker Group (/network/message/handle.go) -// Decrypts and partitions messages when signals via the Switchboard -// - health Tracker (/network/health) -// Via the network instance tracks the state of the network +// decrypts and partitions messages when signals via the Switchboard. +// - Health Tracker (/network/health), +// via the network instance, tracks the state of the network. // - Garbled Messages (/network/message/garbled.go) -// Can be signaled to check all recent messages which could be be decoded -// Uses a message store on disk for persistence +// can be signaled to check all recent messages that could be decoded. It +// uses a message store on disk for persistence. // - Critical Messages (/network/message/critical.go) -// Ensures all protocol layer mandatory messages are sent -// Uses a message store on disk for persistence +// ensures all protocol layer mandatory messages are sent. It uses a +// message store on disk for persistence. // - KeyExchange Trigger (/keyExchange/trigger.go) -// Responds to sent rekeys and executes them +// responds to sent rekeys and executes them. // - KeyExchange Confirm (/keyExchange/confirm.go) -// Responds to confirmations of successful rekey operations +// responds to confirmations of successful rekey operations. +// - Auth Callback (/auth/callback.go) +// handles both auth confirm and requests. func (c *Cmix) StartNetworkFollower(timeoutMS int) error { timeout := time.Duration(timeoutMS) * time.Millisecond return c.api.StartNetworkFollower(timeout) } -// StopNetworkFollower stops the network follower if it is running. -// It returns errors if the Follower is in the wrong status to stop or if it -// fails to stop it. +// StopNetworkFollower stops the network follower if it is running. It returns +// an error if the follower is in the wrong state to stop or if it fails to stop +// it. +// // if the network follower is running and this fails, the client object will // most likely be in an unrecoverable state and need to be trashed. func (c *Cmix) StopNetworkFollower() error { @@ -61,8 +67,8 @@ func (c *Cmix) StopNetworkFollower() error { return nil } -// WaitForNewtwork will block until either the network is healthy or the -// passed timeout. It will return true if the network is healthy +// WaitForNetwork will block until either the network is healthy or the passed +// timeout is reached. It will return true if the network is healthy. func (c *Cmix) WaitForNetwork(timeoutMS int) bool { start := netTime.Now() timeout := time.Duration(timeoutMS) * time.Millisecond @@ -75,44 +81,44 @@ func (c *Cmix) WaitForNetwork(timeoutMS int) bool { return false } -// Gets the state of the network follower. Returns: -// Stopped - 0 -// Starting - 1000 -// Running - 2000 -// Stopping - 3000 +// NetworkFollowerStatus gets the state of the network follower. It returns a +// status with the following values: +// Stopped - 0 +// Running - 2000 +// Stopping - 3000 func (c *Cmix) NetworkFollowerStatus() int { return int(c.api.NetworkFollowerStatus()) } -// HasRunningProcessies checks if any background threads are running. -// returns true if none are running. This is meant to be -// used when NetworkFollowerStatus() returns Stopping. -// Due to the handling of comms on iOS, where the OS can -// block indefiently, it may not enter the stopped -// state apropreatly. This can be used instead. +// HasRunningProcessies checks if any background threads are running and returns +// true if one or more are. +// +// This is meant to be used when NetworkFollowerStatus returns xxdk.Stopping. +// Due to the handling of comms on iOS, where the OS can block indefinitely, it +// may not enter the stopped state appropriately. This can be used instead. func (c *Cmix) HasRunningProcessies() bool { return c.api.HasRunningProcessies() } // IsHealthy returns true if the network is read to be in a healthy state where -// messages can be sent +// messages can be sent. func (c *Cmix) IsHealthy() bool { return c.api.GetCmix().IsHealthy() } -// A callback when which is used to receive notification if network health -// changes +// NetworkHealthCallback contains a callback that is used to receive +// notification if network health changes. type NetworkHealthCallback interface { Callback(bool) } -// AddHealthCallback registers the network health callback to be called -// any time the network health changes. Returns a unique ID that can be used to -// unregister the network health callback. +// AddHealthCallback adds a callback that gets called whenever the network +// health changes. Returns a registration ID that can be used to unregister. func (c *Cmix) AddHealthCallback(nhc NetworkHealthCallback) int64 { return int64(c.api.GetCmix().AddHealthCallback(nhc.Callback)) } +// RemoveHealthCallback removes a health callback using its registration ID. func (c *Cmix) RemoveHealthCallback(funcID int64) { c.api.GetCmix().RemoveHealthCallback(uint64(funcID)) } @@ -122,7 +128,8 @@ type ClientError interface { } // RegisterClientErrorCallback registers the callback to handle errors from the -// long running threads controlled by StartNetworkFollower and StopNetworkFollower +// long-running threads controlled by StartNetworkFollower and +// StopNetworkFollower. func (c *Cmix) RegisterClientErrorCallback(clientError ClientError) { errChan := c.api.GetErrorsChannel() go func() { diff --git a/bindings/identity.go b/bindings/identity.go index c3e470df403bcd8b838d1f2240068f8afba4261f..6ffd270664d9b16db77a2bbb3d21970379b4991c 100644 --- a/bindings/identity.go +++ b/bindings/identity.go @@ -15,24 +15,24 @@ import ( "gitlab.com/elixxir/primitives/fact" ) -// ReceptionIdentity struct -// Example marshalled ReceptionIdentity: -// {"ID":"emV6aW1hAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD", // User ID (base64) -// // RSA Private key (PEM format) -// "RSAPrivatePem":"LS0tLS1CRUdJTiBSU0EgUFJJVkFURSBLRVktLS0tLQpNSUlFcFFJQkFBS0NBUUVBNU15dTdhYjBJOS9UL1BFUUxtd2x3ejZHV3FjMUNYemVIVXhoVEc4bmg1WWRWSXMxCmJ2THpBVjNOMDJxdXN6K2s4TVFEWjBtejMzdkswUmhPczZIY0NUSFdzTEpXRkE5WWpzWWlCRi9qTDd1bmd1ckIKL2tvK1JJSnNrWGFWaEZaazRGdERoRXhTNWY4RnR0Qmk1NmNLZmdJQlVKT3ozZi9qQllTMkxzMlJ6cWV5YXM3SApjV2RaME9TclBTT3BiYlViU1FPbS9LWnlweGZHU21yZ2oxRUZuU1dZZ2xGZTdUOTRPbHF5MG14QTV5clVXbHorCk9sK3hHbXpCNUp4WUFSMU9oMFQrQTk4RWMrTUZHNm43L1MraDdzRDgybGRnVnJmbStFTzRCdmFKeTRESGZGMWgKNnp6QnVnY25NUVFGc0dLeDFYWC9COTVMdUpPVjdyeXlDbzZGbHdJREFRQUJBb0lCQVFDaUh6OGNlcDZvQk9RTAphUzBVRitHeU5VMnlVcVRNTWtTWThoUkh1c09CMmFheXoybHZVb3RLUHBPbjZRSWRWVTJrcE4vY2dtY0lSb2x5CkhBMDRUOHJBWVNaRlVqaVlRajkzKzRFREpJYXd2Z0YyVEs1bFoyb3oxVTdreStncU82V0RMR2Z0Q0wvODVQWEIKa210aXhnUXpRV3g1RWcvemtHdm03eURBalQxeDloNytsRjJwNFlBam5kT2xTS0dmQjFZeTR1RXBQd0kwc1lWdgpKQWc0MEFxbllZUmt4emJPbmQxWGNjdEJFN2Z1VDdrWXhoeSs3WXYrUTJwVy9BYmh6NGlHOEY1MW9GMGZwV0czCmlISDhsVXZFTkp2SUZEVHZ0UEpESlFZalBRN3lUbGlGZUdrMXZUQkcyQkpQNExzVzhpbDZOeUFuRktaY1hOQ24KeHVCendiSlJBb0dCQVBUK0dGTVJGRHRHZVl6NmwzZmg3UjJ0MlhrMysvUmpvR3BDUWREWDhYNERqR1pVd1RGVQpOS2tQTTNjS29ia2RBYlBDb3FpL0tOOVBibk9QVlZ3R3JkSE9vSnNibFVHYmJGamFTUzJQMFZnNUVhTC9rT2dUCmxMMUdoVFpIUWk1VUlMM0p4M1Z3T0ZRQ3RQOU1UQlQ0UEQvcEFLbDg3VTJXN3JTY1dGV1ZGbFNkQW9HQkFPOFUKVmhHWkRpVGFKTWVtSGZIdVYrNmtzaUlsam9aUVVzeGpmTGNMZ2NjV2RmTHBqS0ZWTzJNN3NqcEJEZ0w4NmFnegorVk14ZkQzZ1l0SmNWN01aMVcwNlZ6TlNVTHh3a1dRY1hXUWdDaXc5elpyYlhCUmZRNUVjMFBlblVoWWVwVzF5CkpkTC8rSlpQeDJxSzVrQytiWU5EdmxlNWdpcjlDSGVzTlR5enVyckRBb0dCQUl0cTJnN1RaazhCSVFUUVNrZ24Kb3BkRUtzRW4wZExXcXlBdENtVTlyaWpHL2l2eHlXczMveXZDQWNpWm5VVEp0QUZISHVlbXVTeXplQ2g5QmRkegoyWkRPNUdqQVBxVHlQS3NudFlNZkY4UDczZ1NES1VSWWVFbHFDejdET0c5QzRzcitPK3FoN1B3cCtqUmFoK1ZiCkNuWllNMDlBVDQ3YStJYUJmbWRkaXpLbEFvR0JBSmo1dkRDNmJIQnNISWlhNUNJL1RZaG5YWXUzMkVCYytQM0sKMHF3VThzOCtzZTNpUHBla2Y4RjVHd3RuUU4zc2tsMk1GQWFGYldmeVFZazBpUEVTb0p1cGJzNXA1enNNRkJ1bwpncUZrVnQ0RUZhRDJweTVwM2tQbDJsZjhlZXVwWkZScGE0WmRQdVIrMjZ4eWYrNEJhdlZJeld3NFNPL1V4Q3crCnhqbTNEczRkQW9HQWREL0VOa1BjU004c1BCM3JSWW9MQ2twcUV2U0MzbVZSbjNJd3c1WFAwcDRRVndhRmR1ckMKYUhtSE1EekNrNEUvb0haQVhFdGZ2S2tRaUI4MXVYM2c1aVo4amdYUVhXUHRteTVIcVVhcWJYUTlENkxWc3B0egpKL3R4SWJLMXp5c1o2bk9IY1VoUUwyVVF6SlBBRThZNDdjYzVzTThEN3kwZjJ0QURTQUZNMmN3PQotLS0tLUVORCBSU0EgUFJJVkFURSBLRVktLS0tLQ==", -// // Salt for identity (base64) -// "Salt":"4kk02v0NIcGtlobZ/xkxqWz8uH/ams/gjvQm14QT0dI=", -// // DH Private key -// "DHKeyPrivate":"eyJWYWx1ZSI6NDU2MDgzOTEzMjA0OTIyODA5Njg2MDI3MzQ0MzM3OTA0MzAyODYwMjM2NDk2NDM5NDI4NTcxMTMwNDMzOTQwMzgyMTIyMjY4OTQzNTMyMjIyMzc1MTkzNTEzMjU4MjA4MDA0NTczMDY4MjEwNzg2NDI5NjA1MjA0OTA3MjI2ODI5OTc3NTczMDkxODY0NTY3NDExMDExNjQxNCwiRmluZ2VycHJpbnQiOjE2ODAxNTQxNTExMjMzMDk4MzYzfQ==" -// } +// ReceptionIdentity struct. +// +// JSON example: +// { +// "ID":"emV6aW1hAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD", +// "RSAPrivatePem":"LS0tLS1CRUdJTiBSU0EgUFJJVkFURSBLRVktLS0tLQpNSUlFcFFJQkFBS0NBUUVBNU15dTdhYjBJOS9UL1BFUUxtd2x3ejZHV3FjMUNYemVIVXhoVEc4bmg1WWRWSXMxCmJ2THpBVjNOMDJxdXN6K2s4TVFEWjBtejMzdkswUmhPczZIY0NUSFdzTEpXRkE5WWpzWWlCRi9qTDd1bmd1ckIKL2tvK1JJSnNrWGFWaEZaazRGdERoRXhTNWY4RnR0Qmk1NmNLZmdJQlVKT3ozZi9qQllTMkxzMlJ6cWV5YXM3SApjV2RaME9TclBTT3BiYlViU1FPbS9LWnlweGZHU21yZ2oxRUZuU1dZZ2xGZTdUOTRPbHF5MG14QTV5clVXbHorCk9sK3hHbXpCNUp4WUFSMU9oMFQrQTk4RWMrTUZHNm43L1MraDdzRDgybGRnVnJmbStFTzRCdmFKeTRESGZGMWgKNnp6QnVnY25NUVFGc0dLeDFYWC9COTVMdUpPVjdyeXlDbzZGbHdJREFRQUJBb0lCQVFDaUh6OGNlcDZvQk9RTAphUzBVRitHeU5VMnlVcVRNTWtTWThoUkh1c09CMmFheXoybHZVb3RLUHBPbjZRSWRWVTJrcE4vY2dtY0lSb2x5CkhBMDRUOHJBWVNaRlVqaVlRajkzKzRFREpJYXd2Z0YyVEs1bFoyb3oxVTdreStncU82V0RMR2Z0Q0wvODVQWEIKa210aXhnUXpRV3g1RWcvemtHdm03eURBalQxeDloNytsRjJwNFlBam5kT2xTS0dmQjFZeTR1RXBQd0kwc1lWdgpKQWc0MEFxbllZUmt4emJPbmQxWGNjdEJFN2Z1VDdrWXhoeSs3WXYrUTJwVy9BYmh6NGlHOEY1MW9GMGZwV0czCmlISDhsVXZFTkp2SUZEVHZ0UEpESlFZalBRN3lUbGlGZUdrMXZUQkcyQkpQNExzVzhpbDZOeUFuRktaY1hOQ24KeHVCendiSlJBb0dCQVBUK0dGTVJGRHRHZVl6NmwzZmg3UjJ0MlhrMysvUmpvR3BDUWREWDhYNERqR1pVd1RGVQpOS2tQTTNjS29ia2RBYlBDb3FpL0tOOVBibk9QVlZ3R3JkSE9vSnNibFVHYmJGamFTUzJQMFZnNUVhTC9rT2dUCmxMMUdoVFpIUWk1VUlMM0p4M1Z3T0ZRQ3RQOU1UQlQ0UEQvcEFLbDg3VTJXN3JTY1dGV1ZGbFNkQW9HQkFPOFUKVmhHWkRpVGFKTWVtSGZIdVYrNmtzaUlsam9aUVVzeGpmTGNMZ2NjV2RmTHBqS0ZWTzJNN3NqcEJEZ0w4NmFnegorVk14ZkQzZ1l0SmNWN01aMVcwNlZ6TlNVTHh3a1dRY1hXUWdDaXc5elpyYlhCUmZRNUVjMFBlblVoWWVwVzF5CkpkTC8rSlpQeDJxSzVrQytiWU5EdmxlNWdpcjlDSGVzTlR5enVyckRBb0dCQUl0cTJnN1RaazhCSVFUUVNrZ24Kb3BkRUtzRW4wZExXcXlBdENtVTlyaWpHL2l2eHlXczMveXZDQWNpWm5VVEp0QUZISHVlbXVTeXplQ2g5QmRkegoyWkRPNUdqQVBxVHlQS3NudFlNZkY4UDczZ1NES1VSWWVFbHFDejdET0c5QzRzcitPK3FoN1B3cCtqUmFoK1ZiCkNuWllNMDlBVDQ3YStJYUJmbWRkaXpLbEFvR0JBSmo1dkRDNmJIQnNISWlhNUNJL1RZaG5YWXUzMkVCYytQM0sKMHF3VThzOCtzZTNpUHBla2Y4RjVHd3RuUU4zc2tsMk1GQWFGYldmeVFZazBpUEVTb0p1cGJzNXA1enNNRkJ1bwpncUZrVnQ0RUZhRDJweTVwM2tQbDJsZjhlZXVwWkZScGE0WmRQdVIrMjZ4eWYrNEJhdlZJeld3NFNPL1V4Q3crCnhqbTNEczRkQW9HQWREL0VOa1BjU004c1BCM3JSWW9MQ2twcUV2U0MzbVZSbjNJd3c1WFAwcDRRVndhRmR1ckMKYUhtSE1EekNrNEUvb0haQVhFdGZ2S2tRaUI4MXVYM2c1aVo4amdYUVhXUHRteTVIcVVhcWJYUTlENkxWc3B0egpKL3R4SWJLMXp5c1o2bk9IY1VoUUwyVVF6SlBBRThZNDdjYzVzTThEN3kwZjJ0QURTQUZNMmN3PQotLS0tLUVORCBSU0EgUFJJVkFURSBLRVktLS0tLQ==", +// "Salt":"4kk02v0NIcGtlobZ/xkxqWz8uH/ams/gjvQm14QT0dI=", +// "DHKeyPrivate":"eyJWYWx1ZSI6NDU2MDgzOTEzMjA0OTIyODA5Njg2MDI3MzQ0MzM3OTA0MzAyODYwMjM2NDk2NDM5NDI4NTcxMTMwNDMzOTQwMzgyMTIyMjY4OTQzNTMyMjIyMzc1MTkzNTEzMjU4MjA4MDA0NTczMDY4MjEwNzg2NDI5NjA1MjA0OTA3MjI2ODI5OTc3NTczMDkxODY0NTY3NDExMDExNjQxNCwiRmluZ2VycHJpbnQiOjE2ODAxNTQxNTExMjMzMDk4MzYzfQ==" +// } type ReceptionIdentity struct { - ID []byte - RSAPrivatePem []byte - Salt []byte - DHKeyPrivate []byte + ID []byte // User ID (base64) + RSAPrivatePem []byte // RSA Private key (PEM format) + Salt []byte // Salt for identity (base64) + DHKeyPrivate []byte // DH Private key } -// MakeReceptionIdentity generates a new cryptographic identity for receiving messages +// MakeReceptionIdentity generates a new cryptographic identity for receiving +// messages. func (c *Cmix) MakeReceptionIdentity() ([]byte, error) { ident, err := xxdk.MakeReceptionIdentity(c.api) if err != nil { @@ -42,7 +42,8 @@ func (c *Cmix) MakeReceptionIdentity() ([]byte, error) { return ident.Marshal() } -// MakeLegacyReceptionIdentity generates the legacy identity for receiving messages +// MakeLegacyReceptionIdentity generates the legacy identity for receiving +// messages. func (c *Cmix) MakeLegacyReceptionIdentity() ([]byte, error) { ident, err := xxdk.MakeLegacyReceptionIdentity(c.api) if err != nil { @@ -52,7 +53,8 @@ func (c *Cmix) MakeLegacyReceptionIdentity() ([]byte, error) { return ident.Marshal() } -// GetIDFromContact accepts a marshalled contact.Contact object & returns a marshalled id.ID object +// GetIDFromContact accepts a marshalled contact.Contact object and returns a +// marshalled id.ID object. func GetIDFromContact(marshaled []byte) ([]byte, error) { cnt, err := contact.Unmarshal(marshaled) if err != nil { @@ -62,7 +64,8 @@ func GetIDFromContact(marshaled []byte) ([]byte, error) { return cnt.ID.Marshal(), nil } -// GetPubkeyFromContact accepts a marshalled contact.Contact object & returns a json marshalled large.Int DhPubKey +// GetPubkeyFromContact accepts a marshalled contact.Contact object and returns +// a JSON marshalled large.Int DH public key. func GetPubkeyFromContact(marshaled []byte) ([]byte, error) { cnt, err := contact.Unmarshal(marshaled) if err != nil { @@ -72,17 +75,24 @@ func GetPubkeyFromContact(marshaled []byte) ([]byte, error) { return json.Marshal(cnt.DhPubKey) } -// Fact is an internal fact type for use in the bindings layer -// example marshalled Fact: -// {"Fact":"Zezima","Type":0} +// Fact is an internal fact type for use in the bindings layer. +// +// JSON example: +// { +// "Fact": "Zezima", +// "Type": 0 +// } type Fact struct { Fact string Type int } // SetFactsOnContact replaces the facts on the contact with the passed in facts -// pass in empty facts in order to clear the facts -// Accepts a marshalled contact.Contact object & a marshalled list of Fact objects +// pass in empty facts in order to clear the facts. +// +// Parameters: +// - marshaled - JSON marshalled contact.Contact object +// - facts - JSON marshalled Fact object. func SetFactsOnContact(marshaled []byte, facts []byte) ([]byte, error) { cnt, err := contact.Unmarshal(marshaled) if err != nil { @@ -107,7 +117,8 @@ func SetFactsOnContact(marshaled []byte, facts []byte) ([]byte, error) { return cnt.Marshal(), nil } -// GetFactsFromContact accepts a marshalled contact.Contact object, returning its marshalled list of Fact objects +// GetFactsFromContact accepts a marshalled contact.Contact object and returns +// its marshalled list of Fact objects. func GetFactsFromContact(marshaled []byte) ([]byte, error) { cnt, err := contact.Unmarshal(marshaled) if err != nil { @@ -129,9 +140,10 @@ func GetFactsFromContact(marshaled []byte) ([]byte, error) { return factsListMarshaled, nil } -// StoreReceptionIdentity stores the given identity in Cmix storage with the given key -// This is the ideal way to securely store identities, as the caller of this function -// is only required to store the given key separately rather than the keying material +// StoreReceptionIdentity stores the given identity in Cmix storage with the +// given key. This is the ideal way to securely store identities, as the caller +// of this function is only required to store the given key separately rather +// than the keying material. func StoreReceptionIdentity(key string, identity []byte, cmixId int) error { cmix, err := cmixTrackerSingleton.get(cmixId) if err != nil { @@ -144,7 +156,8 @@ func StoreReceptionIdentity(key string, identity []byte, cmixId int) error { return xxdk.StoreReceptionIdentity(key, receptionIdentity, cmix.api) } -// LoadReceptionIdentity loads the given identity in Cmix storage with the given key +// LoadReceptionIdentity loads the given identity in Cmix storage with the given +// key. func LoadReceptionIdentity(key string, cmixId int) ([]byte, error) { cmix, err := cmixTrackerSingleton.get(cmixId) if err != nil { diff --git a/bindings/listener.go b/bindings/listener.go index 5d4e5608d212e8b596468cd8887bfb86560bf4ff..c19bca2fd3d1dfa72608f51b60c474f64cfa7b24 100644 --- a/bindings/listener.go +++ b/bindings/listener.go @@ -14,34 +14,42 @@ import ( "gitlab.com/elixxir/client/e2e/receive" ) -// Listener provides a callback to hear a message -// An object implementing this interface can be called back when the client -// gets a message of the type that the registerer specified at registration -// time. +// Listener provides a callback to hear a message. +// +// An object implementing this interface can be called back when the client gets +// a message of the type that the registerer specified at registration time. type Listener interface { - // Hear is called to receive a message in the UI - // Accepts a marshalled Message object + // Hear is called to receive a message in the UI. + // + // Parameters: + // - item - JSON marshalled Message object Hear(item []byte) - // Name returns a name, used for debugging + + // Name returns a name; used for debugging. Name() string } -// listener is an object internal to bindings which matches the interface expected by RegisterListener -// it wraps the Listener type, which is usable by the bindings layer +// listener is an object internal to bindings which matches the interface +// expected by RegisterListener. +// +// It wraps the Listener type, which is usable by the bindings layer. type listener struct { l Listener } -// Message is the bindings representation of a receive.Message -// Example Message format: -// {"MessageType":1, -// "ID":"EB/70R5HYEw5htZ4Hg9ondrn3+cAc/lH2G0mjQMja3w=", -// "Payload":"7TzZKgNphT5UooNM7mDSwtVcIs8AIu4vMKm4ld6GSR8YX5GrHirixUBAejmsgdroRJyo06TkIVef7UM9FN8YfQ==", -// "Sender":"emV6aW1hAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD", -// "RecipientID":"amFrZXh4MzYwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD", -// "EphemeralID":17,"Timestamp":1653580439357351000, -// "Encrypted":false, -// "RoundId":19} +// Message is the bindings' representation of a receive.Message. +// +// JSON example: +// { +// "MessageType":1, +// "ID":"EB/70R5HYEw5htZ4Hg9ondrn3+cAc/lH2G0mjQMja3w=", +// "Payload":"7TzZKgNphT5UooNM7mDSwtVcIs8AIu4vMKm4ld6GSR8YX5GrHirixUBAejmsgdroRJyo06TkIVef7UM9FN8YfQ==", +// "Sender":"emV6aW1hAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD", +// "RecipientID":"amFrZXh4MzYwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD", +// "EphemeralID":17,"Timestamp":1653580439357351000, +// "Encrypted":false, +// "RoundId":19 +// } type Message struct { MessageType int ID []byte @@ -56,7 +64,7 @@ type Message struct { RoundId int } -// Hear is called to receive a message in the UI +// Hear is called to receive a message in the UI. func (l listener) Hear(item receive.Message) { m := Message{ MessageType: int(item.MessageType), @@ -76,7 +84,7 @@ func (l listener) Hear(item receive.Message) { l.l.Hear(result) } -// Name used for debugging +// Name used for debugging. func (l listener) Name() string { return l.l.Name() } diff --git a/bindings/listener_test.go b/bindings/listener_test.go index 8336dd207f0a9232ec3daa650f8bcdd571358189..92276c186e1d30ac8d91785df3a1ab8839cf0746 100644 --- a/bindings/listener_test.go +++ b/bindings/listener_test.go @@ -20,9 +20,9 @@ import ( func TestMessage_Json(t *testing.T) { rng := csprng.NewSystemRNG() messageID := e2e.MessageID{} - rng.Read(messageID[:]) + _, _ = rng.Read(messageID[:]) payload := make([]byte, 64) - rng.Read(payload) + _, _ = rng.Read(payload) sender := id.NewIdFromString("zezima", id.User, t) receiver := id.NewIdFromString("jakexx360", id.User, t) m := Message{ diff --git a/bindings/logging.go b/bindings/logging.go index 5fa5fe0e196807f9baa52dfa9969f6331a85ec5a..6783d4b546f293862863110a85b16791dbf88baa 100644 --- a/bindings/logging.go +++ b/bindings/logging.go @@ -18,16 +18,20 @@ import ( "google.golang.org/grpc/grpclog" ) -// sets level of logging. All logs the set level and above will be displayed -// options are: -// TRACE - 0 -// DEBUG - 1 -// INFO - 2 -// WARN - 3 -// ERROR - 4 -// CRITICAL - 5 -// FATAL - 6 -// The default state without updates is: INFO +// LogLevel sets level of logging. All logs at the set level and below will be +// displayed (e.g., when log level is ERROR, only ERROR, CRITICAL, and FATAL +// messages will be printed). +// +// Log level options: +// TRACE - 0 +// DEBUG - 1 +// INFO - 2 +// WARN - 3 +// ERROR - 4 +// CRITICAL - 5 +// FATAL - 6 +// +// The default log level without updates is INFO. func LogLevel(level int) error { if level < 0 || level > 6 { return errors.New(fmt.Sprintf("log level is not valid: log level: %d", level)) @@ -62,12 +66,12 @@ type LogWriter interface { Log(string) } -//RegisterLogWriter registers a callback on which logs are written. +// RegisterLogWriter registers a callback on which logs are written. func RegisterLogWriter(writer LogWriter) { jww.SetLogOutput(&writerAdapter{lw: writer}) } -// EnableGrpcLogs sets GRPC trace logging +// EnableGrpcLogs sets GRPC trace logging. func EnableGrpcLogs(writer LogWriter) { logger := &writerAdapter{lw: writer} grpclog.SetLoggerV2(grpclog.NewLoggerV2WithVerbosity( diff --git a/bindings/ndf.go b/bindings/ndf.go index 4787544b6075a9ac835f92624c807130d1aa964a..eb6a5c87d7c33ee968c6d005cb10ab96e7026968 100644 --- a/bindings/ndf.go +++ b/bindings/ndf.go @@ -10,9 +10,9 @@ package bindings import "gitlab.com/elixxir/client/xxdk" // DownloadAndVerifySignedNdfWithUrl retrieves the NDF from a specified URL. -// The NDF is processed into a protobuf containing a signature which -// is verified using the cert string passed in. The NDF is returned as marshaled -// byte data which may be used to start a client. +// The NDF is processed into a protobuf containing a signature that is verified +// using the cert string passed in. The NDF is returned as marshaled byte data +// that may be used to start a client. func DownloadAndVerifySignedNdfWithUrl(url, cert string) ([]byte, error) { return xxdk.DownloadAndVerifySignedNdfWithUrl(url, cert) } diff --git a/bindings/params.go b/bindings/params.go index cc7883b30c673f6166eca4a1d865481a24554fe0..50da624ea6a944ae6fff08214aea2c44f17c58da 100644 --- a/bindings/params.go +++ b/bindings/params.go @@ -16,50 +16,50 @@ import ( "gitlab.com/elixxir/client/xxdk" ) -// GetDefaultCMixParams returns a JSON serialized object with all of the -// CMIX parameters and their default values. Call this function and modify -// the json to change CMIX settings. +// GetDefaultCMixParams returns a JSON serialized object with all of the cMix +// parameters and their default values. Call this function and modify the JSON +// to change cMix settings. func GetDefaultCMixParams() []byte { defaultParams := xxdk.GetDefaultCMixParams() data, err := defaultParams.Marshal() if err != nil { - jww.FATAL.Panicf("Unexpected error: %+v", err) + jww.FATAL.Panicf("Failed to JSON marshal cMix params: %+v", err) } return data } -// GetDefaultE2EParams returns a JSON serialized object with all of the -// E2E parameters and their default values. Call this function and modify -// the json to change E2E settings. +// GetDefaultE2EParams returns a JSON serialized object with all of the E2E +// parameters and their default values. Call this function and modify the JSON +// to change E2E settings. func GetDefaultE2EParams() []byte { defaultParams := xxdk.GetDefaultE2EParams() data, err := defaultParams.Marshal() if err != nil { - jww.FATAL.Panicf("Unexpected error: %+v", err) + jww.FATAL.Panicf("Failed to JSON marshal E2E params: %+v", err) } return data } // GetDefaultFileTransferParams returns a JSON serialized object with all the -// File transfer parameters and their default values. Call this function and modify -// the json to change file transfer settings. +// file transfer parameters and their default values. Call this function and +// modify the JSON to change file transfer settings. func GetDefaultFileTransferParams() []byte { defaultParams := fileTransfer.DefaultParams() data, err := defaultParams.MarshalJSON() if err != nil { - jww.FATAL.Panicf("Unexpected error: %+v", err) + jww.FATAL.Panicf("Failed to JSON marshal file transfer params: %+v", err) } return data } // GetDefaultSingleUseParams returns a JSON serialized object with all the -// single use parameters and their default values. Call this function and modify -// the json to change single use settings. +// single-use parameters and their default values. Call this function and modify +// the JSON to change single use settings. func GetDefaultSingleUseParams() []byte { defaultParams := single.GetDefaultRequestParams() data, err := defaultParams.MarshalJSON() if err != nil { - jww.FATAL.Panicf("Unexpected error: %+v", err) + jww.FATAL.Panicf("Failed to JSON marshal single-use params: %+v", err) } return data } diff --git a/bindings/restlike.go b/bindings/restlike.go index b1a6fbd2167b681c51c71841c32260e07c8e9de6..4c6653af495b0b019a5ef02160f80c1eb07ce286 100644 --- a/bindings/restlike.go +++ b/bindings/restlike.go @@ -15,14 +15,17 @@ import ( "gitlab.com/elixxir/client/restlike/connect" ) -// RestlikeMessage is the bindings representation of a restlike.Message -// Example marshalled RestlikeMessage: -//{"Version":1, -// "Headers":"Y29udGVudHM6YXBwbGljYXRpb24vanNvbg==", -// "Content":"VGhpcyBpcyBhIHJlc3RsaWtlIG1lc3NhZ2U=", -// "Method":2, -// "URI":"xx://CmixRestlike/rest", -// "Error":""} +// RestlikeMessage is the bindings' representation of a restlike.Message +// +// JSON example: +// { +// "Version":1, +// "Headers":"Y29udGVudHM6YXBwbGljYXRpb24vanNvbg==", +// "Content":"VGhpcyBpcyBhIHJlc3RsaWtlIG1lc3NhZ2U=", +// "Method":2, +// "URI":"xx://CmixRestlike/rest", +// "Error":"" +// } type RestlikeMessage struct { Version uint32 Headers []byte @@ -32,11 +35,18 @@ type RestlikeMessage struct { Error string } -// RestlikeRequest performs a normal restlike request -// request - marshalled RestlikeMessage -// Returns marshalled result RestlikeMessage -func RestlikeRequest(clientID, connectionID int, request, - e2eParamsJSON []byte) ([]byte, error) { +// RestlikeRequest performs a normal restlike request. +// +// Parameters: +// - clientID - ID of the cMix client in the tracker +// - connectionID - ID of the connection in the tracker +// - request - JSON marshalled RestlikeMessage +// - e2eParamsJSON - JSON marshalled xxdk.E2EParams +// +// Returns: +// - []byte - JSON marshalled RestlikeMessage +func RestlikeRequest( + clientID, connectionID int, request, e2eParamsJSON []byte) ([]byte, error) { if len(e2eParamsJSON) == 0 { jww.WARN.Printf("restlike params unspecified, using defaults") e2eParamsJSON = GetDefaultE2EParams() @@ -87,9 +97,16 @@ func RestlikeRequest(clientID, connectionID int, request, return json.Marshal(respMessage) } -// RestlikeRequestAuth performs an authenticated restlike request -// request - marshalled RestlikeMessage -// Returns marshalled result RestlikeMessage +// RestlikeRequestAuth performs an authenticated restlike request. +// +// Parameters: +// - clientID - ID of the cMix client in the tracker +// - authConnectionID - ID of the authenticated connection in the tracker +// - request - JSON marshalled RestlikeMessage +// - e2eParamsJSON - JSON marshalled xxdk.E2EParams +// +// Returns: +// - []byte - JSON marshalled RestlikeMessage func RestlikeRequestAuth(clientID int, authConnectionID int, request, e2eParamsJSON []byte) ([]byte, error) { if len(e2eParamsJSON) == 0 { @@ -122,10 +139,11 @@ func RestlikeRequestAuth(clientID int, authConnectionID int, request, E2eGrp: nil, } - result, err := c.Request(restlike.Method(msg.Method), restlike.URI(msg.URI), msg.Content, &restlike.Headers{ - Headers: msg.Headers, - Version: msg.Version, - }, params.Base) + result, err := c.Request(restlike.Method(msg.Method), restlike.URI(msg.URI), + msg.Content, &restlike.Headers{ + Headers: msg.Headers, + Version: msg.Version, + }, params.Base) if err != nil { return nil, err } diff --git a/bindings/restlikeSingle.go b/bindings/restlikeSingle.go index f6ddee5fcf2acafdfcd8f72aa80fc7916cafa5f9..85db774067cee1f2f9d76446df9c2157ed9f6fc8 100644 --- a/bindings/restlikeSingle.go +++ b/bindings/restlikeSingle.go @@ -15,15 +15,26 @@ import ( "gitlab.com/elixxir/crypto/contact" ) -// RestlikeCallback is the public function type bindings can use to make an asynchronous restlike request -// It accepts a json marshalled restlike.Message and an error (the results of calling json.Marshal on the message) +// RestlikeCallback is the public function type bindings can use to make an +// asynchronous restlike request. +// +// Parameters: +// - []byte - JSON marshalled restlike.Message +// - error - an error (the results of calling json.Marshal on the message) type RestlikeCallback interface { Callback([]byte, error) } -// RequestRestLike sends a restlike request to a given contact -// Accepts marshalled contact object as recipient, marshalled RestlikeMessage and params JSON -// Returns json marshalled restlike.Message & error +// RequestRestLike sends a restlike request to a given contact. +// +// Parameters: +// - e2eID - ID of the e2e client in the tracker +// - recipient - marshalled contact.Contact object +// - request - JSON marshalled RestlikeMessage +// - paramsJSON - JSON marshalled single.RequestParams +// +// Returns: +// - []byte - JSON marshalled restlike.Message func RequestRestLike(e2eID int, recipient, request, paramsJSON []byte) ([]byte, error) { c, err := e2eTrackerSingleton.get(e2eID) if err != nil { @@ -59,11 +70,18 @@ func RequestRestLike(e2eID int, recipient, request, paramsJSON []byte) ([]byte, return json.Marshal(resp) } -// AsyncRequestRestLike sends an asynchronous restlike request to a given contact -// Accepts e2e client ID, marshalled contact object as recipient, -// marshalled RestlikeMessage, marshalled Params json, and a RestlikeCallback +// AsyncRequestRestLike sends an asynchronous restlike request to a given +// contact. +// +// Parameters: +// - e2eID - ID of the e2e client in the tracker +// - recipient - marshalled contact.Contact object +// - request - JSON marshalled RestlikeMessage +// - paramsJSON - JSON marshalled single.RequestParams +// - cb - RestlikeCallback callback +// // Returns an error, and the RestlikeCallback will be called with the results -// of json marshalling the response when received +// of JSON marshalling the response when received. func AsyncRequestRestLike(e2eID int, recipient, request, paramsJSON []byte, cb RestlikeCallback) error { c, err := e2eTrackerSingleton.get(e2eID) if err != nil { @@ -92,8 +110,9 @@ func AsyncRequestRestLike(e2eID int, recipient, request, paramsJSON []byte, cb R return err } - return req.AsyncRequest(recipientContact, restlike.Method(message.Method), restlike.URI(message.URI), - message.Content, &restlike.Headers{ + return req.AsyncRequest( + recipientContact, restlike.Method(message.Method), + restlike.URI(message.URI), message.Content, &restlike.Headers{ Headers: message.Headers, Version: 0, }, rlcb, params) diff --git a/bindings/secrets.go b/bindings/secrets.go index 5bdeeed03c35cf6e0af99b8a64aaf54f213e8a23..6086282de043b535a769a6c5e5a5c788a156a081 100644 --- a/bindings/secrets.go +++ b/bindings/secrets.go @@ -12,13 +12,16 @@ import ( "gitlab.com/xx_network/crypto/csprng" ) -// GenerateSecret creates a secret password using a system-based -// pseudorandom number generator. It takes 1 parameter, `numBytes`, -// which should be set to 32, but can be set higher in certain cases. +// GenerateSecret creates a secret password using a system-based pseudorandom +// number generator. +// +// Parameters: +// - numBytes - The size of secret. It should be set to 32, but can be set +// higher in certain cases. func GenerateSecret(numBytes int) []byte { if numBytes < 32 { - jww.FATAL.Panicf("Secrets must have at least 32 bytes " + - "(256 bits) of entropy.") + jww.FATAL.Panic( + "Secrets must have at least 32 bytes (256 bits) of entropy.") } out := make([]byte, numBytes) diff --git a/bindings/single.go b/bindings/single.go index c54bfeecabcb762be47aed7c8f023da1b2a7a23f..ddc2c559f4865d6cac05554824cd2dc376de1b56 100644 --- a/bindings/single.go +++ b/bindings/single.go @@ -17,11 +17,24 @@ import ( "gitlab.com/xx_network/primitives/id" ) -/* PUBLIC WRAPPER METHODS */ +//////////////////////////////////////////////////////////////////////////////// +// Public Wrapper Methods // +//////////////////////////////////////////////////////////////////////////////// -// TransmitSingleUse accepts a marshalled recipient contact object, tag, payload, params JSON, SingleUseResponse callback func & a -// Client. Transmits payload to recipient via single use -func TransmitSingleUse(e2eID int, recipient []byte, tag string, payload, paramsJSON []byte, responseCB SingleUseResponse) ([]byte, error) { +// TransmitSingleUse transmits payload to recipient via single-use. +// +// Parameters: +// - e2eID - ID of the e2e client in the tracker +// - recipient - marshalled contact.Contact object +// - tag - identifies the single-use message +// - payload - message contents +// - paramsJSON - JSON marshalled single.RequestParams +// - responseCB - the callback that will be called when a response is received +// +// Returns: +// - []byte - JSON marshalled SingleUseSendReport +func TransmitSingleUse(e2eID int, recipient []byte, tag string, payload, + paramsJSON []byte, responseCB SingleUseResponse) ([]byte, error) { e2eCl, err := e2eTrackerSingleton.get(e2eID) if err != nil { return nil, err @@ -39,7 +52,9 @@ func TransmitSingleUse(e2eID int, recipient []byte, tag string, payload, paramsJ return nil, err } - rids, eid, err := single.TransmitRequest(recipientContact, tag, payload, rcb, params, e2eCl.api.GetCmix(), e2eCl.api.GetRng().GetStream(), e2eCl.api.GetStorage().GetE2EGroup()) + rids, eid, err := single.TransmitRequest(recipientContact, tag, payload, + rcb, params, e2eCl.api.GetCmix(), e2eCl.api.GetRng().GetStream(), + e2eCl.api.GetStorage().GetE2EGroup()) if err != nil { return nil, err @@ -52,7 +67,16 @@ func TransmitSingleUse(e2eID int, recipient []byte, tag string, payload, paramsJ return json.Marshal(sr) } -// Listen starts a single use listener on a given tag using the passed in client and SingleUseCallback func +// Listen starts a single-use listener on a given tag using the passed in client +// and SingleUseCallback func. +// +// Parameters: +// - e2eID - ID of the e2e client in the tracker +// - tag - identifies the single-use message +// - cb - the callback that will be called when a response is received +// +// Returns: +// - StopFunc - a function used to stop the listener func Listen(e2eID int, tag string, cb SingleUseCallback) (StopFunc, error) { e2eCl, err := e2eTrackerSingleton.get(e2eID) if err != nil { @@ -64,33 +88,40 @@ func Listen(e2eID int, tag string, cb SingleUseCallback) (StopFunc, error) { if err != nil { return nil, err } - l := single.Listen(tag, e2eCl.api.GetReceptionIdentity().ID, dhpk, e2eCl.api.GetCmix(), e2eCl.api.GetStorage().GetE2EGroup(), listener) + l := single.Listen(tag, e2eCl.api.GetReceptionIdentity().ID, dhpk, + e2eCl.api.GetCmix(), e2eCl.api.GetStorage().GetE2EGroup(), listener) return l.Stop, nil } // JSON Types -// SingleUseSendReport is the bindings struct used to represent information returned by single.TransmitRequest +// SingleUseSendReport is the bindings-layer struct used to represent +// information returned by single.TransmitRequest. // -// Example json marshalled struct: -// {"Rounds":[1,5,9], -// "EphID":{"EphId":[0,0,0,0,0,0,3,89], -// "Source":"emV6aW1hAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD"}} +// JSON example: +// { +// "Rounds":[1,5,9], +// "EphID":{"EphId":[0,0,0,0,0,0,3,89], +// "Source":"emV6aW1hAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD"} +// } type SingleUseSendReport struct { RoundsList ReceptionID []byte EphID int64 } -// SingleUseResponseReport is the bindings struct used to represent information passed -// to the single.Response callback interface in response to single.TransmitRequest +// SingleUseResponseReport is the bindings-layer struct used to represent +// information passed to the single.Response callback interface in response to +// single.TransmitRequest. // -// Example json marshalled struct: -// {"Rounds":[1,5,9], -// "Payload":"rSuPD35ELWwm5KTR9ViKIz/r1YGRgXIl5792SF8o8piZzN6sT4Liq4rUU/nfOPvQEjbfWNh/NYxdJ72VctDnWw==", -// "ReceptionID":{"EphId":[0,0,0,0,0,0,3,89], -// "Source":"emV6aW1hAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD"}, -// "Err":null} +// JSON example: +// { +// "Rounds":[1,5,9], +// "Payload":"rSuPD35ELWwm5KTR9ViKIz/r1YGRgXIl5792SF8o8piZzN6sT4Liq4rUU/nfOPvQEjbfWNh/NYxdJ72VctDnWw==", +// "ReceptionID":{"EphId":[0,0,0,0,0,0,3,89], +// "Source":"emV6aW1hAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD"}, +// "Err":null +// } type SingleUseResponseReport struct { RoundsList Payload []byte @@ -99,15 +130,17 @@ type SingleUseResponseReport struct { Err error } -// SingleUseCallbackReport is the bindings struct used to represent single use messages -// received by a callback passed into single.Listen +// SingleUseCallbackReport is the bindings-layer struct used to represent +// single -use messages received by a callback passed into single.Listen. // -// Example json marshalled struct: -// {"Rounds":[1,5,9], -// "Payload":"rSuPD35ELWwm5KTR9ViKIz/r1YGRgXIl5792SF8o8piZzN6sT4Liq4rUU/nfOPvQEjbfWNh/NYxdJ72VctDnWw==", -// "Partner":"emV6aW1hAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD", -// "EphID":{"EphId":[0,0,0,0,0,0,3,89], -// "Source":"emV6aW1hAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD"}} +// JSON example: +// { +// "Rounds":[1,5,9], +// "Payload":"rSuPD35ELWwm5KTR9ViKIz/r1YGRgXIl5792SF8o8piZzN6sT4Liq4rUU/nfOPvQEjbfWNh/NYxdJ72VctDnWw==", +// "Partner":"emV6aW1hAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD", +// "EphID":{"EphId":[0,0,0,0,0,0,3,89], +// "Source":"emV6aW1hAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD"} +// } type SingleUseCallbackReport struct { RoundsList Payload []byte @@ -116,36 +149,49 @@ type SingleUseCallbackReport struct { ReceptionID []byte } -// Function types +//////////////////////////////////////////////////////////////////////////////// +// Function Types // +//////////////////////////////////////////////////////////////////////////////// -// StopFunc is the function to stop a listener returned to the bindings layer when one is started +// StopFunc is the function to stop a listener returned to the bindings layer +// when one is started. type StopFunc func() -// SingleUseCallback func is passed into Listen and called when messages are received -// Accepts a SingleUseCallbackReport marshalled to json +// SingleUseCallback func is passed into Listen and called when messages are +// received. +// +// Parameters: +// - callbackReport - JSON marshalled SingleUseCallbackReport type SingleUseCallback interface { Callback(callbackReport []byte, err error) } -// SingleUseResponse is the public facing callback func passed by bindings clients into TransmitSingleUse -// Accepts a SingleUseResponseReport marshalled to json +// SingleUseResponse is the public facing callback function passed by bindings +// clients into TransmitSingleUse. +// +// Parameters: +// - callbackReport - JSON marshalled SingleUseResponseReport type SingleUseResponse interface { Callback(responseReport []byte, err error) } -/* CALLBACK WRAPPERS */ +//////////////////////////////////////////////////////////////////////////////// +// Callback Wrappers // +//////////////////////////////////////////////////////////////////////////////// -/* listener struct */ +/* Listener Struct */ -// singleUseListener is the internal struct used to wrap a SingleUseCallback func, -// which matches the single.Receiver interface +// singleUseListener is the internal struct used to wrap a SingleUseCallback +// function, which matches the single.Receiver interface. type singleUseListener struct { scb SingleUseCallback } -// Callback is called whenever a single use message is heard by the listener, and translates the info to -//a SingleUseCallbackReport which is marshalled & passed to bindings -func (sl singleUseListener) Callback(req *single.Request, eid receptionID.EphemeralIdentity, rl []rounds.Round) { +// Callback is called whenever a single-use message is heard by the listener +// and translates the info to a SingleUseCallbackReport that is marshalled and +// passed to bindings. +func (sl singleUseListener) Callback( + req *single.Request, eid receptionID.EphemeralIdentity, rl []rounds.Round) { var rids []id.Round for _, r := range rl { rids = append(rids, r.ID) @@ -163,16 +209,18 @@ func (sl singleUseListener) Callback(req *single.Request, eid receptionID.Epheme sl.scb.Callback(json.Marshal(scr)) } -/* response struct */ +/* Response Struct */ -// singleUseResponse is the private struct backing SingleUseResponse, which subscribes to the single.Response interface +// singleUseResponse is the private struct backing SingleUseResponse, which +// subscribes to the single.Response interface. type singleUseResponse struct { response SingleUseResponse } -// Callback builds a SingleUseSendReport & passes the json marshalled version into the callback -func (sr singleUseResponse) Callback(payload []byte, receptionID receptionID.EphemeralIdentity, - rounds []rounds.Round, err error) { +// Callback builds a SingleUseSendReport and passes the JSON marshalled version +// into the callback. +func (sr singleUseResponse) Callback(payload []byte, + receptionID receptionID.EphemeralIdentity, rounds []rounds.Round, err error) { var rids []id.Round for _, r := range rounds { rids = append(rids, r.ID) diff --git a/bindings/single_test.go b/bindings/single_test.go index be543bb7e0a972085c871a781a0a6e0bb9d43af7..863ff7c71a5671fd983c70ec1ead3d04acb35c70 100644 --- a/bindings/single_test.go +++ b/bindings/single_test.go @@ -24,7 +24,7 @@ func TestSingleUseJsonMarshals(t *testing.T) { rid := id.NewIdFromString("zezima", id.User, t) eid, _, _, err := ephemeral.GetId(rid, 16, time.Now().UnixNano()) if err != nil { - t.Fatalf("Failed to generate ephemeral id: %+v", err) + t.Fatalf("Failed to generate ephemeral ID: %+v", err) } ephId := receptionID.EphemeralIdentity{ EphId: eid, @@ -32,7 +32,7 @@ func TestSingleUseJsonMarshals(t *testing.T) { } payload := make([]byte, 64) rng := csprng.NewSystemRNG() - rng.Read(payload) + _, _ = rng.Read(payload) sendReport := SingleUseSendReport{ RoundsList: rl, EphID: ephId.EphId.Int64(), diff --git a/bindings/version.go b/bindings/version.go index ad7ddc66e800713d84f2d3858f854d6b5cedb6aa..e0571df8f1f22855f504b021fe869111781f724b 100644 --- a/bindings/version.go +++ b/bindings/version.go @@ -11,17 +11,17 @@ package bindings import "gitlab.com/elixxir/client/xxdk" -// GetVersion returns the api SEMVER +// GetVersion returns the xxdk.SEMVER. func GetVersion() string { return xxdk.SEMVER } -// GetGitVersion rturns the api GITVERSION +// GetGitVersion returns the xxdk.GITVERSION. func GetGitVersion() string { return xxdk.GITVERSION } -// GetDependencies returns the api DEPENDENCIES +// GetDependencies returns the xxdk.DEPENDENCIES. func GetDependencies() string { return xxdk.DEPENDENCIES }