Class: Nem::Model::Message

Inherits:
Object
  • Object
show all
Includes:
Nem::Mixin::Assignable
Defined in:
lib/nem/model/message.rb

Constant Summary collapse

TYPE_PLAIN =
1
TYPE_ENCRYPTED =
2

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(value = '', type: :plain, private_key: nil, public_key: nil) ⇒ Message



24
25
26
27
28
29
# File 'lib/nem/model/message.rb', line 24

def initialize(value = '', type: :plain, private_key: nil, public_key: nil)
  @value = value
  @type = (type == :encrypted) ? TYPE_ENCRYPTED : TYPE_PLAIN
  @private_key = private_key
  @public_key = public_key
end

Instance Attribute Details

#payloadString



8
9
10
# File 'lib/nem/model/message.rb', line 8

def payload
  @payload
end

#private_keyString



8
9
10
# File 'lib/nem/model/message.rb', line 8

def private_key
  @private_key
end

#public_keyString



8
9
10
# File 'lib/nem/model/message.rb', line 8

def public_key
  @public_key
end

#typeInteger



8
9
10
# File 'lib/nem/model/message.rb', line 8

def type
  @type
end

#valueString



8
9
10
# File 'lib/nem/model/message.rb', line 8

def value
  @value
end

Class Method Details

.new_from_message(hash) ⇒ Object



17
18
19
20
21
22
# File 'lib/nem/model/message.rb', line 17

def self.new_from_message(hash)
  new(
    hash[:payload],
    type: (hash[:type] == TYPE_ENCRYPTED) ? :encrypted : :plain
  )
end

Instance Method Details

#==(other) ⇒ Boolean



76
77
78
# File 'lib/nem/model/message.rb', line 76

def ==(other)
  @value == other.value
end

#bytesizeInteger



56
57
58
# File 'lib/nem/model/message.rb', line 56

def bytesize
  payload.bytesize
end

#decrypt!Object



38
39
40
41
42
43
# File 'lib/nem/model/message.rb', line 38

def decrypt!
  bin_sk = fix_private_key(@private_key).scan(/../).map(&:hex).reverse.pack('C*')
  bin_pk = (public_key || @public_key).scan(/../).map(&:hex).pack('C*')
  @value = Nem::Util::Ed25519.decrypt(bin_sk, bin_pk, payload)
  @type = TYPE_PLAIN
end

#encrypt!Object



31
32
33
34
35
36
# File 'lib/nem/model/message.rb', line 31

def encrypt!
  bin_sk = fix_private_key(@private_key).scan(/../).map(&:hex).reverse.pack('C*')
  bin_pk = (public_key || @public_key).scan(/../).map(&:hex).pack('C*')
  @value = Nem::Util::Ed25519.encrypt(bin_sk, bin_pk, value)
  @type = TYPE_ENCRYPTED
end

#encrypted?Boolean



46
47
48
# File 'lib/nem/model/message.rb', line 46

def encrypted?
  @type == TYPE_ENCRYPTED
end

#plain?Boolean



51
52
53
# File 'lib/nem/model/message.rb', line 51

def plain?
  @type == TYPE_PLAIN
end

#to_hashHash



66
67
68
# File 'lib/nem/model/message.rb', line 66

def to_hash
  { payload: payload, type: @type }
end

#to_sString



71
72
73
# File 'lib/nem/model/message.rb', line 71

def to_s
  @value.to_s
end

#valid?Boolean



61
62
63
# File 'lib/nem/model/message.rb', line 61

def valid?
  bytesize <= 1024
end