leader.go 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389
  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 = 1000
  56. var dbWriteSize float64 = 20000
  57. var collisionCounter []float64
  58. var clientsConnected int
  59. var maxTimePerRound time.Duration = 30 * 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 waitChannel = make(chan net.Conn, maxNumberOfClients)
  71. //var waitChannel = 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. waitChannel <- 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. for id := 0; id < numThreads; id++ {
  241. wg.Add(1)
  242. followerConnection, err := tls.Dial("tcp", follower, conf)
  243. if err != nil {
  244. panic(err)
  245. }
  246. followerConnection.SetDeadline(time.Time{})
  247. go phase1(id, phase, followerConnection, wg, m, virtualAddresses)
  248. }
  249. wg.Wait()
  250. fmt.Println("fullDurationPhase1", time.Since(startPhase1).Seconds())
  251. //Phase 2
  252. startPhase2 = time.Now()
  253. followerConnection, err := tls.Dial("tcp", follower, conf)
  254. if err != nil {
  255. panic(err)
  256. }
  257. followerConnection.SetDeadline(time.Time{})
  258. phase2(followerConnection)
  259. fmt.Println("fullDurationPhase2", time.Since(startPhase2).Seconds())
  260. //Phase 3
  261. startPhase3 = time.Now()
  262. //no tweets -> continue to phase 1 and mb get tweets
  263. topicList, topicAmount = lib.GetTopicList(0)
  264. if len(topicList) == 0 {
  265. continue
  266. }
  267. phase[0] = 3
  268. startTimeRound = time.Now()
  269. for id := 0; id < numThreads; id++ {
  270. wg.Add(1)
  271. followerConnection, err := tls.Dial("tcp", follower, conf)
  272. if err != nil {
  273. panic(err)
  274. }
  275. followerConnection.SetDeadline(time.Time{})
  276. go phase3(id, phase, followerConnection, wg, m)
  277. }
  278. wg.Wait()
  279. fmt.Println("fullDurationPhase3", time.Since(startPhase3).Seconds())
  280. lib.CleanUpdbR(round)
  281. }
  282. }
  283. func phase1(id int, phase []byte, followerConnection net.Conn, wg *sync.WaitGroup, m *sync.RWMutex, virtualAddresses []int) {
  284. roundAsBytes := intToByte(round)
  285. gotClient := make([]byte, 1)
  286. gotClient[0] = 0
  287. //wait until time is up
  288. for len(waitChannel) == 0 {
  289. if time.Since(startTimeRound) > maxTimePerRound {
  290. //tells follower that this worker is done
  291. writeTo(followerConnection, gotClient)
  292. wg.Done()
  293. return
  294. }
  295. time.Sleep(1 * time.Second)
  296. }
  297. for clientConnection := range waitChannel {
  298. clientsServedPhase1[round] = clientsServedPhase1[round] + 1
  299. if clientsServedPhase1[round]%1000 == 0 {
  300. fmt.Println("clientsServedPhase1", clientsServedPhase1[round])
  301. fmt.Println("timeTaken", time.Since(startPhase1))
  302. }
  303. gotClient[0] = 1
  304. //tells follower that this worker got a clientConnection
  305. writeTo(followerConnection, gotClient)
  306. //sends clients publicKey to follower
  307. m.RLock()
  308. clientPublicKey := clientData[clientConnection.RemoteAddr()].PublicKey
  309. m.RUnlock()
  310. writeTo(followerConnection, clientPublicKey[:])
  311. //setup the worker-specific db
  312. dbSize := int(C.dbSize)
  313. db := make([][]byte, dbSize)
  314. for i := 0; i < dbSize; i++ {
  315. db[i] = make([]byte, int(C.db[i].dataSize))
  316. }
  317. //tells client that phase 1 has begun
  318. errorBool := writeToWError(clientConnection, phase, followerConnection, 5)
  319. if errorBool {
  320. contBool := handleClientDC(wg, followerConnection, waitChannel)
  321. if contBool {
  322. continue
  323. } else {
  324. return
  325. }
  326. }
  327. //tells client current dbWriteSize
  328. errorBool = writeToWError(clientConnection, intToByte(int(dbWriteSize)), followerConnection, 5)
  329. if errorBool {
  330. contBool := handleClientDC(wg, followerConnection, waitChannel)
  331. if contBool {
  332. continue
  333. } else {
  334. return
  335. }
  336. }
  337. //tells client current round
  338. errorBool = writeToWError(clientConnection, roundAsBytes, followerConnection, 5)
  339. if errorBool {
  340. contBool := handleClientDC(wg, followerConnection, waitChannel)
  341. if contBool {
  342. continue
  343. } else {
  344. return
  345. }
  346. }
  347. //begin auditing
  348. //auditingStart := time.Now()
  349. m.RLock()
  350. var clientKeys = clientData[clientConnection.RemoteAddr()]
  351. m.RUnlock()
  352. clientKeys, pirQuery, errorBool := handlePirQuery(clientKeys, clientConnection, followerConnection, 0, true)
  353. if errorBool {
  354. contBool := handleClientDC(wg, followerConnection, waitChannel)
  355. if contBool {
  356. continue
  357. } else {
  358. return
  359. }
  360. }
  361. errorBool = getSendVirtualAddress(pirQuery[0], virtualAddresses, clientKeys.SharedSecret, clientConnection, followerConnection)
  362. if errorBool {
  363. contBool := handleClientDC(wg, followerConnection, waitChannel)
  364. if contBool {
  365. continue
  366. } else {
  367. return
  368. }
  369. }
  370. if id == 0 {
  371. //fmt.Println("Auditing duration", time.Since(auditingStart).Seconds())
  372. }
  373. m.Lock()
  374. clientData[clientConnection.RemoteAddr()] = clientKeys
  375. m.Unlock()
  376. //accept dpfQuery from client
  377. dpfLengthBytes, errorBool := readFrom(clientConnection, 4, followerConnection, 5)
  378. if errorBool {
  379. contBool := handleClientDC(wg, followerConnection, waitChannel)
  380. if contBool {
  381. continue
  382. } else {
  383. return
  384. }
  385. }
  386. dpfLength := byteToInt(dpfLengthBytes)
  387. dpfQueryAEncrypted, errorBool := readFrom(clientConnection, dpfLength, followerConnection, 5)
  388. if errorBool {
  389. contBool := handleClientDC(wg, followerConnection, waitChannel)
  390. if contBool {
  391. continue
  392. } else {
  393. return
  394. }
  395. }
  396. dpfQueryBEncrypted, errorBool := readFrom(clientConnection, dpfLength, followerConnection, 5)
  397. if errorBool {
  398. contBool := handleClientDC(wg, followerConnection, waitChannel)
  399. if contBool {
  400. continue
  401. } else {
  402. return
  403. }
  404. }
  405. writeToWError(followerConnection, dpfLengthBytes, nil, 0)
  406. writeToWError(followerConnection, dpfQueryBEncrypted, nil, 0)
  407. //decrypt dpfQueryA for sorting into db
  408. var decryptNonce [24]byte
  409. copy(decryptNonce[:], dpfQueryAEncrypted[:24])
  410. dpfQueryA, ok := box.Open(nil, dpfQueryAEncrypted[24:], &decryptNonce, clientPublicKey, leaderPrivateKey)
  411. if !ok {
  412. panic("dpfQueryA decryption not ok")
  413. }
  414. ds := int(C.db[0].dataSize)
  415. dataShareLeader := make([]byte, ds)
  416. pos := C.getUint128_t(C.int(virtualAddresses[int(dbWriteSize)]))
  417. C.evalDPF(C.ctx[id], (*C.uchar)(&dpfQueryA[0]), pos, C.int(ds), (*C.uchar)(&dataShareLeader[0]))
  418. dataShareFollower, _ := readFrom(followerConnection, ds, nil, 0)
  419. writeToWError(followerConnection, dataShareLeader, nil, 0)
  420. auditXOR := make([]byte, ds)
  421. passedAudit := true
  422. for i := 0; i < ds; i++ {
  423. auditXOR[i] = dataShareLeader[i] ^ dataShareFollower[i]
  424. //client tried to write to a position that is not a virtuallAddress
  425. if auditXOR[i] != 0 {
  426. clientConnection.Close()
  427. passedAudit = false
  428. }
  429. }
  430. if passedAudit {
  431. //run dpf, xor into local db
  432. for i := 0; i < dbSize; i++ {
  433. ds := int(C.db[i].dataSize)
  434. dataShare := make([]byte, ds)
  435. pos := C.getUint128_t(C.int(virtualAddresses[i]))
  436. C.evalDPF(C.ctx[id], (*C.uchar)(&dpfQueryA[0]), pos, C.int(ds), (*C.uchar)(&dataShare[0]))
  437. for j := 0; j < ds; j++ {
  438. db[i][j] = db[i][j] ^ dataShare[j]
  439. }
  440. }
  441. //xor the worker's DB into the main DB
  442. for i := 0; i < dbSize; i++ {
  443. m.Lock()
  444. C.xorIn(C.int(i), (*C.uchar)(&db[i][0]))
  445. m.Unlock()
  446. }
  447. waitChannel <- clientConnection
  448. }
  449. //loop that waits for new client or leaves phase1 if time is up
  450. for {
  451. if time.Since(startTimeRound) < maxTimePerRound {
  452. //this worker handles the next client
  453. if len(waitChannel) > 0 {
  454. break
  455. //this worker waits for next client
  456. } else {
  457. time.Sleep(1 * time.Second)
  458. }
  459. //times up
  460. } else {
  461. //tells follower that this worker is done
  462. gotClient[0] = 0
  463. writeTo(followerConnection, gotClient)
  464. wg.Done()
  465. return
  466. }
  467. }
  468. }
  469. }
  470. func phase2(followerConnection net.Conn) {
  471. //gets current seed
  472. seedLeader := make([]byte, 16)
  473. C.readSeed((*C.uchar)(&seedLeader[0]))
  474. //get data
  475. dbSize := int(C.dbSize)
  476. tmpdbLeader := make([][]byte, dbSize)
  477. for i := range tmpdbLeader {
  478. tmpdbLeader[i] = make([]byte, dataLength)
  479. }
  480. for i := 0; i < dbSize; i++ {
  481. C.readData(C.int(i), (*C.uchar)(&tmpdbLeader[i][0]))
  482. }
  483. //writes seed to follower
  484. writeTo(followerConnection, seedLeader)
  485. //write data to follower
  486. //this is surely inefficent
  487. for i := 0; i < dbSize; i++ {
  488. writeTo(followerConnection, tmpdbLeader[i])
  489. }
  490. //receive seed from follower
  491. seedFollower, _ := readFrom(followerConnection, 16, nil, 0)
  492. //receive data from follower
  493. tmpdbFollower := make([][]byte, dbSize)
  494. for i := range tmpdbFollower {
  495. tmpdbFollower[i] = make([]byte, dataLength)
  496. }
  497. for i := 0; i < dbSize; i++ {
  498. tmpdbFollower[i], _ = readFrom(followerConnection, dataLength, nil, 0)
  499. }
  500. //put together the db
  501. tmpdb := make([][]byte, dbSize)
  502. for i := range tmpdb {
  503. tmpdb[i] = make([]byte, dataLength)
  504. }
  505. //get own Ciphers
  506. ciphersLeader := make([]*C.uchar, dbSize)
  507. for i := 0; i < dbSize; i++ {
  508. ciphersLeader[i] = (*C.uchar)(C.malloc(16))
  509. }
  510. for i := 0; i < dbSize; i++ {
  511. C.getCipher(1, C.int(i), ciphersLeader[i])
  512. }
  513. //send own Ciphers to follower
  514. for i := 0; i < dbSize; i++ {
  515. writeTo(followerConnection, C.GoBytes(unsafe.Pointer(ciphersLeader[i]), 16))
  516. }
  517. //receive ciphers from follower
  518. ciphersFollower := make([]byte, dbSize*16)
  519. for i := 0; i < dbSize; i++ {
  520. _, err := followerConnection.Read(ciphersFollower[i*16:])
  521. if err != nil {
  522. panic(err)
  523. }
  524. }
  525. //put in ciphers from follower
  526. for i := 0; i < dbSize; i++ {
  527. C.putCipher(1, C.int(i), (*C.uchar)(&ciphersFollower[i*16]))
  528. }
  529. //decrypt each row
  530. for i := 0; i < dbSize; i++ {
  531. 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]))
  532. }
  533. var tweets []lib.Tweet
  534. var currentPublisherAmount int = 0
  535. var collisions float64
  536. for i := 0; i < dbSize; i++ {
  537. //discard cover message
  538. if tmpdb[i][1] == 0 {
  539. continue
  540. //collision
  541. } else if -1 == strings.Index(string(tmpdb[i]), ";;") {
  542. currentPublisherAmount++
  543. currentPublisherAmount++
  544. collisions++
  545. continue
  546. } else {
  547. currentPublisherAmount++
  548. //reconstruct tweet
  549. var position int = 0
  550. var topics []string
  551. var topic string
  552. var text string
  553. for _, letter := range tmpdb[i] {
  554. if string(letter) == ";" {
  555. if topic != "" {
  556. topics = append(topics, topic)
  557. topic = ""
  558. }
  559. position++
  560. } else {
  561. if position == 0 {
  562. if string(letter) == "," {
  563. topics = append(topics, topic)
  564. topic = ""
  565. } else {
  566. //change this works for ints, need to be changed for strings
  567. //have
  568. topic = topic + string(letter)
  569. }
  570. } else if position == 1 {
  571. text = text + string(letter)
  572. }
  573. }
  574. }
  575. tweet := lib.Tweet{"", -1, topics, text, round}
  576. if text != "" {
  577. tweets = append(tweets, tweet)
  578. } else {
  579. //this is a odd(number) way collisions
  580. collisions++
  581. }
  582. }
  583. }
  584. collisionCounter = append(collisionCounter, collisions)
  585. if collisions/dbWriteSize > 0.05 {
  586. fmt.Println("Collisions this round", collisions, "dbWriteSize", dbWriteSize)
  587. }
  588. //fmt.Println("tweets recovered: ", tweets)
  589. //sort into read db
  590. //fmt.Println("newTweets", tweets)
  591. lib.NewEntries(tweets, 0)
  592. C.resetDb()
  593. //calculates the publisherAverage over the last publisherRounds rounds
  594. index := round % publisherRounds
  595. publisherHistory[index] = currentPublisherAmount
  596. var publisherAmount int
  597. for _, num := range publisherHistory {
  598. publisherAmount += num
  599. }
  600. publisherAverage := 0
  601. if round < publisherRounds {
  602. publisherAverage = publisherAmount / round
  603. } else {
  604. publisherAverage = publisherAmount / publisherRounds
  605. }
  606. //calculates the dbWriteSize for this round
  607. dbWriteSize = math.Ceil(19.5 * float64(publisherAverage))
  608. if dbWriteSize < minDBWriteSize {
  609. dbWriteSize = minDBWriteSize
  610. }
  611. //writes dbWriteSize of current round to follower
  612. writeTo(followerConnection, intToByte(int(dbWriteSize)))
  613. }
  614. func addTestTweets() {
  615. //creates test tweets
  616. tweets := make([]lib.Tweet, 5)
  617. for i := range tweets {
  618. j := i
  619. if i == 1 {
  620. j = 0
  621. }
  622. text := "Text " + strconv.Itoa(i)
  623. var topics []string
  624. topics = append(topics, "Topic "+strconv.Itoa(j))
  625. tweets[i] = lib.Tweet{"", -1, topics, text, i}
  626. }
  627. lib.NewEntries(tweets, 0)
  628. }
  629. //opti! mb it is quicker to send updated topicLists to clients first so pirQuerys are ready
  630. func phase3(id int, phase []byte, followerConnection net.Conn, wg *sync.WaitGroup, m *sync.RWMutex) {
  631. gotClient := make([]byte, 1)
  632. gotClient[0] = 0
  633. //wait until time is up
  634. for len(waitChannel) == 0 {
  635. if time.Since(startTimeRound) > maxTimePerRound*2 {
  636. //tells follower that this worker is done
  637. writeToWError(followerConnection, gotClient, nil, 0)
  638. wg.Done()
  639. return
  640. }
  641. time.Sleep(1 * time.Second)
  642. }
  643. for clientConnection := range waitChannel {
  644. clientsServedPhase3[round] = clientsServedPhase3[round] + 1
  645. if clientsServedPhase3[round]%1000 == 0 {
  646. fmt.Println("clientsServedPhase3", clientsServedPhase3[round])
  647. fmt.Println("timeTaken", time.Since(startPhase3).Seconds())
  648. }
  649. gotClient[0] = 1
  650. //tells follower that this worker got a clientConnection
  651. writeToWError(followerConnection, gotClient, nil, 0)
  652. //tells client current phase
  653. errorBool := writeToWError(clientConnection, phase, followerConnection, 2)
  654. if errorBool {
  655. contBool := handleClientDC(wg, followerConnection, waitChannel)
  656. if contBool {
  657. continue
  658. } else {
  659. return
  660. }
  661. }
  662. /*
  663. possible Values
  664. 0 : new client
  665. leader expects sharedSecrets, expects pirQuery
  666. 1 : update needed
  667. leader sends topicList, performs local update of sharedSecret, expects pirQuery
  668. 2 : no update needed
  669. nothing
  670. */
  671. subPhase := make([]byte, 1)
  672. //gets the data for the current client
  673. m.RLock()
  674. var clientKeys = clientData[clientConnection.RemoteAddr()]
  675. m.RUnlock()
  676. var roundsParticipating = clientKeys.roundsParticipating
  677. //client participates for the first time
  678. if roundsParticipating == 0 {
  679. subPhase[0] = 0
  680. } else if roundsParticipating%roundsBeforeUpdate == 0 {
  681. subPhase[0] = 1
  682. } else {
  683. subPhase[0] = 2
  684. }
  685. //tells client what leader expects
  686. errorBool = writeToWError(clientConnection, subPhase, followerConnection, 2)
  687. if errorBool {
  688. contBool := handleClientDC(wg, followerConnection, waitChannel)
  689. if contBool {
  690. continue
  691. } else {
  692. return
  693. }
  694. }
  695. //tells follower what will happen
  696. writeToWError(followerConnection, subPhase, nil, 0)
  697. //sends clients publicKey so follower knows which client is being served
  698. writeTo(followerConnection, clientKeys.PublicKey[:])
  699. //increases rounds participating for client
  700. clientKeys.roundsParticipating = roundsParticipating + 1
  701. //declaring variables here to prevent dupclicates later
  702. m.RLock()
  703. var sharedSecret [32]byte = clientData[clientConnection.RemoteAddr()].SharedSecret
  704. m.RUnlock()
  705. if subPhase[0] == 0 {
  706. errorBool := sendTopicLists(clientConnection, followerConnection, false)
  707. if errorBool {
  708. contBool := handleClientDC(wg, followerConnection, waitChannel)
  709. if contBool {
  710. continue
  711. } else {
  712. return
  713. }
  714. }
  715. clientKeys, _, errorBool = handlePirQuery(clientKeys, clientConnection, followerConnection, int(subPhase[0]), false)
  716. if errorBool {
  717. contBool := handleClientDC(wg, followerConnection, waitChannel)
  718. if contBool {
  719. continue
  720. } else {
  721. return
  722. }
  723. }
  724. } else if subPhase[0] == 1 {
  725. errorBool := sendTopicLists(clientConnection, followerConnection, false)
  726. if errorBool {
  727. contBool := handleClientDC(wg, followerConnection, waitChannel)
  728. if contBool {
  729. continue
  730. } else {
  731. return
  732. }
  733. }
  734. //updates sharedSecret
  735. sharedSecret = sha256.Sum256(sharedSecret[:])
  736. clientKeys.SharedSecret = sharedSecret
  737. clientKeys, _, errorBool = handlePirQuery(clientKeys, clientConnection, followerConnection, int(subPhase[0]), false)
  738. if errorBool {
  739. contBool := handleClientDC(wg, followerConnection, waitChannel)
  740. if contBool {
  741. continue
  742. } else {
  743. return
  744. }
  745. }
  746. }
  747. errorBool = getSendTweets(clientKeys, nil, clientConnection, followerConnection, m)
  748. if errorBool {
  749. contBool := handleClientDC(wg, followerConnection, waitChannel)
  750. if contBool {
  751. continue
  752. } else {
  753. return
  754. }
  755. }
  756. wantsArchive, errorBool := readFrom(clientConnection, 1, followerConnection, 2)
  757. if errorBool {
  758. contBool := handleClientDC(wg, followerConnection, waitChannel)
  759. if contBool {
  760. continue
  761. } else {
  762. return
  763. }
  764. }
  765. writeToWError(followerConnection, wantsArchive, nil, 0)
  766. if wantsArchive[0] == 1 && archiveTopicAmount > 0 {
  767. _, archiveQuerys, errorBool := handlePirQuery(clientKeys, clientConnection, followerConnection, -1, false)
  768. if errorBool {
  769. contBool := handleClientDC(wg, followerConnection, waitChannel)
  770. if contBool {
  771. continue
  772. } else {
  773. return
  774. }
  775. }
  776. errorBool = getSendTweets(clientKeys, archiveQuerys, clientConnection, followerConnection, m)
  777. if errorBool {
  778. contBool := handleClientDC(wg, followerConnection, waitChannel)
  779. if contBool {
  780. continue
  781. } else {
  782. return
  783. }
  784. }
  785. }
  786. //saves all changes for client
  787. m.Lock()
  788. clientData[clientConnection.RemoteAddr()] = clientKeys
  789. m.Unlock()
  790. waitChannel <- clientConnection
  791. for {
  792. if time.Since(startTimeRound) < 2*maxTimePerRound {
  793. //this worker handles the next client
  794. if len(waitChannel) > 0 {
  795. break
  796. //this worker waits for next client
  797. } else {
  798. time.Sleep(1 * time.Second)
  799. }
  800. //times up
  801. } else {
  802. //tells follower that this worker is done
  803. gotClient[0] = 0
  804. writeToWError(followerConnection, gotClient, nil, 0)
  805. wg.Done()
  806. return
  807. }
  808. }
  809. }
  810. }
  811. //returns true if there is another client
  812. func handleClientDC(wg *sync.WaitGroup, followerConnection net.Conn, channel chan net.Conn) bool {
  813. //loop that waits for new client or leaves phase1 if time is up
  814. for {
  815. if time.Since(startTimeRound) < maxTimePerRound {
  816. //this worker handles the next client
  817. if len(channel) > 0 {
  818. return true
  819. //this worker waits for next client
  820. } else {
  821. time.Sleep(1 * time.Second)
  822. }
  823. //times up
  824. } else {
  825. //tells follower that this worker is done
  826. gotClient := make([]byte, 1)
  827. gotClient[0] = 0
  828. writeTo(followerConnection, gotClient)
  829. wg.Done()
  830. return false
  831. }
  832. }
  833. }
  834. func createVirtualAddresses() []int {
  835. //array will be filled with unique random ascending values
  836. //adapted from: https://stackoverflow.com/questions/20039025/java-array-of-unique-randomly-generated-integers
  837. //+1 to have a position to evaluate each received message
  838. arraySize := int(dbWriteSize) + 1
  839. var maxInt int = int(math.Pow(2, 31))
  840. virtualAddresses := make([]int, arraySize)
  841. for i := 0; i < arraySize; i++ {
  842. virtualAddresses[i] = mr.Intn(maxInt)
  843. for j := 0; j < i; j++ {
  844. if virtualAddresses[i] == virtualAddresses[j] {
  845. i--
  846. break
  847. }
  848. }
  849. }
  850. sort.Ints(virtualAddresses)
  851. return virtualAddresses
  852. }
  853. func getSendVirtualAddress(pirQuery []byte, virtualAddresses []int, sharedSecret [32]byte, clientConnection, followerConnection net.Conn) bool {
  854. //xores all requested addresses into virtuallAddress
  855. virtualAddress := make([]byte, 4)
  856. for index, num := range pirQuery {
  857. if num == 1 {
  858. currentAddress := intToByte(virtualAddresses[index])
  859. for i := 0; i < 4; i++ {
  860. virtualAddress[i] = virtualAddress[i] ^ currentAddress[i]
  861. }
  862. }
  863. }
  864. //xores the sharedSecret
  865. for i := 0; i < 4; i++ {
  866. virtualAddress[i] = virtualAddress[i] ^ sharedSecret[i]
  867. }
  868. virtualAddressFollower, _ := readFrom(followerConnection, 4, nil, 0)
  869. //xores the data from follower
  870. for i := 0; i < 4; i++ {
  871. virtualAddress[i] = virtualAddress[i] ^ virtualAddressFollower[i]
  872. }
  873. errorBool := writeToWError(clientConnection, virtualAddress, followerConnection, 5)
  874. return errorBool
  875. }
  876. func getSendTweets(clientKeys clientKeys, archiveQuerys [][]byte, clientConnection, followerConnection net.Conn, m *sync.RWMutex) bool {
  877. //todo! repeat for archive
  878. tmpNeededSubscriptions := neededSubscriptions
  879. if tmpNeededSubscriptions > topicAmount {
  880. tmpNeededSubscriptions = topicAmount
  881. }
  882. if archiveQuerys != nil {
  883. tmpNeededSubscriptions = len(archiveQuerys)
  884. }
  885. //fmt.Println("tmpNeededSubscriptions", tmpNeededSubscriptions)
  886. tweets := make([][]byte, tmpNeededSubscriptions)
  887. for i := 0; i < tmpNeededSubscriptions; i++ {
  888. //gets all requested tweets
  889. if archiveQuerys == nil {
  890. tweets[i] = lib.GetTweets(clientKeys.PirQuery[i], dataLength, 0, *clientKeys.PublicKey)
  891. } else {
  892. tweets[i] = lib.GetTweets(archiveQuerys[i], dataLength, 1, *clientKeys.PublicKey)
  893. }
  894. //expand sharedSecret so it is of right length
  895. expandBy := len(tweets[i]) / 32
  896. var expandedSharedSecret []byte
  897. for i := 0; i < expandBy; i++ {
  898. expandedSharedSecret = append(expandedSharedSecret, clientKeys.SharedSecret[:]...)
  899. }
  900. //Xor's sharedSecret with all tweets
  901. lib.Xor(expandedSharedSecret[:], tweets[i])
  902. //fmt.Println(tweets[0])
  903. blockLength := len(tweets[i])
  904. receivedTweets, _ := readFrom(followerConnection, blockLength, nil, 0)
  905. //fmt.Println("receivedTweets", blockLength, len(receivedTweets))
  906. //fmt.Println("pubKey", *clientKeys.PublicKey, "Bytes", tweets, "follower", receivedTweets)
  907. lib.Xor(receivedTweets, tweets[i])
  908. }
  909. //sends tweets to client
  910. for i := 0; i < tmpNeededSubscriptions; i++ {
  911. tweetsLengthBytes := intToByte(len(tweets[i]))
  912. errorBool := writeToWError(clientConnection, tweetsLengthBytes, followerConnection, 2)
  913. if errorBool {
  914. return true
  915. }
  916. errorBool = writeToWError(clientConnection, tweets[i], followerConnection, 2)
  917. if errorBool {
  918. return true
  919. }
  920. }
  921. return false
  922. }
  923. func handlePirQuery(clientKeys clientKeys, clientConnection net.Conn, followerConnection net.Conn, subPhase int, doAuditing bool) (clientKeys, [][]byte, bool) {
  924. clientPublicKey := clientKeys.PublicKey
  925. //gets the msg length
  926. msgLengthBytes, errorBool := readFrom(clientConnection, 4, followerConnection, 5)
  927. if errorBool {
  928. return clientKeys, nil, true
  929. }
  930. msgLength := byteToInt(msgLengthBytes)
  931. //gets the leader box
  932. leaderBox, errorBool := readFrom(clientConnection, msgLength, followerConnection, 5)
  933. if errorBool {
  934. return clientKeys, nil, true
  935. }
  936. //gets the follower box
  937. followerBox, errorBool := readFrom(clientConnection, msgLength, followerConnection, 5)
  938. if errorBool {
  939. return clientKeys, nil, true
  940. }
  941. //todo! repeat for archive
  942. tmpNeededSubscriptions := neededSubscriptions
  943. if tmpNeededSubscriptions > topicAmount {
  944. tmpNeededSubscriptions = topicAmount
  945. }
  946. tmpTopicAmount := topicAmount
  947. if subPhase == -1 {
  948. archiveNeededSubscriptions, errorBool := readFrom(clientConnection, 4, followerConnection, 5)
  949. if errorBool {
  950. return clientKeys, nil, true
  951. }
  952. writeToWError(followerConnection, archiveNeededSubscriptions, nil, 0)
  953. tmpNeededSubscriptions = byteToInt(archiveNeededSubscriptions)
  954. tmpTopicAmount = archiveTopicAmount
  955. }
  956. if doAuditing {
  957. tmpNeededSubscriptions = 1
  958. tmpTopicAmount = int(dbWriteSize)
  959. }
  960. //send length to follower
  961. writeToWError(followerConnection, msgLengthBytes, nil, 0)
  962. //send box to follower
  963. writeToWError(followerConnection, followerBox, nil, 0)
  964. var decryptNonce [24]byte
  965. copy(decryptNonce[:], leaderBox[:24])
  966. decrypted, ok := box.Open(nil, leaderBox[24:], &decryptNonce, clientPublicKey, leaderPrivateKey)
  967. if !ok {
  968. fmt.Println("pirQuery decryption not ok")
  969. return clientKeys, nil, true
  970. }
  971. //if sharedSecret is send
  972. if subPhase == 0 {
  973. var tmpSharedSecret [32]byte
  974. for index := 0; index < 32; index++ {
  975. tmpSharedSecret[index] = decrypted[index]
  976. }
  977. clientKeys.SharedSecret = tmpSharedSecret
  978. decrypted = decrypted[32:]
  979. }
  980. if doAuditing {
  981. result := make([][]byte, 1)
  982. result[0] = decrypted
  983. return clientKeys, result, false
  984. }
  985. //transforms byteArray to ints of wanted topics
  986. pirQueryFlattened := decrypted
  987. pirQuerys := make([][]byte, tmpNeededSubscriptions)
  988. for i := range pirQuerys {
  989. pirQuerys[i] = make([]byte, tmpTopicAmount)
  990. }
  991. for i := 0; i < tmpNeededSubscriptions; i++ {
  992. pirQuerys[i] = pirQueryFlattened[i*tmpTopicAmount : (i+1)*tmpTopicAmount]
  993. }
  994. //sets the pirQuery for the client in case whe are not archiving, and not Auditing
  995. if subPhase != -1 {
  996. clientKeys.PirQuery = pirQuerys
  997. }
  998. return clientKeys, pirQuerys, false
  999. }
  1000. func transformBytesToStringArray(topicsAsBytes []byte) []string {
  1001. var topics []string
  1002. var topic string
  1003. var position int = 0
  1004. for _, letter := range topicsAsBytes {
  1005. if string(letter) == "," {
  1006. topics[position] = topic
  1007. topic = ""
  1008. position++
  1009. } else {
  1010. topic = topic + string(letter)
  1011. }
  1012. }
  1013. return topics
  1014. }
  1015. func byteToInt(myBytes []byte) (x int) {
  1016. x = int(myBytes[3])<<24 + int(myBytes[2])<<16 + int(myBytes[1])<<8 + int(myBytes[0])
  1017. return
  1018. }
  1019. //returns true if error occured
  1020. func sendTopicLists(clientConnection, followerConnection net.Conn, setup bool) bool {
  1021. for i := 0; i < 2; i++ {
  1022. var topicList []byte
  1023. if i == 0 {
  1024. topicList, topicAmount = lib.GetTopicList(i)
  1025. } else {
  1026. topicList, archiveTopicAmount = lib.GetTopicList(i)
  1027. }
  1028. topicListLengthBytes := intToByte(len(topicList))
  1029. if !setup {
  1030. err := writeToWError(clientConnection, topicListLengthBytes, followerConnection, 5)
  1031. if err {
  1032. return true
  1033. }
  1034. err = writeToWError(clientConnection, topicList, followerConnection, 5)
  1035. if err {
  1036. return true
  1037. }
  1038. } else {
  1039. _, err := clientConnection.Write(topicListLengthBytes)
  1040. if err != nil {
  1041. return true
  1042. }
  1043. _, err = clientConnection.Write(topicList)
  1044. if err != nil {
  1045. return true
  1046. }
  1047. }
  1048. }
  1049. return false
  1050. }
  1051. //sends the array to the connection
  1052. func writeTo(connection net.Conn, array []byte) {
  1053. remainingLength := len(array)
  1054. for remainingLength > 0 {
  1055. if remainingLength >= mtu {
  1056. _, err := connection.Write(array[:mtu])
  1057. if err != nil {
  1058. panic(err)
  1059. }
  1060. array = array[mtu:]
  1061. remainingLength -= mtu
  1062. } else {
  1063. _, err := connection.Write(array)
  1064. if err != nil {
  1065. panic(err)
  1066. }
  1067. remainingLength = 0
  1068. }
  1069. }
  1070. }
  1071. func writeToWError(connection net.Conn, array []byte, followerConnection net.Conn, size int) bool {
  1072. if connection.RemoteAddr().String() == follower {
  1073. arrayWError := make([]byte, 1)
  1074. arrayWError = append(arrayWError, array[:]...)
  1075. remainingLength := len(arrayWError)
  1076. for remainingLength > 0 {
  1077. if remainingLength >= mtu {
  1078. _, err := connection.Write(arrayWError[:mtu])
  1079. if err != nil {
  1080. return handleError(connection, followerConnection, size, err)
  1081. }
  1082. arrayWError = arrayWError[mtu:]
  1083. remainingLength -= mtu
  1084. } else {
  1085. _, err := connection.Write(arrayWError)
  1086. if err != nil {
  1087. return handleError(connection, followerConnection, size, err)
  1088. }
  1089. remainingLength = 0
  1090. }
  1091. }
  1092. } else {
  1093. remainingLength := len(array)
  1094. for remainingLength > 0 {
  1095. if remainingLength >= mtu {
  1096. _, err := connection.Write(array[:mtu])
  1097. if err != nil {
  1098. return handleError(connection, followerConnection, size, err)
  1099. }
  1100. array = array[mtu:]
  1101. remainingLength -= mtu
  1102. } else {
  1103. _, err := connection.Write(array)
  1104. if err != nil {
  1105. return handleError(connection, followerConnection, size, err)
  1106. }
  1107. remainingLength = 0
  1108. }
  1109. }
  1110. }
  1111. return false
  1112. }
  1113. func handleError(connection, followerConnection net.Conn, size int, err error) bool {
  1114. if err != nil {
  1115. //lets follower know that client has disconnected unexpectedly
  1116. if connection.RemoteAddr().String() != follower {
  1117. if size > mtu {
  1118. fmt.Println("have a look here")
  1119. }
  1120. fmt.Println("error", err)
  1121. array := make([]byte, size)
  1122. array[0] = 1
  1123. _, err = followerConnection.Write(array)
  1124. if err != nil {
  1125. panic(err)
  1126. }
  1127. return true
  1128. } else {
  1129. panic(err)
  1130. }
  1131. }
  1132. return false
  1133. }
  1134. //reads an array which is returned and of size "size" from the connection
  1135. //returns true if error occured
  1136. func readFrom(connection net.Conn, size int, followerConnection net.Conn, sizeError int) ([]byte, bool) {
  1137. var array []byte
  1138. remainingSize := size
  1139. for remainingSize > 0 {
  1140. var err error
  1141. toAppend := make([]byte, mtu)
  1142. if remainingSize > mtu {
  1143. _, err = connection.Read(toAppend)
  1144. array = append(array, toAppend...)
  1145. remainingSize -= mtu
  1146. } else {
  1147. _, err = connection.Read(toAppend[:remainingSize])
  1148. array = append(array, toAppend[:remainingSize]...)
  1149. remainingSize = 0
  1150. }
  1151. if err != nil {
  1152. //lets follower know that client has disconnected unexpectedly
  1153. if connection.RemoteAddr().String() != follower {
  1154. fmt.Println(err)
  1155. array := make([]byte, sizeError)
  1156. array[0] = 1
  1157. _, err = followerConnection.Write(array)
  1158. if err != nil {
  1159. panic(err)
  1160. }
  1161. return nil, true
  1162. } else {
  1163. panic(err)
  1164. }
  1165. }
  1166. }
  1167. return array, false
  1168. }
  1169. func intToByte(myInt int) (retBytes []byte) {
  1170. retBytes = make([]byte, 4)
  1171. retBytes[3] = byte((myInt >> 24) & 0xff)
  1172. retBytes[2] = byte((myInt >> 16) & 0xff)
  1173. retBytes[1] = byte((myInt >> 8) & 0xff)
  1174. retBytes[0] = byte(myInt & 0xff)
  1175. return
  1176. }