leader.go 34 KB

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