leader.go 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410
  1. package main
  2. //#cgo CFLAGS: -fopenmp -O2
  3. //#cgo LDFLAGS: -lcrypto -lm -fopenmp
  4. //#include "../c/dpf.h"
  5. //#include "../c/okv.h"
  6. //#include "../c/dpf.c"
  7. //#include "../c/okv.c"
  8. import "C"
  9. //ssssssssssssssss
  10. import (
  11. "crypto/rand"
  12. "crypto/rsa"
  13. "crypto/sha256"
  14. "crypto/tls"
  15. "crypto/x509"
  16. "crypto/x509/pkix"
  17. "encoding/pem"
  18. "fmt"
  19. "math"
  20. "math/big"
  21. mr "math/rand"
  22. "net"
  23. "sort"
  24. "strconv"
  25. "strings"
  26. "sync"
  27. "time"
  28. lib "2PPS/lib"
  29. "unsafe"
  30. "golang.org/x/crypto/nacl/box"
  31. )
  32. //this stores all neccessary information for each client
  33. type clientKeys struct {
  34. roundsParticipating int
  35. PublicKey *[32]byte
  36. SharedSecret [32]byte
  37. PirQuery [][]byte
  38. }
  39. var clientData = make(map[net.Addr]clientKeys)
  40. const follower string = "127.0.0.1:4442"
  41. //Maximum Transport Unit
  42. const mtu int = 1100
  43. var leaderPrivateKey *[32]byte
  44. var leaderPublicKey *[32]byte
  45. var followerPublicKey *[32]byte
  46. const maxNumberOfClients = 10000000
  47. var topicList []byte
  48. var topicAmount int
  49. var archiveTopicAmount int
  50. // every roundsBeforeUpdate the client updates his pirQuery
  51. const roundsBeforeUpdate = 5
  52. const neededSubscriptions = 1
  53. const numThreads = 12
  54. const dataLength = 256
  55. const minDBWriteSize = 10
  56. var dbWriteSize float64 = 20000
  57. var collisionCounter []float64
  58. var clientsConnected int
  59. var maxTimePerRound time.Duration = 25 * time.Second
  60. var clientsServedPhase1 []int
  61. var clientsServedPhase3 []int
  62. var startPhase1 time.Time
  63. var startPhase2 time.Time
  64. var startPhase3 time.Time
  65. //counts the number of rounds
  66. var round int = 0
  67. var startTime time.Time
  68. var startTimeRound time.Time
  69. //channel for goroutine communication with clients
  70. var phase1Channel = make(chan net.Conn, maxNumberOfClients)
  71. var phase3Channel = make(chan net.Conn, maxNumberOfClients)
  72. //variables for calculating the dbWrite size
  73. const publisherRounds int = 10
  74. var publisherAmount float64
  75. var publisherHistory [publisherRounds]int
  76. //todo! handle client dc during phase1/3
  77. func main() {
  78. //prevents race conditions for wrtiting
  79. m := &sync.RWMutex{}
  80. startTime = time.Now()
  81. clientsServedPhase1 = make([]int, 1000)
  82. clientsServedPhase3 = make([]int, 1000)
  83. generatedPublicKey, generatedPrivateKey, err := box.GenerateKey(rand.Reader)
  84. if err != nil {
  85. panic(err)
  86. }
  87. //why is this neccessary?
  88. leaderPrivateKey = generatedPrivateKey
  89. leaderPublicKey = generatedPublicKey
  90. C.initializeServer(C.int(numThreads))
  91. //calls follower for setup
  92. conf := &tls.Config{
  93. InsecureSkipVerify: true,
  94. }
  95. followerConnection, err := tls.Dial("tcp", follower, conf)
  96. if err != nil {
  97. panic(err)
  98. }
  99. followerConnection.SetDeadline(time.Time{})
  100. //receives follower publicKey
  101. var tmpFollowerPubKey [32]byte
  102. _, err = followerConnection.Read(tmpFollowerPubKey[:])
  103. if err != nil {
  104. panic(err)
  105. }
  106. followerPublicKey = &tmpFollowerPubKey
  107. //send publicKey to follower
  108. writeTo(followerConnection, leaderPublicKey[:])
  109. writeTo(followerConnection, intToByte(neededSubscriptions))
  110. //goroutine for accepting new clients
  111. go func() {
  112. leaderConnectionPrivateKey, err := rsa.GenerateKey(rand.Reader, 2048)
  113. if err != nil {
  114. panic(err)
  115. }
  116. // Generate a pem block with the private key
  117. keyPem := pem.EncodeToMemory(&pem.Block{
  118. Type: "RSA PRIVATE KEY",
  119. Bytes: x509.MarshalPKCS1PrivateKey(leaderConnectionPrivateKey),
  120. })
  121. tml := x509.Certificate{
  122. // you can add any attr that you need
  123. NotBefore: time.Now(),
  124. NotAfter: time.Now().AddDate(5, 0, 0),
  125. // you have to generate a different serial number each execution
  126. SerialNumber: big.NewInt(123123),
  127. Subject: pkix.Name{
  128. CommonName: "New Name",
  129. Organization: []string{"New Org."},
  130. },
  131. BasicConstraintsValid: true,
  132. }
  133. cert, err := x509.CreateCertificate(rand.Reader, &tml, &tml, &leaderConnectionPrivateKey.PublicKey, leaderConnectionPrivateKey)
  134. if err != nil {
  135. panic(err)
  136. }
  137. // Generate a pem block with the certificate
  138. certPem := pem.EncodeToMemory(&pem.Block{
  139. Type: "CERTIFICATE",
  140. Bytes: cert,
  141. })
  142. tlsCert, err := tls.X509KeyPair(certPem, keyPem)
  143. if err != nil {
  144. panic(err)
  145. }
  146. config := &tls.Config{Certificates: []tls.Certificate{tlsCert}}
  147. //listens for clients
  148. lnClients, err := tls.Listen("tcp", ":4441", config)
  149. if err != nil {
  150. panic(err)
  151. }
  152. defer lnClients.Close()
  153. for {
  154. clientConnection, err := lnClients.Accept()
  155. if err != nil {
  156. fmt.Println("error", err)
  157. }
  158. clientConnection.SetDeadline(time.Time{})
  159. //sends topicList so client can participate in phase 3 asap
  160. errorBool := sendTopicLists(clientConnection, followerConnection, true)
  161. if errorBool {
  162. break
  163. }
  164. //send leader publicKey
  165. _, err = clientConnection.Write(leaderPublicKey[:])
  166. if err != nil {
  167. fmt.Println("error", err)
  168. clientConnection.Close()
  169. break
  170. }
  171. //send follower publicKey
  172. _, err = clientConnection.Write(followerPublicKey[:])
  173. if err != nil {
  174. fmt.Println("error", err)
  175. clientConnection.Close()
  176. break
  177. }
  178. var clientPublicKey *[32]byte
  179. var tmpClientPublicKey [32]byte
  180. //gets publicKey from client
  181. _, err = clientConnection.Read(tmpClientPublicKey[:])
  182. if err != nil {
  183. fmt.Println("error", err)
  184. clientConnection.Close()
  185. break
  186. }
  187. _, err = clientConnection.Write(intToByte(neededSubscriptions))
  188. if err != nil {
  189. fmt.Println("error", err)
  190. clientConnection.Close()
  191. break
  192. }
  193. _, err = clientConnection.Write(intToByte(int(startTime.Unix())))
  194. if err != nil {
  195. fmt.Println("error", err)
  196. clientConnection.Close()
  197. break
  198. }
  199. clientPublicKey = &tmpClientPublicKey
  200. //this is the key for map(client data)
  201. remoteAddress := clientConnection.RemoteAddr()
  202. //pirQuery will be added in phase 3
  203. //bs! only want to set roundsParticipating and answerAmount to 0, mb there is a better way
  204. //will work for now
  205. var emptyArray [32]byte
  206. var emptyByteArray [][]byte
  207. keys := clientKeys{0, clientPublicKey, emptyArray, emptyByteArray}
  208. m.Lock()
  209. clientData[remoteAddress] = keys
  210. m.Unlock()
  211. phase1Channel <- clientConnection
  212. clientsConnected++
  213. if clientsConnected%1000 == 0 {
  214. fmt.Println("clientsConnected", clientsConnected)
  215. }
  216. }
  217. }()
  218. wg := &sync.WaitGroup{}
  219. //the current phase
  220. phase := make([]byte, 1)
  221. for {
  222. startPhase1 = time.Now()
  223. startTimeRound = time.Now()
  224. phase[0] = 1
  225. round++
  226. fmt.Println("clientsServedPhase1", clientsServedPhase1[round-1])
  227. fmt.Println("clientsServedPhase3", clientsServedPhase3[round-1])
  228. fmt.Println("dbWriteSize", dbWriteSize)
  229. fmt.Println("Phase 1 Round", round)
  230. //creates a new write Db for this round
  231. for i := 0; i < int(dbWriteSize); i++ {
  232. C.createDb(C.int(1), C.int(dataLength))
  233. }
  234. //creates a new db containing virtual addresses for auditing
  235. virtualAddresses := createVirtualAddresses()
  236. //send all virtualAddresses to follower
  237. for i := 0; i <= int(dbWriteSize); i++ {
  238. writeTo(followerConnection, intToByte(virtualAddresses[i]))
  239. }
  240. //moves all clients to phase1
  241. if len(phase3Channel) > 0 {
  242. for client := range phase3Channel {
  243. phase1Channel <- client
  244. if len(phase3Channel) == 0 {
  245. break
  246. }
  247. }
  248. }
  249. for id := 0; id < numThreads; id++ {
  250. wg.Add(1)
  251. followerConnection, err := tls.Dial("tcp", follower, conf)
  252. if err != nil {
  253. panic(err)
  254. }
  255. followerConnection.SetDeadline(time.Time{})
  256. go phase1(id, phase, followerConnection, wg, m, virtualAddresses)
  257. }
  258. wg.Wait()
  259. fmt.Println("fullDurationPhase1", time.Since(startPhase1).Seconds())
  260. //Phase 2
  261. startPhase2 = time.Now()
  262. followerConnection, err := tls.Dial("tcp", follower, conf)
  263. if err != nil {
  264. panic(err)
  265. }
  266. followerConnection.SetDeadline(time.Time{})
  267. phase2(followerConnection)
  268. fmt.Println("fullDurationPhase2", time.Since(startPhase2).Seconds())
  269. //Phase 3
  270. //moves all clients to phase3
  271. if len(phase1Channel) > 0 {
  272. for client := range phase1Channel {
  273. phase3Channel <- client
  274. if len(phase1Channel) == 0 {
  275. break
  276. }
  277. }
  278. }
  279. startPhase3 = time.Now()
  280. //no tweets -> continue to phase 1 and mb get tweets
  281. topicList, topicAmount = lib.GetTopicList(0)
  282. if len(topicList) == 0 {
  283. continue
  284. }
  285. phase[0] = 3
  286. startTimeRound = time.Now()
  287. for id := 0; id < numThreads; id++ {
  288. wg.Add(1)
  289. followerConnection, err := tls.Dial("tcp", follower, conf)
  290. if err != nil {
  291. panic(err)
  292. }
  293. followerConnection.SetDeadline(time.Time{})
  294. go phase3(id, phase, followerConnection, wg, m)
  295. }
  296. wg.Wait()
  297. fmt.Println("fullDurationPhase3", time.Since(startPhase3).Seconds())
  298. lib.CleanUpdbR(round)
  299. }
  300. }
  301. func phase1(id int, phase []byte, followerConnection net.Conn, wg *sync.WaitGroup, m *sync.RWMutex, virtualAddresses []int) {
  302. roundAsBytes := intToByte(round)
  303. gotClient := make([]byte, 1)
  304. gotClient[0] = 0
  305. //wait until time is up
  306. for len(phase1Channel) == 0 {
  307. if time.Since(startTimeRound) > maxTimePerRound {
  308. //tells follower that this worker is done
  309. writeTo(followerConnection, gotClient)
  310. wg.Done()
  311. return
  312. }
  313. time.Sleep(1 * time.Second)
  314. }
  315. for clientConnection := range phase1Channel {
  316. clientsServedPhase1[round] = clientsServedPhase1[round] + 1
  317. if clientsServedPhase1[round]%1000 == 0 {
  318. fmt.Println("clientsServedPhase1", clientsServedPhase1[round])
  319. fmt.Println("timeTaken", time.Since(startPhase1))
  320. }
  321. gotClient[0] = 1
  322. //tells follower that this worker got a clientConnection
  323. writeTo(followerConnection, gotClient)
  324. //sends clients publicKey to follower
  325. m.RLock()
  326. clientPublicKey := clientData[clientConnection.RemoteAddr()].PublicKey
  327. m.RUnlock()
  328. writeTo(followerConnection, clientPublicKey[:])
  329. //setup the worker-specific db
  330. dbSize := int(C.dbSize)
  331. db := make([][]byte, dbSize)
  332. for i := 0; i < dbSize; i++ {
  333. db[i] = make([]byte, int(C.db[i].dataSize))
  334. }
  335. //tells client that phase 1 has begun
  336. errorBool := writeToWError(clientConnection, phase, followerConnection, 5)
  337. if errorBool {
  338. contBool := handleClientDC(wg, followerConnection, phase1Channel)
  339. if contBool {
  340. continue
  341. } else {
  342. return
  343. }
  344. }
  345. //tells client current dbWriteSize
  346. errorBool = writeToWError(clientConnection, intToByte(int(dbWriteSize)), followerConnection, 5)
  347. if errorBool {
  348. contBool := handleClientDC(wg, followerConnection, phase1Channel)
  349. if contBool {
  350. continue
  351. } else {
  352. return
  353. }
  354. }
  355. //tells client current round
  356. errorBool = writeToWError(clientConnection, roundAsBytes, followerConnection, 5)
  357. if errorBool {
  358. contBool := handleClientDC(wg, followerConnection, phase1Channel)
  359. if contBool {
  360. continue
  361. } else {
  362. return
  363. }
  364. }
  365. //begin auditing
  366. //auditingStart := time.Now()
  367. m.RLock()
  368. var clientKeys = clientData[clientConnection.RemoteAddr()]
  369. m.RUnlock()
  370. clientKeys, pirQuery, errorBool := handlePirQuery(clientKeys, clientConnection, followerConnection, 0, true)
  371. if errorBool {
  372. contBool := handleClientDC(wg, followerConnection, phase1Channel)
  373. if contBool {
  374. continue
  375. } else {
  376. return
  377. }
  378. }
  379. errorBool = getSendVirtualAddress(pirQuery[0], virtualAddresses, clientKeys.SharedSecret, clientConnection, followerConnection)
  380. if errorBool {
  381. contBool := handleClientDC(wg, followerConnection, phase1Channel)
  382. if contBool {
  383. continue
  384. } else {
  385. return
  386. }
  387. }
  388. if id == 0 {
  389. //fmt.Println("Auditing duration", time.Since(auditingStart).Seconds())
  390. }
  391. m.Lock()
  392. clientData[clientConnection.RemoteAddr()] = clientKeys
  393. m.Unlock()
  394. //accept dpfQuery from client
  395. dpfLengthBytes, errorBool := readFrom(clientConnection, 4, followerConnection, 5)
  396. if errorBool {
  397. contBool := handleClientDC(wg, followerConnection, phase1Channel)
  398. if contBool {
  399. continue
  400. } else {
  401. return
  402. }
  403. }
  404. dpfLength := byteToInt(dpfLengthBytes)
  405. dpfQueryAEncrypted, errorBool := readFrom(clientConnection, dpfLength, followerConnection, 5)
  406. if errorBool {
  407. contBool := handleClientDC(wg, followerConnection, phase1Channel)
  408. if contBool {
  409. continue
  410. } else {
  411. return
  412. }
  413. }
  414. dpfQueryBEncrypted, errorBool := readFrom(clientConnection, dpfLength, followerConnection, 5)
  415. if errorBool {
  416. contBool := handleClientDC(wg, followerConnection, phase1Channel)
  417. if contBool {
  418. continue
  419. } else {
  420. return
  421. }
  422. }
  423. writeToWError(followerConnection, dpfLengthBytes, nil, 0)
  424. writeToWError(followerConnection, dpfQueryBEncrypted, nil, 0)
  425. //decrypt dpfQueryA for sorting into db
  426. var decryptNonce [24]byte
  427. copy(decryptNonce[:], dpfQueryAEncrypted[:24])
  428. dpfQueryA, ok := box.Open(nil, dpfQueryAEncrypted[24:], &decryptNonce, clientPublicKey, leaderPrivateKey)
  429. if !ok {
  430. panic("dpfQueryA decryption not ok")
  431. }
  432. ds := int(C.db[0].dataSize)
  433. dataShareLeader := make([]byte, ds)
  434. pos := C.getUint128_t(C.int(virtualAddresses[int(dbWriteSize)]))
  435. C.evalDPF(C.ctx[id], (*C.uchar)(&dpfQueryA[0]), pos, C.int(ds), (*C.uchar)(&dataShareLeader[0]))
  436. dataShareFollower, _ := readFrom(followerConnection, ds, nil, 0)
  437. writeToWError(followerConnection, dataShareLeader, nil, 0)
  438. auditXOR := make([]byte, ds)
  439. passedAudit := true
  440. for i := 0; i < ds; i++ {
  441. auditXOR[i] = dataShareLeader[i] ^ dataShareFollower[i]
  442. //client tried to write to a position that is not a virtuallAddress
  443. if auditXOR[i] != 0 {
  444. clientConnection.Close()
  445. passedAudit = false
  446. }
  447. }
  448. if passedAudit {
  449. //run dpf, xor into local db
  450. for i := 0; i < dbSize; i++ {
  451. ds := int(C.db[i].dataSize)
  452. dataShare := make([]byte, ds)
  453. pos := C.getUint128_t(C.int(virtualAddresses[i]))
  454. C.evalDPF(C.ctx[id], (*C.uchar)(&dpfQueryA[0]), pos, C.int(ds), (*C.uchar)(&dataShare[0]))
  455. for j := 0; j < ds; j++ {
  456. db[i][j] = db[i][j] ^ dataShare[j]
  457. }
  458. }
  459. //xor the worker's DB into the main DB
  460. for i := 0; i < dbSize; i++ {
  461. m.Lock()
  462. C.xorIn(C.int(i), (*C.uchar)(&db[i][0]))
  463. m.Unlock()
  464. }
  465. phase3Channel <- clientConnection
  466. }
  467. //loop that waits for new client or leaves phase1 if time is up
  468. for {
  469. if time.Since(startTimeRound) < maxTimePerRound {
  470. //this worker handles the next client
  471. if len(phase1Channel) > 0 {
  472. break
  473. //this worker waits for next client
  474. } else {
  475. time.Sleep(1 * time.Second)
  476. }
  477. //times up
  478. } else {
  479. //tells follower that this worker is done
  480. gotClient[0] = 0
  481. writeTo(followerConnection, gotClient)
  482. wg.Done()
  483. return
  484. }
  485. }
  486. }
  487. }
  488. func phase2(followerConnection net.Conn) {
  489. //gets current seed
  490. seedLeader := make([]byte, 16)
  491. C.readSeed((*C.uchar)(&seedLeader[0]))
  492. //get data
  493. dbSize := int(C.dbSize)
  494. tmpdbLeader := make([][]byte, dbSize)
  495. for i := range tmpdbLeader {
  496. tmpdbLeader[i] = make([]byte, dataLength)
  497. }
  498. for i := 0; i < dbSize; i++ {
  499. C.readData(C.int(i), (*C.uchar)(&tmpdbLeader[i][0]))
  500. }
  501. //writes seed to follower
  502. writeTo(followerConnection, seedLeader)
  503. //write data to follower
  504. //this is surely inefficent
  505. for i := 0; i < dbSize; i++ {
  506. writeTo(followerConnection, tmpdbLeader[i])
  507. }
  508. //receive seed from follower
  509. seedFollower, _ := readFrom(followerConnection, 16, nil, 0)
  510. //receive data from follower
  511. tmpdbFollower := make([][]byte, dbSize)
  512. for i := range tmpdbFollower {
  513. tmpdbFollower[i] = make([]byte, dataLength)
  514. }
  515. for i := 0; i < dbSize; i++ {
  516. tmpdbFollower[i], _ = readFrom(followerConnection, dataLength, nil, 0)
  517. }
  518. //put together the db
  519. tmpdb := make([][]byte, dbSize)
  520. for i := range tmpdb {
  521. tmpdb[i] = make([]byte, dataLength)
  522. }
  523. //get own Ciphers
  524. ciphersLeader := make([]*C.uchar, dbSize)
  525. for i := 0; i < dbSize; i++ {
  526. ciphersLeader[i] = (*C.uchar)(C.malloc(16))
  527. }
  528. for i := 0; i < dbSize; i++ {
  529. C.getCipher(1, C.int(i), ciphersLeader[i])
  530. }
  531. //send own Ciphers to follower
  532. for i := 0; i < dbSize; i++ {
  533. writeTo(followerConnection, C.GoBytes(unsafe.Pointer(ciphersLeader[i]), 16))
  534. }
  535. //receive ciphers from follower
  536. ciphersFollower := make([]byte, dbSize*16)
  537. for i := 0; i < dbSize; i++ {
  538. _, err := followerConnection.Read(ciphersFollower[i*16:])
  539. if err != nil {
  540. panic(err)
  541. }
  542. }
  543. //put in ciphers from follower
  544. for i := 0; i < dbSize; i++ {
  545. C.putCipher(1, C.int(i), (*C.uchar)(&ciphersFollower[i*16]))
  546. }
  547. //decrypt each row
  548. for i := 0; i < dbSize; i++ {
  549. C.decryptRow(C.int(i), (*C.uchar)(&tmpdb[i][0]), (*C.uchar)(&tmpdbLeader[i][0]), (*C.uchar)(&tmpdbFollower[i][0]), (*C.uchar)(&seedLeader[0]), (*C.uchar)(&seedFollower[0]))
  550. }
  551. var tweets []lib.Tweet
  552. var currentPublisherAmount int = 0
  553. var collisions float64
  554. for i := 0; i < dbSize; i++ {
  555. //discard cover message
  556. if tmpdb[i][1] == 0 {
  557. continue
  558. //collision
  559. } else if -1 == strings.Index(string(tmpdb[i]), ";;") {
  560. currentPublisherAmount++
  561. currentPublisherAmount++
  562. collisions++
  563. continue
  564. } else {
  565. currentPublisherAmount++
  566. //reconstruct tweet
  567. var position int = 0
  568. var topics []string
  569. var topic string
  570. var text string
  571. for _, letter := range tmpdb[i] {
  572. if string(letter) == ";" {
  573. if topic != "" {
  574. topics = append(topics, topic)
  575. topic = ""
  576. }
  577. position++
  578. } else {
  579. if position == 0 {
  580. if string(letter) == "," {
  581. topics = append(topics, topic)
  582. topic = ""
  583. } else {
  584. //change this works for ints, need to be changed for strings
  585. //have
  586. topic = topic + string(letter)
  587. }
  588. } else if position == 1 {
  589. text = text + string(letter)
  590. }
  591. }
  592. }
  593. tweet := lib.Tweet{"", -1, topics, text, round}
  594. if text != "" {
  595. tweets = append(tweets, tweet)
  596. } else {
  597. //this is a odd(number) way collisions
  598. collisions++
  599. }
  600. }
  601. }
  602. collisionCounter = append(collisionCounter, collisions)
  603. if collisions/dbWriteSize > 0.05 {
  604. fmt.Println("Collisions this round", collisions, "dbWriteSize", dbWriteSize)
  605. }
  606. //fmt.Println("tweets recovered: ", tweets)
  607. //sort into read db
  608. //fmt.Println("newTweets", tweets)
  609. lib.NewEntries(tweets, 0)
  610. C.resetDb()
  611. //calculates the publisherAverage over the last publisherRounds rounds
  612. index := round % publisherRounds
  613. publisherHistory[index] = currentPublisherAmount
  614. fmt.Println("currentPublisherAmount", currentPublisherAmount)
  615. var publisherAmount int
  616. for _, num := range publisherHistory {
  617. publisherAmount += num
  618. }
  619. publisherAverage := 0
  620. if round < publisherRounds {
  621. publisherAverage = publisherAmount / round
  622. } else {
  623. publisherAverage = publisherAmount / publisherRounds
  624. }
  625. //calculates the dbWriteSize for this round
  626. dbWriteSize = math.Ceil(19.5 * float64(publisherAverage))
  627. if dbWriteSize < minDBWriteSize {
  628. dbWriteSize = minDBWriteSize
  629. }
  630. //writes dbWriteSize of current round to follower
  631. writeTo(followerConnection, intToByte(int(dbWriteSize)))
  632. }
  633. func addTestTweets() {
  634. //creates test tweets
  635. tweets := make([]lib.Tweet, 5)
  636. for i := range tweets {
  637. j := i
  638. if i == 1 {
  639. j = 0
  640. }
  641. text := "Text " + strconv.Itoa(i)
  642. var topics []string
  643. topics = append(topics, "Topic "+strconv.Itoa(j))
  644. tweets[i] = lib.Tweet{"", -1, topics, text, i}
  645. }
  646. lib.NewEntries(tweets, 0)
  647. }
  648. //opti! mb it is quicker to send updated topicLists to clients first so pirQuerys are ready
  649. func phase3(id int, phase []byte, followerConnection net.Conn, wg *sync.WaitGroup, m *sync.RWMutex) {
  650. gotClient := make([]byte, 1)
  651. gotClient[0] = 0
  652. //wait until time is up
  653. for len(phase3Channel) == 0 {
  654. if time.Since(startTimeRound) > maxTimePerRound*2 {
  655. //tells follower that this worker is done
  656. writeToWError(followerConnection, gotClient, nil, 0)
  657. wg.Done()
  658. return
  659. }
  660. time.Sleep(1 * time.Second)
  661. }
  662. for clientConnection := range phase3Channel {
  663. clientsServedPhase3[round] = clientsServedPhase3[round] + 1
  664. if clientsServedPhase3[round]%1000 == 0 {
  665. fmt.Println("clientsServedPhase3", clientsServedPhase3[round])
  666. fmt.Println("timeTaken", time.Since(startPhase3).Seconds())
  667. }
  668. gotClient[0] = 1
  669. //tells follower that this worker got a clientConnection
  670. writeToWError(followerConnection, gotClient, nil, 0)
  671. //tells client current phase
  672. errorBool := writeToWError(clientConnection, phase, followerConnection, 2)
  673. if errorBool {
  674. contBool := handleClientDC(wg, followerConnection, phase3Channel)
  675. if contBool {
  676. continue
  677. } else {
  678. return
  679. }
  680. }
  681. /*
  682. possible Values
  683. 0 : new client
  684. leader expects sharedSecrets, expects pirQuery
  685. 1 : update needed
  686. leader sends topicList, performs local update of sharedSecret, expects pirQuery
  687. 2 : no update needed
  688. nothing
  689. */
  690. subPhase := make([]byte, 1)
  691. //gets the data for the current client
  692. m.RLock()
  693. var clientKeys = clientData[clientConnection.RemoteAddr()]
  694. m.RUnlock()
  695. var roundsParticipating = clientKeys.roundsParticipating
  696. //client participates for the first time
  697. if roundsParticipating == 0 {
  698. subPhase[0] = 0
  699. } else if roundsParticipating%roundsBeforeUpdate == 0 {
  700. subPhase[0] = 1
  701. } else {
  702. subPhase[0] = 2
  703. }
  704. //tells client what leader expects
  705. errorBool = writeToWError(clientConnection, subPhase, followerConnection, 2)
  706. if errorBool {
  707. contBool := handleClientDC(wg, followerConnection, phase3Channel)
  708. if contBool {
  709. continue
  710. } else {
  711. return
  712. }
  713. }
  714. //tells follower what will happen
  715. writeToWError(followerConnection, subPhase, nil, 0)
  716. //sends clients publicKey so follower knows which client is being served
  717. writeTo(followerConnection, clientKeys.PublicKey[:])
  718. //increases rounds participating for client
  719. clientKeys.roundsParticipating = roundsParticipating + 1
  720. //declaring variables here to prevent dupclicates later
  721. m.RLock()
  722. var sharedSecret [32]byte = clientData[clientConnection.RemoteAddr()].SharedSecret
  723. m.RUnlock()
  724. if subPhase[0] == 0 {
  725. errorBool := sendTopicLists(clientConnection, followerConnection, false)
  726. if errorBool {
  727. contBool := handleClientDC(wg, followerConnection, phase3Channel)
  728. if contBool {
  729. continue
  730. } else {
  731. return
  732. }
  733. }
  734. clientKeys, _, errorBool = handlePirQuery(clientKeys, clientConnection, followerConnection, int(subPhase[0]), false)
  735. if errorBool {
  736. contBool := handleClientDC(wg, followerConnection, phase3Channel)
  737. if contBool {
  738. continue
  739. } else {
  740. return
  741. }
  742. }
  743. } else if subPhase[0] == 1 {
  744. errorBool := sendTopicLists(clientConnection, followerConnection, false)
  745. if errorBool {
  746. contBool := handleClientDC(wg, followerConnection, phase3Channel)
  747. if contBool {
  748. continue
  749. } else {
  750. return
  751. }
  752. }
  753. //updates sharedSecret
  754. sharedSecret = sha256.Sum256(sharedSecret[:])
  755. clientKeys.SharedSecret = sharedSecret
  756. clientKeys, _, errorBool = handlePirQuery(clientKeys, clientConnection, followerConnection, int(subPhase[0]), false)
  757. if errorBool {
  758. contBool := handleClientDC(wg, followerConnection, phase3Channel)
  759. if contBool {
  760. continue
  761. } else {
  762. return
  763. }
  764. }
  765. }
  766. errorBool = getSendTweets(clientKeys, nil, clientConnection, followerConnection, m)
  767. if errorBool {
  768. contBool := handleClientDC(wg, followerConnection, phase3Channel)
  769. if contBool {
  770. continue
  771. } else {
  772. return
  773. }
  774. }
  775. wantsArchive, errorBool := readFrom(clientConnection, 1, followerConnection, 2)
  776. if errorBool {
  777. contBool := handleClientDC(wg, followerConnection, phase3Channel)
  778. if contBool {
  779. continue
  780. } else {
  781. return
  782. }
  783. }
  784. writeToWError(followerConnection, wantsArchive, nil, 0)
  785. if wantsArchive[0] == 1 && archiveTopicAmount > 0 {
  786. _, archiveQuerys, errorBool := handlePirQuery(clientKeys, clientConnection, followerConnection, -1, false)
  787. if errorBool {
  788. contBool := handleClientDC(wg, followerConnection, phase3Channel)
  789. if contBool {
  790. continue
  791. } else {
  792. return
  793. }
  794. }
  795. errorBool = getSendTweets(clientKeys, archiveQuerys, clientConnection, followerConnection, m)
  796. if errorBool {
  797. contBool := handleClientDC(wg, followerConnection, phase3Channel)
  798. if contBool {
  799. continue
  800. } else {
  801. return
  802. }
  803. }
  804. }
  805. //saves all changes for client
  806. m.Lock()
  807. clientData[clientConnection.RemoteAddr()] = clientKeys
  808. m.Unlock()
  809. phase1Channel <- clientConnection
  810. for {
  811. if time.Since(startTimeRound) < 2*maxTimePerRound {
  812. //this worker handles the next client
  813. if len(phase3Channel) > 0 {
  814. break
  815. //this worker waits for next client
  816. } else {
  817. time.Sleep(1 * time.Second)
  818. }
  819. //times up
  820. } else {
  821. //tells follower that this worker is done
  822. gotClient[0] = 0
  823. writeToWError(followerConnection, gotClient, nil, 0)
  824. wg.Done()
  825. return
  826. }
  827. }
  828. }
  829. }
  830. //returns true if there is another client
  831. func handleClientDC(wg *sync.WaitGroup, followerConnection net.Conn, channel chan net.Conn) bool {
  832. //loop that waits for new client or leaves phase1 if time is up
  833. for {
  834. if time.Since(startTimeRound) < maxTimePerRound {
  835. //this worker handles the next client
  836. if len(channel) > 0 {
  837. return true
  838. //this worker waits for next client
  839. } else {
  840. time.Sleep(1 * time.Second)
  841. }
  842. //times up
  843. } else {
  844. //tells follower that this worker is done
  845. gotClient := make([]byte, 1)
  846. gotClient[0] = 0
  847. writeTo(followerConnection, gotClient)
  848. wg.Done()
  849. return false
  850. }
  851. }
  852. }
  853. func createVirtualAddresses() []int {
  854. //array will be filled with unique random ascending values
  855. //adapted from: https://stackoverflow.com/questions/20039025/java-array-of-unique-randomly-generated-integers
  856. //+1 to have a position to evaluate each received message
  857. arraySize := int(dbWriteSize) + 1
  858. var maxInt int = int(math.Pow(2, 31))
  859. virtualAddresses := make([]int, arraySize)
  860. for i := 0; i < arraySize; i++ {
  861. virtualAddresses[i] = mr.Intn(maxInt)
  862. for j := 0; j < i; j++ {
  863. if virtualAddresses[i] == virtualAddresses[j] {
  864. i--
  865. break
  866. }
  867. }
  868. }
  869. sort.Ints(virtualAddresses)
  870. return virtualAddresses
  871. }
  872. func getSendVirtualAddress(pirQuery []byte, virtualAddresses []int, sharedSecret [32]byte, clientConnection, followerConnection net.Conn) bool {
  873. //xores all requested addresses into virtuallAddress
  874. virtualAddress := make([]byte, 4)
  875. for index, num := range pirQuery {
  876. if num == 1 {
  877. currentAddress := intToByte(virtualAddresses[index])
  878. for i := 0; i < 4; i++ {
  879. virtualAddress[i] = virtualAddress[i] ^ currentAddress[i]
  880. }
  881. }
  882. }
  883. //xores the sharedSecret
  884. for i := 0; i < 4; i++ {
  885. virtualAddress[i] = virtualAddress[i] ^ sharedSecret[i]
  886. }
  887. virtualAddressFollower, _ := readFrom(followerConnection, 4, nil, 0)
  888. //xores the data from follower
  889. for i := 0; i < 4; i++ {
  890. virtualAddress[i] = virtualAddress[i] ^ virtualAddressFollower[i]
  891. }
  892. errorBool := writeToWError(clientConnection, virtualAddress, followerConnection, 5)
  893. return errorBool
  894. }
  895. func getSendTweets(clientKeys clientKeys, archiveQuerys [][]byte, clientConnection, followerConnection net.Conn, m *sync.RWMutex) bool {
  896. //todo! repeat for archive
  897. tmpNeededSubscriptions := neededSubscriptions
  898. if tmpNeededSubscriptions > topicAmount {
  899. tmpNeededSubscriptions = topicAmount
  900. }
  901. if archiveQuerys != nil {
  902. tmpNeededSubscriptions = len(archiveQuerys)
  903. }
  904. //fmt.Println("tmpNeededSubscriptions", tmpNeededSubscriptions)
  905. tweets := make([][]byte, tmpNeededSubscriptions)
  906. for i := 0; i < tmpNeededSubscriptions; i++ {
  907. //gets all requested tweets
  908. if archiveQuerys == nil {
  909. tweets[i] = lib.GetTweets(clientKeys.PirQuery[i], dataLength, 0, *clientKeys.PublicKey)
  910. } else {
  911. tweets[i] = lib.GetTweets(archiveQuerys[i], dataLength, 1, *clientKeys.PublicKey)
  912. }
  913. //expand sharedSecret so it is of right length
  914. expandBy := len(tweets[i]) / 32
  915. var expandedSharedSecret []byte
  916. for i := 0; i < expandBy; i++ {
  917. expandedSharedSecret = append(expandedSharedSecret, clientKeys.SharedSecret[:]...)
  918. }
  919. //Xor's sharedSecret with all tweets
  920. lib.Xor(expandedSharedSecret[:], tweets[i])
  921. //fmt.Println(tweets[0])
  922. blockLength := len(tweets[i])
  923. receivedTweets, _ := readFrom(followerConnection, blockLength, nil, 0)
  924. //fmt.Println("receivedTweets", blockLength, len(receivedTweets))
  925. //fmt.Println("pubKey", *clientKeys.PublicKey, "Bytes", tweets, "follower", receivedTweets)
  926. lib.Xor(receivedTweets, tweets[i])
  927. }
  928. //sends tweets to client
  929. for i := 0; i < tmpNeededSubscriptions; i++ {
  930. tweetsLengthBytes := intToByte(len(tweets[i]))
  931. errorBool := writeToWError(clientConnection, tweetsLengthBytes, followerConnection, 2)
  932. if errorBool {
  933. return true
  934. }
  935. errorBool = writeToWError(clientConnection, tweets[i], followerConnection, 2)
  936. if errorBool {
  937. return true
  938. }
  939. }
  940. return false
  941. }
  942. func handlePirQuery(clientKeys clientKeys, clientConnection net.Conn, followerConnection net.Conn, subPhase int, doAuditing bool) (clientKeys, [][]byte, bool) {
  943. clientPublicKey := clientKeys.PublicKey
  944. //gets the msg length
  945. msgLengthBytes, errorBool := readFrom(clientConnection, 4, followerConnection, 5)
  946. if errorBool {
  947. return clientKeys, nil, true
  948. }
  949. msgLength := byteToInt(msgLengthBytes)
  950. //gets the leader box
  951. leaderBox, errorBool := readFrom(clientConnection, msgLength, followerConnection, 5)
  952. if errorBool {
  953. return clientKeys, nil, true
  954. }
  955. //gets the follower box
  956. followerBox, errorBool := readFrom(clientConnection, msgLength, followerConnection, 5)
  957. if errorBool {
  958. return clientKeys, nil, true
  959. }
  960. //todo! repeat for archive
  961. tmpNeededSubscriptions := neededSubscriptions
  962. if tmpNeededSubscriptions > topicAmount {
  963. tmpNeededSubscriptions = topicAmount
  964. }
  965. tmpTopicAmount := topicAmount
  966. if subPhase == -1 {
  967. archiveNeededSubscriptions, errorBool := readFrom(clientConnection, 4, followerConnection, 5)
  968. if errorBool {
  969. return clientKeys, nil, true
  970. }
  971. writeToWError(followerConnection, archiveNeededSubscriptions, nil, 0)
  972. tmpNeededSubscriptions = byteToInt(archiveNeededSubscriptions)
  973. tmpTopicAmount = archiveTopicAmount
  974. }
  975. if doAuditing {
  976. tmpNeededSubscriptions = 1
  977. tmpTopicAmount = int(dbWriteSize)
  978. }
  979. //send length to follower
  980. writeToWError(followerConnection, msgLengthBytes, nil, 0)
  981. //send box to follower
  982. writeToWError(followerConnection, followerBox, nil, 0)
  983. var decryptNonce [24]byte
  984. copy(decryptNonce[:], leaderBox[:24])
  985. decrypted, ok := box.Open(nil, leaderBox[24:], &decryptNonce, clientPublicKey, leaderPrivateKey)
  986. if !ok {
  987. fmt.Println("pirQuery decryption not ok")
  988. return clientKeys, nil, true
  989. }
  990. //if sharedSecret is send
  991. if subPhase == 0 {
  992. var tmpSharedSecret [32]byte
  993. for index := 0; index < 32; index++ {
  994. tmpSharedSecret[index] = decrypted[index]
  995. }
  996. clientKeys.SharedSecret = tmpSharedSecret
  997. decrypted = decrypted[32:]
  998. }
  999. if doAuditing {
  1000. result := make([][]byte, 1)
  1001. result[0] = decrypted
  1002. return clientKeys, result, false
  1003. }
  1004. //transforms byteArray to ints of wanted topics
  1005. pirQueryFlattened := decrypted
  1006. pirQuerys := make([][]byte, tmpNeededSubscriptions)
  1007. for i := range pirQuerys {
  1008. pirQuerys[i] = make([]byte, tmpTopicAmount)
  1009. }
  1010. for i := 0; i < tmpNeededSubscriptions; i++ {
  1011. pirQuerys[i] = pirQueryFlattened[i*tmpTopicAmount : (i+1)*tmpTopicAmount]
  1012. }
  1013. //sets the pirQuery for the client in case whe are not archiving, and not Auditing
  1014. if subPhase != -1 {
  1015. clientKeys.PirQuery = pirQuerys
  1016. }
  1017. return clientKeys, pirQuerys, false
  1018. }
  1019. func transformBytesToStringArray(topicsAsBytes []byte) []string {
  1020. var topics []string
  1021. var topic string
  1022. var position int = 0
  1023. for _, letter := range topicsAsBytes {
  1024. if string(letter) == "," {
  1025. topics[position] = topic
  1026. topic = ""
  1027. position++
  1028. } else {
  1029. topic = topic + string(letter)
  1030. }
  1031. }
  1032. return topics
  1033. }
  1034. func byteToInt(myBytes []byte) (x int) {
  1035. x = int(myBytes[3])<<24 + int(myBytes[2])<<16 + int(myBytes[1])<<8 + int(myBytes[0])
  1036. return
  1037. }
  1038. //returns true if error occured
  1039. func sendTopicLists(clientConnection, followerConnection net.Conn, setup bool) bool {
  1040. for i := 0; i < 2; i++ {
  1041. var topicList []byte
  1042. if i == 0 {
  1043. topicList, topicAmount = lib.GetTopicList(i)
  1044. } else {
  1045. topicList, archiveTopicAmount = lib.GetTopicList(i)
  1046. }
  1047. topicListLengthBytes := intToByte(len(topicList))
  1048. if !setup {
  1049. err := writeToWError(clientConnection, topicListLengthBytes, followerConnection, 5)
  1050. if err {
  1051. return true
  1052. }
  1053. err = writeToWError(clientConnection, topicList, followerConnection, 5)
  1054. if err {
  1055. return true
  1056. }
  1057. } else {
  1058. _, err := clientConnection.Write(topicListLengthBytes)
  1059. if err != nil {
  1060. return true
  1061. }
  1062. _, err = clientConnection.Write(topicList)
  1063. if err != nil {
  1064. return true
  1065. }
  1066. }
  1067. }
  1068. return false
  1069. }
  1070. //sends the array to the connection
  1071. func writeTo(connection net.Conn, array []byte) {
  1072. remainingLength := len(array)
  1073. for remainingLength > 0 {
  1074. if remainingLength >= mtu {
  1075. _, err := connection.Write(array[:mtu])
  1076. if err != nil {
  1077. panic(err)
  1078. }
  1079. array = array[mtu:]
  1080. remainingLength -= mtu
  1081. } else {
  1082. _, err := connection.Write(array)
  1083. if err != nil {
  1084. panic(err)
  1085. }
  1086. remainingLength = 0
  1087. }
  1088. }
  1089. }
  1090. func writeToWError(connection net.Conn, array []byte, followerConnection net.Conn, size int) bool {
  1091. if connection.RemoteAddr().String() == follower {
  1092. arrayWError := make([]byte, 1)
  1093. arrayWError = append(arrayWError, array[:]...)
  1094. remainingLength := len(arrayWError)
  1095. for remainingLength > 0 {
  1096. if remainingLength >= mtu {
  1097. _, err := connection.Write(arrayWError[:mtu])
  1098. if err != nil {
  1099. return handleError(connection, followerConnection, size, err)
  1100. }
  1101. arrayWError = arrayWError[mtu:]
  1102. remainingLength -= mtu
  1103. } else {
  1104. _, err := connection.Write(arrayWError)
  1105. if err != nil {
  1106. return handleError(connection, followerConnection, size, err)
  1107. }
  1108. remainingLength = 0
  1109. }
  1110. }
  1111. } else {
  1112. remainingLength := len(array)
  1113. for remainingLength > 0 {
  1114. if remainingLength >= mtu {
  1115. _, err := connection.Write(array[:mtu])
  1116. if err != nil {
  1117. return handleError(connection, followerConnection, size, err)
  1118. }
  1119. array = array[mtu:]
  1120. remainingLength -= mtu
  1121. } else {
  1122. _, err := connection.Write(array)
  1123. if err != nil {
  1124. return handleError(connection, followerConnection, size, err)
  1125. }
  1126. remainingLength = 0
  1127. }
  1128. }
  1129. }
  1130. return false
  1131. }
  1132. func handleError(connection, followerConnection net.Conn, size int, err error) bool {
  1133. if err != nil {
  1134. //lets follower know that client has disconnected unexpectedly
  1135. if connection.RemoteAddr().String() != follower {
  1136. if size > mtu {
  1137. fmt.Println("have a look here")
  1138. }
  1139. fmt.Println("error", err)
  1140. array := make([]byte, size)
  1141. array[0] = 1
  1142. _, err = followerConnection.Write(array)
  1143. if err != nil {
  1144. panic(err)
  1145. }
  1146. return true
  1147. } else {
  1148. panic(err)
  1149. }
  1150. }
  1151. return false
  1152. }
  1153. //reads an array which is returned and of size "size" from the connection
  1154. //returns true if error occured
  1155. func readFrom(connection net.Conn, size int, followerConnection net.Conn, sizeError int) ([]byte, bool) {
  1156. var array []byte
  1157. remainingSize := size
  1158. for remainingSize > 0 {
  1159. var err error
  1160. toAppend := make([]byte, mtu)
  1161. if remainingSize > mtu {
  1162. _, err = connection.Read(toAppend)
  1163. array = append(array, toAppend...)
  1164. remainingSize -= mtu
  1165. } else {
  1166. _, err = connection.Read(toAppend[:remainingSize])
  1167. array = append(array, toAppend[:remainingSize]...)
  1168. remainingSize = 0
  1169. }
  1170. if err != nil {
  1171. //lets follower know that client has disconnected unexpectedly
  1172. if connection.RemoteAddr().String() != follower {
  1173. fmt.Println(err)
  1174. array := make([]byte, sizeError)
  1175. array[0] = 1
  1176. _, err = followerConnection.Write(array)
  1177. if err != nil {
  1178. panic(err)
  1179. }
  1180. return nil, true
  1181. } else {
  1182. panic(err)
  1183. }
  1184. }
  1185. }
  1186. return array, false
  1187. }
  1188. func intToByte(myInt int) (retBytes []byte) {
  1189. retBytes = make([]byte, 4)
  1190. retBytes[3] = byte((myInt >> 24) & 0xff)
  1191. retBytes[2] = byte((myInt >> 16) & 0xff)
  1192. retBytes[1] = byte((myInt >> 8) & 0xff)
  1193. retBytes[0] = byte(myInt & 0xff)
  1194. return
  1195. }