leader.go 33 KB

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