leader.go 34 KB

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