leader.go 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421
  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. import (
  10. "crypto/rand"
  11. "crypto/rsa"
  12. "crypto/sha256"
  13. "crypto/tls"
  14. "crypto/x509"
  15. "crypto/x509/pkix"
  16. "encoding/pem"
  17. "fmt"
  18. "math"
  19. "math/big"
  20. mr "math/rand"
  21. "net"
  22. "sort"
  23. "strconv"
  24. "strings"
  25. "sync"
  26. "time"
  27. lib "2PPS/lib"
  28. "unsafe"
  29. "golang.org/x/crypto/nacl/box"
  30. )
  31. //this stores all neccessary information for each client
  32. type clientKeys struct {
  33. roundsParticipating int
  34. PublicKey *[32]byte
  35. SharedSecret [32]byte
  36. PirQuery [][]byte
  37. }
  38. var clientData = make(map[net.Addr]clientKeys)
  39. const follower string = "127.0.0.1:4442"
  40. //Maximum Transport Unit
  41. const mtu int = 1100
  42. var leaderPrivateKey *[32]byte
  43. var leaderPublicKey *[32]byte
  44. var followerPublicKey *[32]byte
  45. const maxNumberOfClients = 10000000
  46. var topicList []byte
  47. var topicAmount int
  48. var archiveTopicAmount int
  49. // every roundsBeforeUpdate the client updates his pirQuery
  50. const roundsBeforeUpdate = 3
  51. const neededSubscriptions = 4
  52. const numThreads = 12
  53. const dataLength = 256
  54. const minDBWriteSize = 1000
  55. var dbWriteSize float64 = 10000
  56. var collisionCounter []float64
  57. var clientsConnected int
  58. var maxTimePerRound time.Duration = 10 * time.Second
  59. var clientsServedPhase1 []int
  60. var clientsServedPhase3 []int
  61. var startPhase1 time.Time
  62. var startPhase2 time.Time
  63. var startPhase3 time.Time
  64. //counts the number of rounds
  65. var round int = 0
  66. var startTime time.Time
  67. var startTimeRound time.Time
  68. //channel for goroutine communication with clients
  69. var phase1Channel = make(chan net.Conn, maxNumberOfClients)
  70. var phase3Channel = make(chan net.Conn, maxNumberOfClients)
  71. //variables for calculating the dbWrite size
  72. const publisherRounds int = 10
  73. var publisherAmount float64
  74. var publisherHistory [publisherRounds]int
  75. func main() {
  76. //prevents race conditions for wrtiting
  77. m := &sync.RWMutex{}
  78. startTime = time.Now()
  79. clientsServedPhase1 = make([]int, 1000)
  80. clientsServedPhase3 = make([]int, 1000)
  81. generatedPublicKey, generatedPrivateKey, err := box.GenerateKey(rand.Reader)
  82. if err != nil {
  83. panic(err)
  84. }
  85. //why is this neccessary?
  86. leaderPrivateKey = generatedPrivateKey
  87. leaderPublicKey = generatedPublicKey
  88. C.initializeServer(C.int(numThreads))
  89. //calls follower for setup
  90. conf := &tls.Config{
  91. InsecureSkipVerify: true,
  92. }
  93. followerConnection, err := tls.Dial("tcp", follower, conf)
  94. if err != nil {
  95. panic(err)
  96. }
  97. followerConnection.SetDeadline(time.Time{})
  98. //receives follower publicKey
  99. var tmpFollowerPubKey [32]byte
  100. _, err = followerConnection.Read(tmpFollowerPubKey[:])
  101. if err != nil {
  102. panic(err)
  103. }
  104. followerPublicKey = &tmpFollowerPubKey
  105. //send publicKey to follower
  106. writeTo(followerConnection, leaderPublicKey[:])
  107. writeTo(followerConnection, intToByte(neededSubscriptions))
  108. //goroutine for accepting new clients
  109. go func() {
  110. leaderConnectionPrivateKey, err := rsa.GenerateKey(rand.Reader, 2048)
  111. if err != nil {
  112. panic(err)
  113. }
  114. // Generate a pem block with the private key
  115. keyPem := pem.EncodeToMemory(&pem.Block{
  116. Type: "RSA PRIVATE KEY",
  117. Bytes: x509.MarshalPKCS1PrivateKey(leaderConnectionPrivateKey),
  118. })
  119. tml := x509.Certificate{
  120. // you can add any attr that you need
  121. NotBefore: time.Now(),
  122. NotAfter: time.Now().AddDate(5, 0, 0),
  123. // you have to generate a different serial number each execution
  124. SerialNumber: big.NewInt(123123),
  125. Subject: pkix.Name{
  126. CommonName: "New Name",
  127. Organization: []string{"New Org."},
  128. },
  129. BasicConstraintsValid: true,
  130. }
  131. cert, err := x509.CreateCertificate(rand.Reader, &tml, &tml, &leaderConnectionPrivateKey.PublicKey, leaderConnectionPrivateKey)
  132. if err != nil {
  133. panic(err)
  134. }
  135. // Generate a pem block with the certificate
  136. certPem := pem.EncodeToMemory(&pem.Block{
  137. Type: "CERTIFICATE",
  138. Bytes: cert,
  139. })
  140. tlsCert, err := tls.X509KeyPair(certPem, keyPem)
  141. if err != nil {
  142. panic(err)
  143. }
  144. config := &tls.Config{Certificates: []tls.Certificate{tlsCert}}
  145. //listens for clients
  146. lnClients, err := tls.Listen("tcp", ":4441", config)
  147. if err != nil {
  148. panic(err)
  149. }
  150. defer lnClients.Close()
  151. for {
  152. clientConnection, err := lnClients.Accept()
  153. if err != nil {
  154. fmt.Println("Client connection error 1", err)
  155. clientConnection.Close()
  156. break
  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("Client connection error 2", err)
  168. clientConnection.Close()
  169. break
  170. }
  171. //send follower publicKey
  172. _, err = clientConnection.Write(followerPublicKey[:])
  173. if err != nil {
  174. fmt.Println("Client connection error 3", 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("Client connection error 4", err)
  184. clientConnection.Close()
  185. break
  186. }
  187. _, err = clientConnection.Write(intToByte(neededSubscriptions))
  188. if err != nil {
  189. fmt.Println("Client connection error 5", err)
  190. clientConnection.Close()
  191. break
  192. }
  193. _, err = clientConnection.Write(intToByte(int(startTime.Unix())))
  194. if err != nil {
  195. fmt.Println("Client connection error 6", 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. //if topics are
  585. //int
  586. //topic = topic + fmt.Sprint(int(letter))
  587. //string
  588. topic = topic + string(letter)
  589. }
  590. } else if position == 1 {
  591. text = text + string(letter)
  592. }
  593. }
  594. }
  595. tweet := lib.Tweet{"", -1, topics, text, round}
  596. if text != "" {
  597. tweets = append(tweets, tweet)
  598. } else {
  599. //this is a odd(number) way collisions
  600. collisions++
  601. }
  602. }
  603. }
  604. collisionCounter = append(collisionCounter, collisions)
  605. if collisions/dbWriteSize > 0.05 {
  606. fmt.Println("Collision % this round", collisions/dbWriteSize, "dbWriteSize", dbWriteSize)
  607. }
  608. //fmt.Println("tweets recovered: ", tweets)
  609. //sort into read db
  610. //fmt.Println("newTweets", tweets)
  611. lib.NewEntries(tweets, 0)
  612. C.resetDb()
  613. //calculates the publisherAverage over the last publisherRounds rounds
  614. index := round % publisherRounds
  615. publisherHistory[index] = currentPublisherAmount
  616. fmt.Println("currentPublisherAmount", currentPublisherAmount)
  617. var publisherAmount int
  618. for _, num := range publisherHistory {
  619. publisherAmount += num
  620. }
  621. publisherAverage := 0
  622. if round < publisherRounds {
  623. publisherAverage = publisherAmount / round
  624. } else {
  625. publisherAverage = publisherAmount / publisherRounds
  626. }
  627. //calculates the dbWriteSize for this round
  628. dbWriteSize = math.Ceil(19.5 * float64(publisherAverage))
  629. if dbWriteSize < minDBWriteSize {
  630. dbWriteSize = minDBWriteSize
  631. }
  632. //writes dbWriteSize of current round to follower
  633. writeTo(followerConnection, intToByte(int(dbWriteSize)))
  634. lib.CleanUpdbR(round)
  635. }
  636. func addTestTweets() {
  637. //creates test tweets
  638. tweets := make([]lib.Tweet, 5)
  639. for i := range tweets {
  640. j := i
  641. if i == 1 {
  642. j = 0
  643. }
  644. text := "Text " + strconv.Itoa(i)
  645. var topics []string
  646. topics = append(topics, "Topic "+strconv.Itoa(j))
  647. tweets[i] = lib.Tweet{"", -1, topics, text, i}
  648. }
  649. lib.NewEntries(tweets, 0)
  650. }
  651. //opti! mb it is quicker to send updated topicLists to clients first so pirQuerys are ready
  652. func phase3(id int, phase []byte, followerConnection net.Conn, wg *sync.WaitGroup, m *sync.RWMutex) {
  653. gotClient := make([]byte, 1)
  654. gotClient[0] = 0
  655. //wait until time is up
  656. for len(phase3Channel) == 0 {
  657. if time.Since(startTimeRound) > maxTimePerRound*2 {
  658. //tells follower that this worker is done
  659. writeToWError(followerConnection, gotClient, nil, 0)
  660. wg.Done()
  661. return
  662. }
  663. time.Sleep(1 * time.Second)
  664. }
  665. for clientConnection := range phase3Channel {
  666. clientsServedPhase3[round] = clientsServedPhase3[round] + 1
  667. if clientsServedPhase3[round]%1000 == 0 {
  668. fmt.Println("clientsServedPhase3", clientsServedPhase3[round])
  669. fmt.Println("timeTaken", time.Since(startPhase3).Seconds())
  670. }
  671. gotClient[0] = 1
  672. //tells follower that this worker got a clientConnection
  673. writeToWError(followerConnection, gotClient, nil, 0)
  674. //tells client current phase
  675. errorBool := writeToWError(clientConnection, phase, followerConnection, 2)
  676. if errorBool {
  677. contBool := handleClientDC(wg, followerConnection, phase3Channel)
  678. if contBool {
  679. continue
  680. } else {
  681. return
  682. }
  683. }
  684. /*
  685. possible Values
  686. 0 : new client
  687. leader expects sharedSecrets, expects pirQuery
  688. 1 : update needed
  689. leader sends topicList, performs local update of sharedSecret, expects pirQuery
  690. 2 : no update needed
  691. nothing
  692. */
  693. subPhase := make([]byte, 1)
  694. //gets the data for the current client
  695. m.RLock()
  696. var clientKeys = clientData[clientConnection.RemoteAddr()]
  697. m.RUnlock()
  698. var roundsParticipating = clientKeys.roundsParticipating
  699. //client participates for the first time
  700. if roundsParticipating == 0 {
  701. subPhase[0] = 0
  702. } else if roundsParticipating%roundsBeforeUpdate == 0 {
  703. subPhase[0] = 1
  704. } else {
  705. subPhase[0] = 2
  706. }
  707. //tells client what leader expects
  708. errorBool = writeToWError(clientConnection, subPhase, followerConnection, 2)
  709. if errorBool {
  710. contBool := handleClientDC(wg, followerConnection, phase3Channel)
  711. if contBool {
  712. continue
  713. } else {
  714. return
  715. }
  716. }
  717. //tells follower what will happen
  718. writeToWError(followerConnection, subPhase, nil, 0)
  719. //sends clients publicKey so follower knows which client is being served
  720. writeTo(followerConnection, clientKeys.PublicKey[:])
  721. //increases rounds participating for client
  722. clientKeys.roundsParticipating = roundsParticipating + 1
  723. //declaring variables here to prevent dupclicates later
  724. m.RLock()
  725. var sharedSecret [32]byte = clientData[clientConnection.RemoteAddr()].SharedSecret
  726. m.RUnlock()
  727. if subPhase[0] == 0 {
  728. errorBool := sendTopicLists(clientConnection, followerConnection, false)
  729. if errorBool {
  730. contBool := handleClientDC(wg, followerConnection, phase3Channel)
  731. if contBool {
  732. continue
  733. } else {
  734. return
  735. }
  736. }
  737. clientKeys, _, errorBool = handlePirQuery(clientKeys, clientConnection, followerConnection, int(subPhase[0]), false)
  738. if errorBool {
  739. contBool := handleClientDC(wg, followerConnection, phase3Channel)
  740. if contBool {
  741. continue
  742. } else {
  743. return
  744. }
  745. }
  746. } else if subPhase[0] == 1 {
  747. errorBool := sendTopicLists(clientConnection, followerConnection, false)
  748. if errorBool {
  749. contBool := handleClientDC(wg, followerConnection, phase3Channel)
  750. if contBool {
  751. continue
  752. } else {
  753. return
  754. }
  755. }
  756. //updates sharedSecret
  757. sharedSecret = sha256.Sum256(sharedSecret[:])
  758. clientKeys.SharedSecret = sharedSecret
  759. clientKeys, _, errorBool = handlePirQuery(clientKeys, clientConnection, followerConnection, int(subPhase[0]), false)
  760. if errorBool {
  761. contBool := handleClientDC(wg, followerConnection, phase3Channel)
  762. if contBool {
  763. continue
  764. } else {
  765. return
  766. }
  767. }
  768. }
  769. errorBool = getSendTweets(clientKeys, nil, clientConnection, followerConnection)
  770. if errorBool {
  771. contBool := handleClientDC(wg, followerConnection, phase3Channel)
  772. if contBool {
  773. continue
  774. } else {
  775. return
  776. }
  777. }
  778. wantsArchive, errorBool := readFrom(clientConnection, 1, followerConnection, 2)
  779. if errorBool {
  780. contBool := handleClientDC(wg, followerConnection, phase3Channel)
  781. if contBool {
  782. continue
  783. } else {
  784. return
  785. }
  786. }
  787. writeToWError(followerConnection, wantsArchive, nil, 0)
  788. if wantsArchive[0] == 1 && archiveTopicAmount > 0 {
  789. _, archiveQuerys, errorBool := handlePirQuery(clientKeys, clientConnection, followerConnection, -1, false)
  790. if errorBool {
  791. contBool := handleClientDC(wg, followerConnection, phase3Channel)
  792. if contBool {
  793. continue
  794. } else {
  795. return
  796. }
  797. }
  798. errorBool = getSendTweets(clientKeys, archiveQuerys, clientConnection, followerConnection)
  799. if errorBool {
  800. contBool := handleClientDC(wg, followerConnection, phase3Channel)
  801. if contBool {
  802. continue
  803. } else {
  804. return
  805. }
  806. }
  807. }
  808. //saves all changes for client
  809. m.Lock()
  810. clientData[clientConnection.RemoteAddr()] = clientKeys
  811. m.Unlock()
  812. phase1Channel <- clientConnection
  813. for {
  814. if time.Since(startTimeRound) < 2*maxTimePerRound {
  815. //this worker handles the next client
  816. if len(phase3Channel) > 0 {
  817. break
  818. //this worker waits for next client
  819. } else {
  820. time.Sleep(1 * time.Second)
  821. }
  822. //times up
  823. } else {
  824. //tells follower that this worker is done
  825. gotClient[0] = 0
  826. writeToWError(followerConnection, gotClient, nil, 0)
  827. wg.Done()
  828. return
  829. }
  830. }
  831. }
  832. }
  833. //returns true if there is another client
  834. func handleClientDC(wg *sync.WaitGroup, followerConnection net.Conn, channel chan net.Conn) bool {
  835. //loop that waits for new client or leaves phase1 if time is up
  836. for {
  837. if time.Since(startTimeRound) < maxTimePerRound {
  838. //this worker handles the next client
  839. if len(channel) > 0 {
  840. return true
  841. //this worker waits for next client
  842. } else {
  843. time.Sleep(1 * time.Second)
  844. }
  845. //times up
  846. } else {
  847. //tells follower that this worker is done
  848. gotClient := make([]byte, 1)
  849. gotClient[0] = 0
  850. writeTo(followerConnection, gotClient)
  851. wg.Done()
  852. return false
  853. }
  854. }
  855. }
  856. func createVirtualAddresses() []int {
  857. //array will be filled with unique random ascending values
  858. //adapted from: https://stackoverflow.com/questions/20039025/java-array-of-unique-randomly-generated-integers
  859. //+1 to have a position to evaluate each received message
  860. arraySize := int(dbWriteSize) + 1
  861. var maxInt int = int(math.Pow(2, 31))
  862. virtualAddresses := make([]int, arraySize)
  863. for i := 0; i < arraySize; i++ {
  864. virtualAddresses[i] = mr.Intn(maxInt)
  865. for j := 0; j < i; j++ {
  866. if virtualAddresses[i] == virtualAddresses[j] {
  867. i--
  868. break
  869. }
  870. }
  871. }
  872. sort.Ints(virtualAddresses)
  873. return virtualAddresses
  874. }
  875. func getSendVirtualAddress(pirQuery []byte, virtualAddresses []int, sharedSecret [32]byte, clientConnection, followerConnection net.Conn) bool {
  876. //xores all requested addresses into virtuallAddress
  877. virtualAddress := make([]byte, 4)
  878. for index, num := range pirQuery {
  879. if num == 1 {
  880. currentAddress := intToByte(virtualAddresses[index])
  881. for i := 0; i < 4; i++ {
  882. virtualAddress[i] = virtualAddress[i] ^ currentAddress[i]
  883. }
  884. }
  885. }
  886. //xores the sharedSecret
  887. for i := 0; i < 4; i++ {
  888. virtualAddress[i] = virtualAddress[i] ^ sharedSecret[i]
  889. }
  890. virtualAddressFollower, _ := readFrom(followerConnection, 4, nil, 0)
  891. //xores the data from follower
  892. for i := 0; i < 4; i++ {
  893. virtualAddress[i] = virtualAddress[i] ^ virtualAddressFollower[i]
  894. }
  895. errorBool := writeToWError(clientConnection, virtualAddress, followerConnection, 5)
  896. return errorBool
  897. }
  898. func getSendTweets(clientKeys clientKeys, archiveQuerys [][]byte, clientConnection, followerConnection net.Conn) bool {
  899. tmpNeededSubscriptions := neededSubscriptions
  900. if tmpNeededSubscriptions > topicAmount {
  901. tmpNeededSubscriptions = topicAmount
  902. }
  903. if archiveQuerys != nil {
  904. tmpNeededSubscriptions = len(archiveQuerys)
  905. if tmpNeededSubscriptions > archiveTopicAmount {
  906. tmpNeededSubscriptions = archiveTopicAmount
  907. }
  908. }
  909. //fmt.Println("tmpNeededSubscriptions", tmpNeededSubscriptions)
  910. tweets := make([][]byte, tmpNeededSubscriptions)
  911. for i := 0; i < tmpNeededSubscriptions; i++ {
  912. //gets all requested tweets
  913. if archiveQuerys == nil {
  914. tweets[i] = lib.GetTweets(clientKeys.PirQuery[i], dataLength, 0, *clientKeys.PublicKey)
  915. } else {
  916. tweets[i] = lib.GetTweets(archiveQuerys[i], dataLength, 1, *clientKeys.PublicKey)
  917. }
  918. //expand sharedSecret so it is of right length
  919. expandBy := len(tweets[i]) / 32
  920. var expandedSharedSecret []byte
  921. for i := 0; i < expandBy; i++ {
  922. expandedSharedSecret = append(expandedSharedSecret, clientKeys.SharedSecret[:]...)
  923. }
  924. //Xor's sharedSecret with all tweets
  925. lib.Xor(expandedSharedSecret[:], tweets[i])
  926. //fmt.Println(tweets[0])
  927. blockLength := len(tweets[i])
  928. receivedTweets, _ := readFrom(followerConnection, blockLength, nil, 0)
  929. //fmt.Println("receivedTweets", blockLength, len(receivedTweets))
  930. //fmt.Println("pubKey", *clientKeys.PublicKey, "Bytes", tweets, "follower", receivedTweets)
  931. lib.Xor(receivedTweets, tweets[i])
  932. }
  933. //sends tweets to client
  934. for i := 0; i < tmpNeededSubscriptions; i++ {
  935. tweetsLengthBytes := intToByte(len(tweets[i]))
  936. errorBool := writeToWError(clientConnection, tweetsLengthBytes, followerConnection, 2)
  937. if errorBool {
  938. return true
  939. }
  940. errorBool = writeToWError(clientConnection, tweets[i], followerConnection, 2)
  941. if errorBool {
  942. return true
  943. }
  944. }
  945. return false
  946. }
  947. func handlePirQuery(clientKeys clientKeys, clientConnection net.Conn, followerConnection net.Conn, subPhase int, doAuditing bool) (clientKeys, [][]byte, bool) {
  948. clientPublicKey := clientKeys.PublicKey
  949. //gets the msg length
  950. msgLengthBytes, errorBool := readFrom(clientConnection, 4, followerConnection, 5)
  951. if errorBool {
  952. return clientKeys, nil, true
  953. }
  954. msgLength := byteToInt(msgLengthBytes)
  955. //gets the leader box
  956. leaderBox, errorBool := readFrom(clientConnection, msgLength, followerConnection, 5)
  957. if errorBool {
  958. return clientKeys, nil, true
  959. }
  960. //gets the follower box
  961. followerBox, errorBool := readFrom(clientConnection, msgLength, followerConnection, 5)
  962. if errorBool {
  963. return clientKeys, nil, true
  964. }
  965. tmpNeededSubscriptions := neededSubscriptions
  966. if tmpNeededSubscriptions > topicAmount {
  967. tmpNeededSubscriptions = topicAmount
  968. }
  969. tmpTopicAmount := topicAmount
  970. if subPhase == -1 {
  971. archiveNeededSubscriptions, errorBool := readFrom(clientConnection, 4, followerConnection, 5)
  972. if errorBool {
  973. return clientKeys, nil, true
  974. }
  975. writeToWError(followerConnection, archiveNeededSubscriptions, nil, 0)
  976. tmpNeededSubscriptions = byteToInt(archiveNeededSubscriptions)
  977. tmpTopicAmount = archiveTopicAmount
  978. if tmpNeededSubscriptions > archiveTopicAmount {
  979. tmpNeededSubscriptions = archiveTopicAmount
  980. }
  981. }
  982. if doAuditing {
  983. tmpNeededSubscriptions = 1
  984. tmpTopicAmount = int(dbWriteSize)
  985. }
  986. //send length to follower
  987. writeToWError(followerConnection, msgLengthBytes, nil, 0)
  988. //send box to follower
  989. writeToWError(followerConnection, followerBox, nil, 0)
  990. var decryptNonce [24]byte
  991. copy(decryptNonce[:], leaderBox[:24])
  992. decrypted, ok := box.Open(nil, leaderBox[24:], &decryptNonce, clientPublicKey, leaderPrivateKey)
  993. if !ok {
  994. fmt.Println("pirQuery decryption not ok")
  995. return clientKeys, nil, true
  996. }
  997. //if sharedSecret is send
  998. if subPhase == 0 {
  999. var tmpSharedSecret [32]byte
  1000. for index := 0; index < 32; index++ {
  1001. tmpSharedSecret[index] = decrypted[index]
  1002. }
  1003. clientKeys.SharedSecret = tmpSharedSecret
  1004. decrypted = decrypted[32:]
  1005. }
  1006. if doAuditing {
  1007. result := make([][]byte, 1)
  1008. result[0] = decrypted
  1009. return clientKeys, result, false
  1010. }
  1011. if subPhase == -1 {
  1012. }
  1013. //transforms byteArray to ints of wanted topics
  1014. pirQueryFlattened := decrypted
  1015. pirQuerys := make([][]byte, tmpNeededSubscriptions)
  1016. for i := range pirQuerys {
  1017. pirQuerys[i] = make([]byte, tmpTopicAmount)
  1018. }
  1019. for i := 0; i < tmpNeededSubscriptions; i++ {
  1020. pirQuerys[i] = pirQueryFlattened[i*tmpTopicAmount : (i+1)*tmpTopicAmount]
  1021. }
  1022. //sets the pirQuery for the client in case whe are not archiving, and not Auditing
  1023. if subPhase != -1 {
  1024. clientKeys.PirQuery = pirQuerys
  1025. }
  1026. return clientKeys, pirQuerys, false
  1027. }
  1028. func transformBytesToStringArray(topicsAsBytes []byte) []string {
  1029. var topics []string
  1030. var topic string
  1031. var position int = 0
  1032. for _, letter := range topicsAsBytes {
  1033. if string(letter) == "," {
  1034. topics[position] = topic
  1035. topic = ""
  1036. position++
  1037. } else {
  1038. topic = topic + string(letter)
  1039. }
  1040. }
  1041. return topics
  1042. }
  1043. func byteToInt(myBytes []byte) (x int) {
  1044. x = int(myBytes[3])<<24 + int(myBytes[2])<<16 + int(myBytes[1])<<8 + int(myBytes[0])
  1045. return
  1046. }
  1047. //returns true if error occured
  1048. func sendTopicLists(clientConnection, followerConnection net.Conn, setup bool) bool {
  1049. for i := 0; i < 2; i++ {
  1050. var topicList []byte
  1051. if i == 0 {
  1052. topicList, topicAmount = lib.GetTopicList(i)
  1053. } else {
  1054. topicList, archiveTopicAmount = lib.GetTopicList(i)
  1055. }
  1056. topicListLengthBytes := intToByte(len(topicList))
  1057. if !setup {
  1058. err := writeToWError(clientConnection, topicListLengthBytes, followerConnection, 5)
  1059. if err {
  1060. return true
  1061. }
  1062. err = writeToWError(clientConnection, topicList, followerConnection, 5)
  1063. if err {
  1064. return true
  1065. }
  1066. } else {
  1067. _, err := clientConnection.Write(topicListLengthBytes)
  1068. if err != nil {
  1069. return true
  1070. }
  1071. _, err = clientConnection.Write(topicList)
  1072. if err != nil {
  1073. return true
  1074. }
  1075. }
  1076. }
  1077. return false
  1078. }
  1079. //sends the array to the connection
  1080. func writeTo(connection net.Conn, array []byte) {
  1081. remainingLength := len(array)
  1082. for remainingLength > 0 {
  1083. if remainingLength >= mtu {
  1084. _, err := connection.Write(array[:mtu])
  1085. if err != nil {
  1086. panic(err)
  1087. }
  1088. array = array[mtu:]
  1089. remainingLength -= mtu
  1090. } else {
  1091. _, err := connection.Write(array)
  1092. if err != nil {
  1093. panic(err)
  1094. }
  1095. remainingLength = 0
  1096. }
  1097. }
  1098. }
  1099. func writeToWError(connection net.Conn, array []byte, followerConnection net.Conn, size int) bool {
  1100. if connection.RemoteAddr().String() == follower {
  1101. arrayWError := make([]byte, 1)
  1102. arrayWError = append(arrayWError, array[:]...)
  1103. remainingLength := len(arrayWError)
  1104. for remainingLength > 0 {
  1105. if remainingLength >= mtu {
  1106. _, err := connection.Write(arrayWError[:mtu])
  1107. if err != nil {
  1108. return handleError(connection, followerConnection, size, err)
  1109. }
  1110. arrayWError = arrayWError[mtu:]
  1111. remainingLength -= mtu
  1112. } else {
  1113. _, err := connection.Write(arrayWError)
  1114. if err != nil {
  1115. return handleError(connection, followerConnection, size, err)
  1116. }
  1117. remainingLength = 0
  1118. }
  1119. }
  1120. } else {
  1121. remainingLength := len(array)
  1122. for remainingLength > 0 {
  1123. if remainingLength >= mtu {
  1124. _, err := connection.Write(array[:mtu])
  1125. if err != nil {
  1126. return handleError(connection, followerConnection, size, err)
  1127. }
  1128. array = array[mtu:]
  1129. remainingLength -= mtu
  1130. } else {
  1131. _, err := connection.Write(array)
  1132. if err != nil {
  1133. return handleError(connection, followerConnection, size, err)
  1134. }
  1135. remainingLength = 0
  1136. }
  1137. }
  1138. }
  1139. return false
  1140. }
  1141. func handleError(connection, followerConnection net.Conn, size int, err error) bool {
  1142. if err != nil {
  1143. //lets follower know that client has disconnected unexpectedly
  1144. if connection.RemoteAddr().String() != follower {
  1145. if size > mtu {
  1146. fmt.Println("have a look here")
  1147. }
  1148. fmt.Println("handleError", err)
  1149. array := make([]byte, size)
  1150. array[0] = 1
  1151. _, err = followerConnection.Write(array)
  1152. if err != nil {
  1153. panic(err)
  1154. }
  1155. return true
  1156. } else {
  1157. panic(err)
  1158. }
  1159. }
  1160. return false
  1161. }
  1162. //reads an array which is returned and of size "size" from the connection
  1163. //returns true if error occured
  1164. func readFrom(connection net.Conn, size int, followerConnection net.Conn, sizeError int) ([]byte, bool) {
  1165. var array []byte
  1166. remainingSize := size
  1167. for remainingSize > 0 {
  1168. var err error
  1169. toAppend := make([]byte, mtu)
  1170. if remainingSize > mtu {
  1171. _, err = connection.Read(toAppend)
  1172. array = append(array, toAppend...)
  1173. remainingSize -= mtu
  1174. } else {
  1175. _, err = connection.Read(toAppend[:remainingSize])
  1176. array = append(array, toAppend[:remainingSize]...)
  1177. remainingSize = 0
  1178. }
  1179. if err != nil {
  1180. //lets follower know that client has disconnected unexpectedly
  1181. if connection.RemoteAddr().String() != follower {
  1182. fmt.Println(err)
  1183. array := make([]byte, sizeError)
  1184. array[0] = 1
  1185. _, err = followerConnection.Write(array)
  1186. if err != nil {
  1187. panic(err)
  1188. }
  1189. return nil, true
  1190. } else {
  1191. panic(err)
  1192. }
  1193. }
  1194. }
  1195. return array, false
  1196. }
  1197. func intToByte(myInt int) (retBytes []byte) {
  1198. retBytes = make([]byte, 4)
  1199. retBytes[3] = byte((myInt >> 24) & 0xff)
  1200. retBytes[2] = byte((myInt >> 16) & 0xff)
  1201. retBytes[1] = byte((myInt >> 8) & 0xff)
  1202. retBytes[0] = byte(myInt & 0xff)
  1203. return
  1204. }