util.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package ncutils
  2. import (
  3. "fmt"
  4. "strings"
  5. "time"
  6. )
  7. // BackOff - back off any function while there is an error
  8. func BackOff(isExponential bool, maxTime int, f interface{}) (interface{}, error) {
  9. // maxTime seconds
  10. startTime := time.Now()
  11. sleepTime := time.Second
  12. for time.Now().Before(startTime.Add(time.Second * time.Duration(maxTime))) {
  13. if result, err := f.(func() (interface{}, error))(); err == nil {
  14. return result, nil
  15. }
  16. time.Sleep(sleepTime)
  17. if isExponential {
  18. sleepTime = sleepTime << 1
  19. }
  20. PrintLog("retrying...", 1)
  21. }
  22. return nil, fmt.Errorf("could not find result")
  23. }
  24. // DestructMessage - reconstruct original message through chunks
  25. func DestructMessage(builtMsg string, senderPublicKey *[32]byte, recipientPrivateKey *[32]byte) ([]byte, error) {
  26. var chunks = strings.Split(builtMsg, splitKey)
  27. var totalMessage = make([]byte, len(builtMsg))
  28. for _, chunk := range chunks {
  29. var bytes, decErr = BoxDecrypt([]byte(chunk), senderPublicKey, recipientPrivateKey)
  30. if decErr != nil || bytes == nil {
  31. return nil, decErr
  32. }
  33. totalMessage = append(totalMessage, bytes...)
  34. }
  35. return totalMessage, nil
  36. }
  37. // BuildMessage Build a message for publishing
  38. func BuildMessage(originalMessage []byte, recipientPubKey *[32]byte, senderPrivateKey *[32]byte) (string, error) {
  39. chunks := getSliceChunks(originalMessage, 16128)
  40. var sb strings.Builder
  41. for i := 0; i < len(chunks); i++ {
  42. var encryptedText, encryptErr = BoxEncrypt(chunks[i], recipientPubKey, senderPrivateKey)
  43. if encryptErr != nil {
  44. return "", encryptErr
  45. }
  46. sb.Write(encryptedText)
  47. if i < len(chunks)-1 {
  48. sb.WriteString(splitKey)
  49. }
  50. }
  51. return sb.String(), nil
  52. }
  53. var splitKey = "<|#|>"
  54. func getSliceChunks(slice []byte, chunkSize int) [][]byte {
  55. var chunks [][]byte
  56. for i := 0; i < len(slice); i += chunkSize {
  57. lastByte := i + chunkSize
  58. if lastByte > len(slice) {
  59. lastByte = len(slice)
  60. }
  61. chunks = append(chunks, slice[i:lastByte])
  62. }
  63. return chunks
  64. }