signatures.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. from twisted.internet import defer
  16. from ._base import SQLBaseStore
  17. from unpaddedbase64 import encode_base64
  18. from synapse.crypto.event_signing import compute_event_reference_hash
  19. class SignatureStore(SQLBaseStore):
  20. """Persistence for event signatures and hashes"""
  21. def get_event_reference_hashes(self, event_ids):
  22. def f(txn):
  23. return [
  24. self._get_event_reference_hashes_txn(txn, ev)
  25. for ev in event_ids
  26. ]
  27. return self.runInteraction(
  28. "get_event_reference_hashes",
  29. f
  30. )
  31. @defer.inlineCallbacks
  32. def add_event_hashes(self, event_ids):
  33. hashes = yield self.get_event_reference_hashes(
  34. event_ids
  35. )
  36. hashes = [
  37. {
  38. k: encode_base64(v) for k, v in h.items()
  39. if k == "sha256"
  40. }
  41. for h in hashes
  42. ]
  43. defer.returnValue(zip(event_ids, hashes))
  44. def _get_event_reference_hashes_txn(self, txn, event_id):
  45. """Get all the hashes for a given PDU.
  46. Args:
  47. txn (cursor):
  48. event_id (str): Id for the Event.
  49. Returns:
  50. A dict of algorithm -> hash.
  51. """
  52. query = (
  53. "SELECT algorithm, hash"
  54. " FROM event_reference_hashes"
  55. " WHERE event_id = ?"
  56. )
  57. txn.execute(query, (event_id, ))
  58. return {k: v for k, v in txn.fetchall()}
  59. def _store_event_reference_hashes_txn(self, txn, events):
  60. """Store a hash for a PDU
  61. Args:
  62. txn (cursor):
  63. events (list): list of Events.
  64. """
  65. vals = []
  66. for event in events:
  67. ref_alg, ref_hash_bytes = compute_event_reference_hash(event)
  68. vals.append({
  69. "event_id": event.event_id,
  70. "algorithm": ref_alg,
  71. "hash": buffer(ref_hash_bytes),
  72. })
  73. self._simple_insert_many_txn(
  74. txn,
  75. table="event_reference_hashes",
  76. values=vals,
  77. )