func (u StellarMessage) GetError() (result Error, ok bool) {
	armName, _ := u.ArmForSwitch(int32(u.Type))

	if armName == "Error" {
		result = *u.Error
		ok = true
	}

	return
}

func ( u StellarMessage ) GetError ( ) ( result Error , ok bool ) { armName , _ := u . ArmForSwitch ( int32 ( u . Type ) ) if armName == " " { result = * u . Error ok = true } return }

// GetError retrieves the Error value from the union,
// returning ok if the union's switch indicated the value is valid.

GetError retrieves the Error value from the union returning ok if the union s switch indicated the value is valid .


func (u StellarMessage) MustHello() Hello {
	val, ok := u.GetHello()

	if !ok {
		panic("arm Hello is not set")
	}

	return val
}

func ( u StellarMessage ) MustHello ( ) Hello { val , ok := u . GetHello ( ) if ! ok { panic ( " " ) } return val }

// MustHello retrieves the Hello value from the union,
// panicing if the value is not set.

MustHello retrieves the Hello value from the union panicing if the value is not set .


func (u StellarMessage) GetHello() (result Hello, ok bool) {
	armName, _ := u.ArmForSwitch(int32(u.Type))

	if armName == "Hello" {
		result = *u.Hello
		ok = true
	}

	return
}

func ( u StellarMessage ) GetHello ( ) ( result Hello , ok bool ) { armName , _ := u . ArmForSwitch ( int32 ( u . Type ) ) if armName == " " { result = * u . Hello ok = true } return }

// GetHello retrieves the Hello value from the union,
// returning ok if the union's switch indicated the value is valid.

GetHello retrieves the Hello value from the union returning ok if the union s switch indicated the value is valid .


func (u StellarMessage) MustAuth() Auth {
	val, ok := u.GetAuth()

	if !ok {
		panic("arm Auth is not set")
	}

	return val
}

func ( u StellarMessage ) MustAuth ( ) Auth { val , ok := u . GetAuth ( ) if ! ok { panic ( " " ) } return val }

// MustAuth retrieves the Auth value from the union,
// panicing if the value is not set.

MustAuth retrieves the Auth value from the union panicing if the value is not set .


func (u StellarMessage) GetAuth() (result Auth, ok bool) {
	armName, _ := u.ArmForSwitch(int32(u.Type))

	if armName == "Auth" {
		result = *u.Auth
		ok = true
	}

	return
}

func ( u StellarMessage ) GetAuth ( ) ( result Auth , ok bool ) { armName , _ := u . ArmForSwitch ( int32 ( u . Type ) ) if armName == " " { result = * u . Auth ok = true } return }

// GetAuth retrieves the Auth value from the union,
// returning ok if the union's switch indicated the value is valid.

GetAuth retrieves the Auth value from the union returning ok if the union s switch indicated the value is valid .


func (u StellarMessage) MustDontHave() DontHave {
	val, ok := u.GetDontHave()

	if !ok {
		panic("arm DontHave is not set")
	}

	return val
}

func ( u StellarMessage ) MustDontHave ( ) DontHave { val , ok := u . GetDontHave ( ) if ! ok { panic ( " " ) } return val }

// MustDontHave retrieves the DontHave value from the union,
// panicing if the value is not set.

MustDontHave retrieves the DontHave value from the union panicing if the value is not set .


func (u StellarMessage) GetDontHave() (result DontHave, ok bool) {
	armName, _ := u.ArmForSwitch(int32(u.Type))

	if armName == "DontHave" {
		result = *u.DontHave
		ok = true
	}

	return
}

func ( u StellarMessage ) GetDontHave ( ) ( result DontHave , ok bool ) { armName , _ := u . ArmForSwitch ( int32 ( u . Type ) ) if armName == " " { result = * u . DontHave ok = true } return }

// GetDontHave retrieves the DontHave value from the union,
// returning ok if the union's switch indicated the value is valid.

GetDontHave retrieves the DontHave value from the union returning ok if the union s switch indicated the value is valid .


func (u StellarMessage) MustPeers() []PeerAddress {
	val, ok := u.GetPeers()

	if !ok {
		panic("arm Peers is not set")
	}

	return val
}

func ( u StellarMessage ) MustPeers ( ) [ ] PeerAddress { val , ok := u . GetPeers ( ) if ! ok { panic ( " " ) } return val }

// MustPeers retrieves the Peers value from the union,
// panicing if the value is not set.

MustPeers retrieves the Peers value from the union panicing if the value is not set .


func (u StellarMessage) GetPeers() (result []PeerAddress, ok bool) {
	armName, _ := u.ArmForSwitch(int32(u.Type))

	if armName == "Peers" {
		result = *u.Peers
		ok = true
	}

	return
}

func ( u StellarMessage ) GetPeers ( ) ( result [ ] PeerAddress , ok bool ) { armName , _ := u . ArmForSwitch ( int32 ( u . Type ) ) if armName == " " { result = * u . Peers ok = true } return }

// GetPeers retrieves the Peers value from the union,
// returning ok if the union's switch indicated the value is valid.

GetPeers retrieves the Peers value from the union returning ok if the union s switch indicated the value is valid .


func (u StellarMessage) MustTxSetHash() Uint256 {
	val, ok := u.GetTxSetHash()

	if !ok {
		panic("arm TxSetHash is not set")
	}

	return val
}

func ( u StellarMessage ) MustTxSetHash ( ) Uint256 { val , ok := u . GetTxSetHash ( ) if ! ok { panic ( " " ) } return val }

// MustTxSetHash retrieves the TxSetHash value from the union,
// panicing if the value is not set.

MustTxSetHash retrieves the TxSetHash value from the union panicing if the value is not set .


func (u StellarMessage) GetTxSetHash() (result Uint256, ok bool) {
	armName, _ := u.ArmForSwitch(int32(u.Type))

	if armName == "TxSetHash" {
		result = *u.TxSetHash
		ok = true
	}

	return
}

func ( u StellarMessage ) GetTxSetHash ( ) ( result Uint256 , ok bool ) { armName , _ := u . ArmForSwitch ( int32 ( u . Type ) ) if armName == " " { result = * u . TxSetHash ok = true } return }

// GetTxSetHash retrieves the TxSetHash value from the union,
// returning ok if the union's switch indicated the value is valid.

GetTxSetHash retrieves the TxSetHash value from the union returning ok if the union s switch indicated the value is valid .


func (u StellarMessage) MustTxSet() TransactionSet {
	val, ok := u.GetTxSet()

	if !ok {
		panic("arm TxSet is not set")
	}

	return val
}

func ( u StellarMessage ) MustTxSet ( ) TransactionSet { val , ok := u . GetTxSet ( ) if ! ok { panic ( " " ) } return val }

// MustTxSet retrieves the TxSet value from the union,
// panicing if the value is not set.

MustTxSet retrieves the TxSet value from the union panicing if the value is not set .


func (u StellarMessage) GetTxSet() (result TransactionSet, ok bool) {
	armName, _ := u.ArmForSwitch(int32(u.Type))

	if armName == "TxSet" {
		result = *u.TxSet
		ok = true
	}

	return
}

func ( u StellarMessage ) GetTxSet ( ) ( result TransactionSet , ok bool ) { armName , _ := u . ArmForSwitch ( int32 ( u . Type ) ) if armName == " " { result = * u . TxSet ok = true } return }

// GetTxSet retrieves the TxSet value from the union,
// returning ok if the union's switch indicated the value is valid.

GetTxSet retrieves the TxSet value from the union returning ok if the union s switch indicated the value is valid .


func (u StellarMessage) MustTransaction() TransactionEnvelope {
	val, ok := u.GetTransaction()

	if !ok {
		panic("arm Transaction is not set")
	}

	return val
}

func ( u StellarMessage ) MustTransaction ( ) TransactionEnvelope { val , ok := u . GetTransaction ( ) if ! ok { panic ( " " ) } return val }

// MustTransaction retrieves the Transaction value from the union,
// panicing if the value is not set.

MustTransaction retrieves the Transaction value from the union panicing if the value is not set .


func (u StellarMessage) GetTransaction() (result TransactionEnvelope, ok bool) {
	armName, _ := u.ArmForSwitch(int32(u.Type))

	if armName == "Transaction" {
		result = *u.Transaction
		ok = true
	}

	return
}

func ( u StellarMessage ) GetTransaction ( ) ( result TransactionEnvelope , ok bool ) { armName , _ := u . ArmForSwitch ( int32 ( u . Type ) ) if armName == " " { result = * u . Transaction ok = true } return }

// GetTransaction retrieves the Transaction value from the union,
// returning ok if the union's switch indicated the value is valid.

GetTransaction retrieves the Transaction value from the union returning ok if the union s switch indicated the value is valid .


func (u StellarMessage) MustQSetHash() Uint256 {
	val, ok := u.GetQSetHash()

	if !ok {
		panic("arm QSetHash is not set")
	}

	return val
}

func ( u StellarMessage ) MustQSetHash ( ) Uint256 { val , ok := u . GetQSetHash ( ) if ! ok { panic ( " " ) } return val }

// MustQSetHash retrieves the QSetHash value from the union,
// panicing if the value is not set.

MustQSetHash retrieves the QSetHash value from the union panicing if the value is not set .


func (u StellarMessage) GetQSetHash() (result Uint256, ok bool) {
	armName, _ := u.ArmForSwitch(int32(u.Type))

	if armName == "QSetHash" {
		result = *u.QSetHash
		ok = true
	}

	return
}

func ( u StellarMessage ) GetQSetHash ( ) ( result Uint256 , ok bool ) { armName , _ := u . ArmForSwitch ( int32 ( u . Type ) ) if armName == " " { result = * u . QSetHash ok = true } return }

// GetQSetHash retrieves the QSetHash value from the union,
// returning ok if the union's switch indicated the value is valid.

GetQSetHash retrieves the QSetHash value from the union returning ok if the union s switch indicated the value is valid .


func (u StellarMessage) MustQSet() ScpQuorumSet {
	val, ok := u.GetQSet()

	if !ok {
		panic("arm QSet is not set")
	}

	return val
}

func ( u StellarMessage ) MustQSet ( ) ScpQuorumSet { val , ok := u . GetQSet ( ) if ! ok { panic ( " " ) } return val }

// MustQSet retrieves the QSet value from the union,
// panicing if the value is not set.

MustQSet retrieves the QSet value from the union panicing if the value is not set .


func (u StellarMessage) GetQSet() (result ScpQuorumSet, ok bool) {
	armName, _ := u.ArmForSwitch(int32(u.Type))

	if armName == "QSet" {
		result = *u.QSet
		ok = true
	}

	return
}

func ( u StellarMessage ) GetQSet ( ) ( result ScpQuorumSet , ok bool ) { armName , _ := u . ArmForSwitch ( int32 ( u . Type ) ) if armName == " " { result = * u . QSet ok = true } return }

// GetQSet retrieves the QSet value from the union,
// returning ok if the union's switch indicated the value is valid.

GetQSet retrieves the QSet value from the union returning ok if the union s switch indicated the value is valid .


func (u StellarMessage) MustEnvelope() ScpEnvelope {
	val, ok := u.GetEnvelope()

	if !ok {
		panic("arm Envelope is not set")
	}

	return val
}

func ( u StellarMessage ) MustEnvelope ( ) ScpEnvelope { val , ok := u . GetEnvelope ( ) if ! ok { panic ( " " ) } return val }

// MustEnvelope retrieves the Envelope value from the union,
// panicing if the value is not set.

MustEnvelope retrieves the Envelope value from the union panicing if the value is not set .


func (u StellarMessage) GetEnvelope() (result ScpEnvelope, ok bool) {
	armName, _ := u.ArmForSwitch(int32(u.Type))

	if armName == "Envelope" {
		result = *u.Envelope
		ok = true
	}

	return
}

func ( u StellarMessage ) GetEnvelope ( ) ( result ScpEnvelope , ok bool ) { armName , _ := u . ArmForSwitch ( int32 ( u . Type ) ) if armName == " " { result = * u . Envelope ok = true } return }

// GetEnvelope retrieves the Envelope value from the union,
// returning ok if the union's switch indicated the value is valid.

GetEnvelope retrieves the Envelope value from the union returning ok if the union s switch indicated the value is valid .


func (u StellarMessage) MustGetScpLedgerSeq() Uint32 {
	val, ok := u.GetGetScpLedgerSeq()

	if !ok {
		panic("arm GetScpLedgerSeq is not set")
	}

	return val
}

func ( u StellarMessage ) MustGetScpLedgerSeq ( ) Uint32 { val , ok := u . GetGetScpLedgerSeq ( ) if ! ok { panic ( " " ) } return val }

// MustGetScpLedgerSeq retrieves the GetScpLedgerSeq value from the union,
// panicing if the value is not set.

MustGetScpLedgerSeq retrieves the GetScpLedgerSeq value from the union panicing if the value is not set .


func (u StellarMessage) GetGetScpLedgerSeq() (result Uint32, ok bool) {
	armName, _ := u.ArmForSwitch(int32(u.Type))

	if armName == "GetScpLedgerSeq" {
		result = *u.GetScpLedgerSeq
		ok = true
	}

	return
}

func ( u StellarMessage ) GetGetScpLedgerSeq ( ) ( result Uint32 , ok bool ) { armName , _ := u . ArmForSwitch ( int32 ( u . Type ) ) if armName == " " { result = * u . GetScpLedgerSeq ok = true } return }

// GetGetScpLedgerSeq retrieves the GetScpLedgerSeq value from the union,
// returning ok if the union's switch indicated the value is valid.

GetGetScpLedgerSeq retrieves the GetScpLedgerSeq value from the union returning ok if the union s switch indicated the value is valid .


func (u AuthenticatedMessage) ArmForSwitch(sw int32) (string, bool) {
	switch Uint32(sw) {
	case 0:
		return "V0", true
	}
	return "-", false
}

func ( u AuthenticatedMessage ) ArmForSwitch ( sw int32 ) ( string , bool ) { switch Uint32 ( sw ) { case 0 : return " " , true } return " " , false }

// ArmForSwitch returns which field name should be used for storing
// the value for an instance of AuthenticatedMessage

ArmForSwitch returns which field name should be used for storing the value for an instance of AuthenticatedMessage


func NewAuthenticatedMessage(v Uint32, value interface{}) (result AuthenticatedMessage, err error) {
	result.V = v
	switch Uint32(v) {
	case 0:
		tv, ok := value.(AuthenticatedMessageV0)
		if !ok {
			err = fmt.Errorf("invalid value, must be AuthenticatedMessageV0")
			return
		}
		result.V0 = &tv
	}
	return
}

func NewAuthenticatedMessage ( v Uint32 , value interface { } ) ( result AuthenticatedMessage , err error ) { result . V = v switch Uint32 ( v ) { case 0 : tv , ok := value . ( AuthenticatedMessageV0 ) if ! ok { err = fmt . Errorf ( " " ) return } result . V0 = & tv } return }

// NewAuthenticatedMessage creates a new  AuthenticatedMessage.

NewAuthenticatedMessage creates a new AuthenticatedMessage .


func (e ScpStatementType) ValidEnum(v int32) bool {
	_, ok := scpStatementTypeMap[v]
	return ok
}

func ( e ScpStatementType ) ValidEnum ( v int32 ) bool { _ , ok := scpStatementTypeMap [ v ] return ok }

// ValidEnum validates a proposed value for this enum.  Implements
// the Enum interface for ScpStatementType

ValidEnum validates a proposed value for this enum . Implements the Enum interface for ScpStatementType


func (u ScpStatementPledges) ArmForSwitch(sw int32) (string, bool) {
	switch ScpStatementType(sw) {
	case ScpStatementTypeScpStPrepare:
		return "Prepare", true
	case ScpStatementTypeScpStConfirm:
		return "Confirm", true
	case ScpStatementTypeScpStExternalize:
		return "Externalize", true
	case ScpStatementTypeScpStNominate:
		return "Nominate", true
	}
	return "-", false
}

func ( u ScpStatementPledges ) ArmForSwitch ( sw int32 ) ( string , bool ) { switch ScpStatementType ( sw ) { case ScpStatementTypeScpStPrepare : return " " , true case ScpStatementTypeScpStConfirm : return " " , true case ScpStatementTypeScpStExternalize : return " " , true case ScpStatementTypeScpStNominate : return " " , true } return " " , false }

// ArmForSwitch returns which field name should be used for storing
// the value for an instance of ScpStatementPledges

ArmForSwitch returns which field name should be used for storing the value for an instance of ScpStatementPledges


func NewScpStatementPledges(aType ScpStatementType, value interface{}) (result ScpStatementPledges, err error) {
	result.Type = aType
	switch ScpStatementType(aType) {
	case ScpStatementTypeScpStPrepare:
		tv, ok := value.(ScpStatementPrepare)
		if !ok {
			err = fmt.Errorf("invalid value, must be ScpStatementPrepare")
			return
		}
		result.Prepare = &tv
	case ScpStatementTypeScpStConfirm:
		tv, ok := value.(ScpStatementConfirm)
		if !ok {
			err = fmt.Errorf("invalid value, must be ScpStatementConfirm")
			return
		}
		result.Confirm = &tv
	case ScpStatementTypeScpStExternalize:
		tv, ok := value.(ScpStatementExternalize)
		if !ok {
			err = fmt.Errorf("invalid value, must be ScpStatementExternalize")
			return
		}
		result.Externalize = &tv
	case ScpStatementTypeScpStNominate:
		tv, ok := value.(ScpNomination)
		if !ok {
			err = fmt.Errorf("invalid value, must be ScpNomination")
			return
		}
		result.Nominate = &tv
	}
	return
}

func NewScpStatementPledges ( aType ScpStatementType , value interface { } ) ( result ScpStatementPledges , err error ) { result . Type = aType switch ScpStatementType ( aType ) { case ScpStatementTypeScpStPrepare : tv , ok := value . ( ScpStatementPrepare ) if ! ok { err = fmt . Errorf ( " " ) return } result . Prepare = & tv case ScpStatementTypeScpStConfirm : tv , ok := value . ( ScpStatementConfirm ) if ! ok { err = fmt . Errorf ( " " ) return } result . Confirm = & tv case ScpStatementTypeScpStExternalize : tv , ok := value . ( ScpStatementExternalize ) if ! ok { err = fmt . Errorf ( " " ) return } result . Externalize = & tv case ScpStatementTypeScpStNominate : tv , ok := value . ( ScpNomination ) if ! ok { err = fmt . Errorf ( " " ) return } result . Nominate = & tv } return }

// NewScpStatementPledges creates a new  ScpStatementPledges.

NewScpStatementPledges creates a new ScpStatementPledges .


func (u ScpStatementPledges) MustPrepare() ScpStatementPrepare {
	val, ok := u.GetPrepare()

	if !ok {
		panic("arm Prepare is not set")
	}

	return val
}

func ( u ScpStatementPledges ) MustPrepare ( ) ScpStatementPrepare { val , ok := u . GetPrepare ( ) if ! ok { panic ( " " ) } return val }

// MustPrepare retrieves the Prepare value from the union,
// panicing if the value is not set.

MustPrepare retrieves the Prepare value from the union panicing if the value is not set .


func (u ScpStatementPledges) GetPrepare() (result ScpStatementPrepare, ok bool) {
	armName, _ := u.ArmForSwitch(int32(u.Type))

	if armName == "Prepare" {
		result = *u.Prepare
		ok = true
	}

	return
}

func ( u ScpStatementPledges ) GetPrepare ( ) ( result ScpStatementPrepare , ok bool ) { armName , _ := u . ArmForSwitch ( int32 ( u . Type ) ) if armName == " " { result = * u . Prepare ok = true } return }

// GetPrepare retrieves the Prepare value from the union,
// returning ok if the union's switch indicated the value is valid.

GetPrepare retrieves the Prepare value from the union returning ok if the union s switch indicated the value is valid .


func (u ScpStatementPledges) MustConfirm() ScpStatementConfirm {
	val, ok := u.GetConfirm()

	if !ok {
		panic("arm Confirm is not set")
	}

	return val
}

func ( u ScpStatementPledges ) MustConfirm ( ) ScpStatementConfirm { val , ok := u . GetConfirm ( ) if ! ok { panic ( " " ) } return val }

// MustConfirm retrieves the Confirm value from the union,
// panicing if the value is not set.

MustConfirm retrieves the Confirm value from the union panicing if the value is not set .


func (u ScpStatementPledges) GetConfirm() (result ScpStatementConfirm, ok bool) {
	armName, _ := u.ArmForSwitch(int32(u.Type))

	if armName == "Confirm" {
		result = *u.Confirm
		ok = true
	}

	return
}

func ( u ScpStatementPledges ) GetConfirm ( ) ( result ScpStatementConfirm , ok bool ) { armName , _ := u . ArmForSwitch ( int32 ( u . Type ) ) if armName == " " { result = * u . Confirm ok = true } return }

// GetConfirm retrieves the Confirm value from the union,
// returning ok if the union's switch indicated the value is valid.

GetConfirm retrieves the Confirm value from the union returning ok if the union s switch indicated the value is valid .


func (u ScpStatementPledges) MustExternalize() ScpStatementExternalize {
	val, ok := u.GetExternalize()

	if !ok {
		panic("arm Externalize is not set")
	}

	return val
}

func ( u ScpStatementPledges ) MustExternalize ( ) ScpStatementExternalize { val , ok := u . GetExternalize ( ) if ! ok { panic ( " " ) } return val }

// MustExternalize retrieves the Externalize value from the union,
// panicing if the value is not set.

MustExternalize retrieves the Externalize value from the union panicing if the value is not set .


func (u ScpStatementPledges) GetExternalize() (result ScpStatementExternalize, ok bool) {
	armName, _ := u.ArmForSwitch(int32(u.Type))

	if armName == "Externalize" {
		result = *u.Externalize
		ok = true
	}

	return
}

func ( u ScpStatementPledges ) GetExternalize ( ) ( result ScpStatementExternalize , ok bool ) { armName , _ := u . ArmForSwitch ( int32 ( u . Type ) ) if armName == " " { result = * u . Externalize ok = true } return }

// GetExternalize retrieves the Externalize value from the union,
// returning ok if the union's switch indicated the value is valid.

GetExternalize retrieves the Externalize value from the union returning ok if the union s switch indicated the value is valid .


func (u ScpStatementPledges) MustNominate() ScpNomination {
	val, ok := u.GetNominate()

	if !ok {
		panic("arm Nominate is not set")
	}

	return val
}

func ( u ScpStatementPledges ) MustNominate ( ) ScpNomination { val , ok := u . GetNominate ( ) if ! ok { panic ( " " ) } return val }

// MustNominate retrieves the Nominate value from the union,
// panicing if the value is not set.

MustNominate retrieves the Nominate value from the union panicing if the value is not set .


func (u ScpStatementPledges) GetNominate() (result ScpNomination, ok bool) {
	armName, _ := u.ArmForSwitch(int32(u.Type))

	if armName == "Nominate" {
		result = *u.Nominate
		ok = true
	}

	return
}

func ( u ScpStatementPledges ) GetNominate ( ) ( result ScpNomination , ok bool ) { armName , _ := u . ArmForSwitch ( int32 ( u . Type ) ) if armName == " " { result = * u . Nominate ok = true } return }

// GetNominate retrieves the Nominate value from the union,
// returning ok if the union's switch indicated the value is valid.

GetNominate retrieves the Nominate value from the union returning ok if the union s switch indicated the value is valid .


func SafeUnmarshalBase64(data string, dest interface{}) error {
	count := &countWriter{}
	l := len(data)

	b64 := io.TeeReader(strings.NewReader(data), count)
	raw := base64.NewDecoder(base64.StdEncoding, b64)
	_, err := Unmarshal(raw, dest)

	if err != nil {
		return err
	}

	if count.Count != l {
		return fmt.Errorf("input not fully consumed. expected to read: %d, actual: %d", l, count.Count)
	}

	return nil
}

func SafeUnmarshalBase64 ( data string , dest interface { } ) error { count := & countWriter { } l := len ( data ) b64 := io . TeeReader ( strings . NewReader ( data ) , count ) raw := base64 . NewDecoder ( base64 . StdEncoding , b64 ) _ , err := Unmarshal ( raw , dest ) if err != nil { return err } if count . Count != l { return fmt . Errorf ( " " , l , count . Count ) } return nil }

// SafeUnmarshalBase64 first decodes the provided reader from base64 before decoding the xdr
// into the provided destination.  Also ensures that the reader is fully consumed.

SafeUnmarshalBase64 first decodes the provided reader from base64 before decoding the xdr into the provided destination . Also ensures that the reader is fully consumed .


func SafeUnmarshal(data []byte, dest interface{}) error {
	r := bytes.NewReader(data)
	n, err := Unmarshal(r, dest)

	if err != nil {
		return err
	}

	if n != len(data) {
		return fmt.Errorf("input not fully consumed. expected to read: %d, actual: %d", len(data), n)
	}

	return nil
}

func SafeUnmarshal ( data [ ] byte , dest interface { } ) error { r := bytes . NewReader ( data ) n , err := Unmarshal ( r , dest ) if err != nil { return err } if n != len ( data ) { return fmt . Errorf ( " " , len ( data ) , n ) } return nil }

// SafeUnmarshal decodes the provided reader into the destination and verifies
// that provided bytes are all consumed by the unmarshalling process.

SafeUnmarshal decodes the provided reader into the destination and verifies that provided bytes are all consumed by the unmarshalling process .


func (pr *PathPaymentResult) SendAmount() Int64 {
	s, ok := pr.GetSuccess()
	if !ok {
		return 0
	}

	if len(s.Offers) == 0 {
		return s.Last.Amount
	}

	sa := s.Offers[0].AssetBought
	var ret Int64

	for _, o := range s.Offers {
		if o.AssetBought.String() != sa.String() {
			break
		}
		ret += o.AmountBought
	}

	return ret
}

func ( pr * PathPaymentResult ) SendAmount ( ) Int64 { s , ok := pr . GetSuccess ( ) if ! ok { return 0 } if len ( s . Offers ) == 0 { return s . Last . Amount } sa := s . Offers [ 0 ] . AssetBought var ret Int64 for _ , o := range s . Offers { if o . AssetBought . String ( ) != sa . String ( ) { break } ret += o . AmountBought } return ret }

// SendAmount returns the amount spent, denominated in the source asset, in the
// course of this path payment

SendAmount returns the amount spent denominated in the source asset in the course of this path payment


func (c *Client) LoadAccount(accountID string) (account Account, err error) {
	c.initHTTPClient()
	resp, err := c.Client.Get(c.URL + "/accounts/" + accountID)
	if err != nil {
		return
	}

	err = decodeResponse(resp, &account)
	return
}

func ( c * Client ) LoadAccount ( accountID string ) ( account Account , err error ) { c . initHTTPClient ( ) resp , err := c . Client . Get ( c . URL + " " + accountID ) if err != nil { return } err = decodeResponse ( resp , & account ) return }

// LoadAccount loads the account state from horizon. err can be either error
// object or horizon.Error object.

LoadAccount loads the account state from horizon . err can be either error object or horizon . Error object .


func (c *Client) SequenceForAccount(
	accountID string,
) (xdr.SequenceNumber, error) {

	a, err := c.LoadAccount(accountID)
	if err != nil {
		return 0, err
	}

	seq, err := strconv.ParseUint(a.Sequence, 10, 64)
	if err != nil {
		return 0, err
	}

	return xdr.SequenceNumber(seq), nil
}

func ( c * Client ) SequenceForAccount ( accountID string , ) ( xdr . SequenceNumber , error ) { a , err := c . LoadAccount ( accountID ) if err != nil { return 0 , err } seq , err := strconv . ParseUint ( a . Sequence , 10 , 64 ) if err != nil { return 0 , err } return xdr . SequenceNumber ( seq ) , nil }

// SequenceForAccount implements build.SequenceProvider

SequenceForAccount implements build . SequenceProvider


func (c *Client) SubmitTransaction(transactionEnvelopeXdr string) (response TransactionSuccess, err error) {
	v := url.Values{}
	v.Set("tx", transactionEnvelopeXdr)

	c.initHTTPClient()
	resp, err := c.Client.PostForm(c.URL+"/transactions", v)
	if err != nil {
		return
	}

	err = decodeResponse(resp, &response)
	return
}

func ( c * Client ) SubmitTransaction ( transactionEnvelopeXdr string ) ( response TransactionSuccess , err error ) { v := url . Values { } v . Set ( " " , transactionEnvelopeXdr ) c . initHTTPClient ( ) resp , err := c . Client . PostForm ( c . URL + " " , v ) if err != nil { return } err = decodeResponse ( resp , & response ) return }

// SubmitTransaction submits a transaction to the network. err can be either error object or horizon.Error object.

SubmitTransaction submits a transaction to the network . err can be either error object or horizon . Error object .


func (key *LedgerKey) Equals(other LedgerKey) bool {
	if key.Type != other.Type {
		return false
	}

	switch key.Type {
	case LedgerEntryTypeAccount:
		l := key.MustAccount()
		r := other.MustAccount()
		return l.AccountId.Equals(r.AccountId)
	case LedgerEntryTypeData:
		l := key.MustData()
		r := other.MustData()
		return l.AccountId.Equals(r.AccountId) && l.DataName == r.DataName
	case LedgerEntryTypeOffer:
		l := key.MustOffer()
		r := other.MustOffer()
		return l.SellerId.Equals(r.SellerId) && l.OfferId == r.OfferId
	case LedgerEntryTypeTrustline:
		l := key.MustTrustLine()
		r := other.MustTrustLine()
		return l.AccountId.Equals(r.AccountId) && l.Asset.Equals(r.Asset)
	default:
		panic(fmt.Errorf("Unknown ledger key type: %v", key.Type))
	}
}

func ( key * LedgerKey ) Equals ( other LedgerKey ) bool { if key . Type != other . Type { return false } switch key . Type { case LedgerEntryTypeAccount : l := key . MustAccount ( ) r := other . MustAccount ( ) return l . AccountId . Equals ( r . AccountId ) case LedgerEntryTypeData : l := key . MustData ( ) r := other . MustData ( ) return l . AccountId . Equals ( r . AccountId ) && l . DataName == r . DataName case LedgerEntryTypeOffer : l := key . MustOffer ( ) r := other . MustOffer ( ) return l . SellerId . Equals ( r . SellerId ) && l . OfferId == r . OfferId case LedgerEntryTypeTrustline : l := key . MustTrustLine ( ) r := other . MustTrustLine ( ) return l . AccountId . Equals ( r . AccountId ) && l . Asset . Equals ( r . Asset ) default : panic ( fmt . Errorf ( " " , key . Type ) ) } }

// Equals returns true if `other` is equivalent to `key`

Equals returns true if other is equivalent to key


func (key *LedgerKey) SetAccount(account AccountId) error {
	data := LedgerKeyAccount{account}
	nkey, err := NewLedgerKey(LedgerEntryTypeAccount, data)
	if err != nil {
		return err
	}

	*key = nkey
	return nil
}

func ( key * LedgerKey ) SetAccount ( account AccountId ) error { data := LedgerKeyAccount { account } nkey , err := NewLedgerKey ( LedgerEntryTypeAccount , data ) if err != nil { return err } * key = nkey return nil }

// SetAccount mutates `key` such that it represents the identity of `account`

SetAccount mutates key such that it represents the identity of account


func (key *LedgerKey) SetData(account AccountId, name string) error {
	data := LedgerKeyData{account, String64(name)}
	nkey, err := NewLedgerKey(LedgerEntryTypeData, data)
	if err != nil {
		return err
	}

	*key = nkey
	return nil
}

func ( key * LedgerKey ) SetData ( account AccountId , name string ) error { data := LedgerKeyData { account , String64 ( name ) } nkey , err := NewLedgerKey ( LedgerEntryTypeData , data ) if err != nil { return err } * key = nkey return nil }

// SetData mutates `key` such that it represents the identity of the
// data entry owned by `account` and for `name`.

SetData mutates key such that it represents the identity of the data entry owned by account and for name .


func (key *LedgerKey) SetOffer(account AccountId, id uint64) error {
	data := LedgerKeyOffer{account, Uint64(id)}
	nkey, err := NewLedgerKey(LedgerEntryTypeOffer, data)
	if err != nil {
		return err
	}

	*key = nkey
	return nil
}

func ( key * LedgerKey ) SetOffer ( account AccountId , id uint64 ) error { data := LedgerKeyOffer { account , Uint64 ( id ) } nkey , err := NewLedgerKey ( LedgerEntryTypeOffer , data ) if err != nil { return err } * key = nkey return nil }

// SetOffer mutates `key` such that it represents the identity of the
// data entry owned by `account` and for offer `id`.

SetOffer mutates key such that it represents the identity of the data entry owned by account and for offer id .


func (key *LedgerKey) SetTrustline(account AccountId, line Asset) error {
	data := LedgerKeyTrustLine{account, line}
	nkey, err := NewLedgerKey(LedgerEntryTypeTrustline, data)
	if err != nil {
		return err
	}

	*key = nkey
	return nil
}

func ( key * LedgerKey ) SetTrustline ( account AccountId , line Asset ) error { data := LedgerKeyTrustLine { account , line } nkey , err := NewLedgerKey ( LedgerEntryTypeTrustline , data ) if err != nil { return err } * key = nkey return nil }

// SetTrustline mutates `key` such that it represents the identity of the
// trustline owned by `account` and for `asset`.

SetTrustline mutates key such that it represents the identity of the trustline owned by account and for asset .


func (b *CHDBuilder) Add(key []byte, value []byte) {
	b.keys = append(b.keys, key)
	b.values = append(b.values, value)
}

func ( b * CHDBuilder ) Add ( key [ ] byte , value [ ] byte ) { b . keys = append ( b . keys , key ) b . values = append ( b . values , value ) }

// Add a key and value to the hash table.


func tryHash(hasher *chdHasher, seen map[uint64]bool, keys [][]byte, values [][]byte, indices []uint16, bucket *bucket, ri uint16, r uint64) bool {
	// Track duplicates within this bucket.
	duplicate := make(map[uint64]bool)
	// Make hashes for each entry in the bucket.
	hashes := make([]uint64, len(bucket.keys))
	for i, k := range bucket.keys {
		h := hasher.Table(r, k)
		hashes[i] = h
		if seen[h] {
			return false
		}
		if duplicate[h] {
			return false
		}
		duplicate[h] = true
	}

	// Update seen hashes
	for _, h := range hashes {
		seen[h] = true
	}

	// Add the hash index.
	indices[bucket.index] = ri

	// Update the the hash table.
	for i, h := range hashes {
		keys[h] = bucket.keys[i]
		values[h] = bucket.values[i]
	}
	return true
}

// Try to find a hash function that does not cause collisions with table, when
// applied to the keys in the bucket.

Try to find a hash function that does not cause collisions with table when applied to the keys in the bucket .


func (h *chdHasher) HashIndexFromKey(b []byte) uint64 {
	return (hasher(b) ^ h.r[0]) % h.buckets
}

func ( h * chdHasher ) HashIndexFromKey ( b [ ] byte ) uint64 { return ( hasher ( b ) ^ h . r [ 0 ] ) % h . buckets }


func (b *sliceReader) ReadInt() uint64 {
	return uint64(binary.LittleEndian.Uint32(b.Read(4)))
}

func ( b * sliceReader ) ReadInt ( ) uint64 { return uint64 ( binary . LittleEndian . Uint32 ( b . Read ( 4 ) ) ) }

// Despite returning a uint64, this actually reads a uint32. All table indices
// and lengths are stored as uint32 values.

Despite returning a uint64 this actually reads a uint32 . All table indices and lengths are stored as uint32 values .


func Read(r io.Reader) (*CHD, error) {
	b, err := ioutil.ReadAll(r)
	if err != nil {
		return nil, err
	}
	return Mmap(b)
}

func Read ( r io . Reader ) ( * CHD , error ) { b , err := ioutil . ReadAll ( r ) if err != nil { return nil , err } return Mmap ( b ) }


func (c *CHD) Get(key []byte) []byte {
	r0 := c.r[0]
	h := hasher(key) ^ r0
	i := h % uint64(len(c.indices))
	ri := c.indices[i]
	// This can occur if there were unassigned slots in the hash table.
	if ri >= uint16(len(c.r)) {
		return nil
	}
	r := c.r[ri]
	ti := (h ^ r) % uint64(len(c.keys))
	// fmt.Printf("r[0]=%d, h=%d, i=%d, ri=%d, r=%d, ti=%d\n", c.r[0], h, i, ri, r, ti)
	k := c.keys[ti]
	if bytes.Compare(k, key) != 0 {
		return nil
	}
	v := c.values[ti]
	return v
}


func (c *CHD) Iterate() *Iterator {
	if len(c.keys) == 0 {
		return nil
	}
	return &Iterator{c: c}
}

func ( c * CHD ) Iterate ( ) * Iterator { if len ( c . keys ) == 0 { return nil } return & Iterator { c : c } }

// Iterate over entries in the hash table.

Iterate over entries in the hash table .


func (c *CHD) Write(w io.Writer) error {
	write := func(nd ...interface{}) error {
		for _, d := range nd {
			if err := binary.Write(w, binary.LittleEndian, d); err != nil {
				return err
			}
		}
		return nil
	}

	data := []interface{}{
		uint32(len(c.r)), c.r,
		uint32(len(c.indices)), c.indices,
		uint32(len(c.keys)),
	}

	if err := write(data...); err != nil {
		return err
	}

	for i := range c.keys {
		k, v := c.keys[i], c.values[i]
		if err := write(uint32(len(k)), uint32(len(v))); err != nil {
			return err
		}
		if _, err := w.Write(k); err != nil {
			return err
		}
		if _, err := w.Write(v); err != nil {
			return err
		}
	}
	return nil
}

func ( c * CHD ) Write ( w io . Writer ) error { write := func ( nd ... interface { } ) error { for _ , d := range nd { if err := binary . Write ( w , binary . LittleEndian , d ) ; err != nil { return err } } return nil } data := [ ] interface { } { uint32 ( len ( c . r ) ) , c . r , uint32 ( len ( c . indices ) ) , c . indices , uint32 ( len ( c . keys ) ) , } if err := write ( data ... ) ; err != nil { return err } for i := range c . keys { k , v := c . keys [ i ] , c . values [ i ] if err := write ( uint32 ( len ( k ) ) , uint32 ( len ( v ) ) ) ; err != nil { return err } if _ , err := w . Write ( k ) ; err != nil { return err } if _ , err := w . Write ( v ) ; err != nil { return err } } return nil }

// Serialize the CHD. The serialized form is conducive to mmapped access. See
// the Mmap function for details.

Serialize the CHD . The serialized form is conducive to mmapped access . See the Mmap function for details .


func RegisterDatasources(path string) error {
	cs := C.CString(path)
	defer C.free(unsafe.Pointer(cs))
	if C.mapnik_register_datasources(cs) == 0 {
		e := C.GoString(C.mapnik_register_last_error())
		if e != "" {
			return errors.New("registering datasources: " + e)
		}
		return errors.New("error while registering datasources")
	}
	return nil
}

func RegisterDatasources ( path string ) error { cs := C . CString ( path ) defer C . free ( unsafe . Pointer ( cs ) ) if C . mapnik_register_datasources ( cs ) == 0 { e := C . GoString ( C . mapnik_register_last_error ( ) ) if e != " " { return errors . New ( " " + e ) } return errors . New ( " " ) } return nil }

// RegisterDatasources adds path to the Mapnik plugin search path.

RegisterDatasources adds path to the Mapnik plugin search path .


func RegisterFonts(path string) error {
	cs := C.CString(path)
	defer C.free(unsafe.Pointer(cs))
	if C.mapnik_register_fonts(cs) == 0 {
		e := C.GoString(C.mapnik_register_last_error())
		if e != "" {
			return errors.New("registering fonts: " + e)
		}
		return errors.New("error while registering fonts")
	}
	return nil
}

func RegisterFonts ( path string ) error { cs := C . CString ( path ) defer C . free ( unsafe . Pointer ( cs ) ) if C . mapnik_register_fonts ( cs ) == 0 { e := C . GoString ( C . mapnik_register_last_error ( ) ) if e != " " { return errors . New ( " " + e ) } return errors . New ( " " ) } return nil }

// RegisterDatasources adds path to the Mapnik fonts search path.

RegisterDatasources adds path to the Mapnik fonts search path .


func New() *Map {
	return &Map{
		m:      C.mapnik_map(C.uint(800), C.uint(600)),
		width:  800,
		height: 600,
	}
}

func New ( ) * Map { return & Map { m : C . mapnik_map ( C . uint ( 800 ) , C . uint ( 600 ) ) , width : 800 , height : 600 , } }


func NewSized(width, height int) *Map {
	return &Map{
		m:      C.mapnik_map(C.uint(width), C.uint(height)),
		width:  width,
		height: height,
	}
}

func NewSized ( width , height int ) * Map { return & Map { m : C . mapnik_map ( C . uint ( width ) , C . uint ( height ) ) , width : width , height : height , } }

// NewSized initializes a new Map with the given size.

NewSized initializes a new Map with the given size .


func (m *Map) Load(stylesheet string) error {
	cs := C.CString(stylesheet)
	defer C.free(unsafe.Pointer(cs))
	if C.mapnik_map_load(m.m, cs) != 0 {
		return m.lastError()
	}
	return nil
}

func ( m * Map ) Load ( stylesheet string ) error { cs := C . CString ( stylesheet ) defer C . free ( unsafe . Pointer ( cs ) ) if C . mapnik_map_load ( m . m , cs ) != 0 { return m . lastError ( ) } return nil }


func (m *Map) Resize(width, height int) {
	C.mapnik_map_resize(m.m, C.uint(width), C.uint(height))
	m.width = width
	m.height = height
}

func ( m * Map ) Resize ( width , height int ) { C . mapnik_map_resize ( m . m , C . uint ( width ) , C . uint ( height ) ) m . width = width m . height = height }

// Resize changes the map size in pixel.
// Sizes larger than 16k pixels are ignored by Mapnik. Use NewSized
// to initialize larger maps.

Resize changes the map size in pixel . Sizes larger than 16k pixels are ignored by Mapnik . Use NewSized to initialize larger maps .


func (m *Map) Free() {
	C.mapnik_map_free(m.m)
	m.m = nil
}

func ( m * Map ) Free ( ) { C . mapnik_map_free ( m . m ) m . m = nil }


func (m *Map) SRS() string {
	return C.GoString(C.mapnik_map_get_srs(m.m))
}

func ( m * Map ) SRS ( ) string { return C . GoString ( C . mapnik_map_get_srs ( m . m ) ) }

// SRS returns the projection of the map.


func (m *Map) ZoomAll() error {
	if C.mapnik_map_zoom_all(m.m) != 0 {
		return m.lastError()
	}
	return nil
}

func ( m * Map ) ZoomAll ( ) error { if C . mapnik_map_zoom_all ( m . m ) != 0 { return m . lastError ( ) } return nil }


func (m *Map) ZoomTo(minx, miny, maxx, maxy float64) {
	bbox := C.mapnik_bbox(C.double(minx), C.double(miny), C.double(maxx), C.double(maxy))
	defer C.mapnik_bbox_free(bbox)
	C.mapnik_map_zoom_to_box(m.m, bbox)
}

func ( m * Map ) ZoomTo ( minx , miny , maxx , maxy float64 ) { bbox := C . mapnik_bbox ( C . double ( minx ) , C . double ( miny ) , C . double ( maxx ) , C . double ( maxy ) ) defer C . mapnik_bbox_free ( bbox ) C . mapnik_map_zoom_to_box ( m . m , bbox ) }

// ZoomTo zooms to the given bounding box.

ZoomTo zooms to the given bounding box .


func (m *Map) Render(opts RenderOpts) ([]byte, error) {
	scaleFactor := opts.ScaleFactor
	if scaleFactor == 0.0 {
		scaleFactor = 1.0
	}
	i := C.mapnik_map_render_to_image(m.m, C.double(opts.Scale), C.double(scaleFactor))
	if i == nil {
		return nil, m.lastError()
	}
	defer C.mapnik_image_free(i)
	if opts.Format == "raw" {
		size := 0
		raw := C.mapnik_image_to_raw(i, (*C.size_t)(unsafe.Pointer(&size)))
		return C.GoBytes(unsafe.Pointer(raw), C.int(size)), nil
	}
	var format *C.char
	if opts.Format != "" {
		format = C.CString(opts.Format)
	} else {
		format = C.CString("png256")
	}
	b := C.mapnik_image_to_blob(i, format)
	if b == nil {
		return nil, errors.New("mapnik: " + C.GoString(C.mapnik_image_last_error(i)))
	}
	C.free(unsafe.Pointer(format))
	defer C.mapnik_image_blob_free(b)
	return C.GoBytes(unsafe.Pointer(b.ptr), C.int(b.len)), nil
}

func ( m * Map ) Render ( opts RenderOpts ) ( [ ] byte , error ) { scaleFactor := opts . ScaleFactor if scaleFactor == 0.0 { scaleFactor = 1.0 } i := C . mapnik_map_render_to_image ( m . m , C . double ( opts . Scale ) , C . double ( scaleFactor ) ) if i == nil { return nil , m . lastError ( ) } defer C . mapnik_image_free ( i ) if opts . Format == " " { size := 0 raw := C . mapnik_image_to_raw ( i , ( * C . size_t ) ( unsafe . Pointer ( & size ) ) ) return C . GoBytes ( unsafe . Pointer ( raw ) , C . int ( size ) ) , nil } var format * C . char if opts . Format != " " { format = C . CString ( opts . Format ) } else { format = C . CString ( " " ) } b := C . mapnik_image_to_blob ( i , format ) if b == nil { return nil , errors . New ( " " + C . GoString ( C . mapnik_image_last_error ( i ) ) ) } C . free ( unsafe . Pointer ( format ) ) defer C . mapnik_image_blob_free ( b ) return C . GoBytes ( unsafe . Pointer ( b . ptr ) , C . int ( b . len ) ) , nil }

// Render returns the map as an encoded image.

Render returns the map as an encoded image .


func (m *Map) RenderImage(opts RenderOpts) (*image.NRGBA, error) {
	scaleFactor := opts.ScaleFactor
	if scaleFactor == 0.0 {
		scaleFactor = 1.0
	}
	i := C.mapnik_map_render_to_image(m.m, C.double(opts.Scale), C.double(scaleFactor))
	if i == nil {
		return nil, m.lastError()
	}
	defer C.mapnik_image_free(i)
	size := 0
	raw := C.mapnik_image_to_raw(i, (*C.size_t)(unsafe.Pointer(&size)))
	b := C.GoBytes(unsafe.Pointer(raw), C.int(size))
	img := &image.NRGBA{
		Pix:    b,
		Stride: int(m.width * 4),
		Rect:   image.Rect(0, 0, int(m.width), int(m.height)),
	}
	return img, nil
}

func ( m * Map ) RenderImage ( opts RenderOpts ) ( * image . NRGBA , error ) { scaleFactor := opts . ScaleFactor if scaleFactor == 0.0 { scaleFactor = 1.0 } i := C . mapnik_map_render_to_image ( m . m , C . double ( opts . Scale ) , C . double ( scaleFactor ) ) if i == nil { return nil , m . lastError ( ) } defer C . mapnik_image_free ( i ) size := 0 raw := C . mapnik_image_to_raw ( i , ( * C . size_t ) ( unsafe . Pointer ( & size ) ) ) b := C . GoBytes ( unsafe . Pointer ( raw ) , C . int ( size ) ) img := & image . NRGBA { Pix : b , Stride : int ( m . width * 4 ) , Rect : image . Rect ( 0 , 0 , int ( m . width ) , int ( m . height ) ) , } return img , nil }

// RenderImage returns the map as an unencoded image.Image.

RenderImage returns the map as an unencoded image . Image .


func (m *Map) RenderToFile(opts RenderOpts, path string) error {
	scaleFactor := opts.ScaleFactor
	if scaleFactor == 0.0 {
		scaleFactor = 1.0
	}
	cs := C.CString(path)
	defer C.free(unsafe.Pointer(cs))
	var format *C.char
	if opts.Format != "" {
		format = C.CString(opts.Format)
	} else {
		format = C.CString("png256")
	}
	defer C.free(unsafe.Pointer(format))
	if C.mapnik_map_render_to_file(m.m, cs, C.double(opts.Scale), C.double(scaleFactor), format) != 0 {
		return m.lastError()
	}
	return nil
}

func ( m * Map ) RenderToFile ( opts RenderOpts , path string ) error { scaleFactor := opts . ScaleFactor if scaleFactor == 0.0 { scaleFactor = 1.0 } cs := C . CString ( path ) defer C . free ( unsafe . Pointer ( cs ) ) var format * C . char if opts . Format != " " { format = C . CString ( opts . Format ) } else { format = C . CString ( " " ) } defer C . free ( unsafe . Pointer ( format ) ) if C . mapnik_map_render_to_file ( m . m , cs , C . double ( opts . Scale ) , C . double ( scaleFactor ) , format ) != 0 { return m . lastError ( ) } return nil }

// RenderToFile writes the map as an encoded image to the file system.

RenderToFile writes the map as an encoded image to the file system .


func (m *Map) SetBufferSize(s int) {
	C.mapnik_map_set_buffer_size(m.m, C.int(s))
}

func ( m * Map ) SetBufferSize ( s int ) { C . mapnik_map_set_buffer_size ( m . m , C . int ( s ) ) }

// SetBufferSize sets the pixel buffer at the map image edges where Mapnik should not render any labels.

SetBufferSize sets the pixel buffer at the map image edges where Mapnik should not render any labels .


func Search(st string, mx time.Duration) ([]SearchResponse, error) {
	conn, err := listenForSearchResponses()
	if err != nil {
		return nil, err
	}
	defer conn.Close()

	searchBytes, broadcastAddr := buildSearchRequest(st, mx)
	// Write search bytes on the wire so all devices can respond
	_, err = conn.WriteTo(searchBytes, broadcastAddr)
	if err != nil {
		return nil, err
	}

	return readSearchResponses(conn, mx)
}

// Search the network for SSDP devices using the given search string and duration
// to discover new devices. This function will return an array of SearchReponses
// discovered.

Search the network for SSDP devices using the given search string and duration to discover new devices . This function will return an array of SearchReponses discovered .


func (p *blockingPool) Get() (net.Conn, error) {
	//in case that pool is closed or pool.conns is set to nil
	conns := p.conns
	if conns == nil {
		return nil, ErrClosed
	}

	select {
	case conn := <-conns:
		if time.Since(conn.start) > p.livetime {
			if conn.Conn != nil {
				conn.Conn.Close()
				conn.Conn = nil
			}
		}
		if conn.Conn == nil {
			var err error
			conn.Conn, err = p.factory()
			if err != nil {
				conn.start = time.Now()
				p.put(conn)
				return nil, err
			}
		}
		conn.unusable = false
		return conn, nil
	case <-time.After(time.Second*p.timeout):
		return nil, ErrTimeout
	}
}

//Get blocks for an available connection.

Get blocks for an available connection .


func (p *blockingPool) put(conn *WrappedConn) error {
	//in case that pool is closed and pool.conns is set to nil
	conns := p.conns
	if conns == nil {
		//conn.Conn is possibly nil coz factory() may fail, in which case conn is immediately
		//put back to the pool
		if conn.Conn != nil {
			conn.Conn.Close()
			conn.Conn = nil
		}
		return ErrClosed
	}

	//if conn is marked unusable, underlying net.Conn is set to nil
	if conn.unusable {
		if conn.Conn != nil {
			conn.Conn.Close()
			conn.Conn = nil
		}
	}

	//It is impossible to block as number of connections is never more than length of channel
	conns <-conn
	return nil
}

//put puts the connection back to the pool. If the pool is closed, put simply close
//any connections received and return immediately. A nil net.Conn is illegal and will be rejected.

put puts the connection back to the pool . If the pool is closed put simply close any connections received and return immediately . A nil net . Conn is illegal and will be rejected .


func MonoToStereoF32(buf *audio.Float32Buffer) error {
	if buf == nil || buf.Format == nil || buf.Format.NumChannels != 1 {
		return audio.ErrInvalidBuffer
	}
	stereoData := make([]float32, len(buf.Data)*2)
	var j int
	for i := 0; i < len(buf.Data); i++ {
		stereoData[j] = buf.Data[i]
		j++
		stereoData[j] = buf.Data[i]
		j++
	}
	buf.Data = stereoData
	buf.Format.NumChannels = 2
	return nil
}

func MonoToStereoF32 ( buf * audio . Float32Buffer ) error { if buf == nil || buf . Format == nil || buf . Format . NumChannels != 1 { return audio . ErrInvalidBuffer } stereoData := make ( [ ] float32 , len ( buf . Data ) * 2 ) var j int for i := 0 ; i < len ( buf . Data ) ; i ++ { stereoData [ j ] = buf . Data [ i ] j ++ stereoData [ j ] = buf . Data [ i ] j ++ } buf . Data = stereoData buf . Format . NumChannels = 2 return nil }

// MonoToStereoF32 converts a mono stream into a stereo one
// by copying the mono signal to both channels in an interleaved
// signal.

MonoToStereoF32 converts a mono stream into a stereo one by copying the mono signal to both channels in an interleaved signal .


func BitCrush(buf *audio.FloatBuffer, factor float64) {
	stepSize := crusherStepSize * factor
	for i := 0; i < len(buf.Data); i++ {
		frac, exp := math.Frexp(buf.Data[i])
		frac = signum(frac) * math.Floor(math.Abs(frac)/stepSize+0.5) * stepSize
		buf.Data[i] = math.Ldexp(frac, exp)
	}
}

func BitCrush ( buf * audio . FloatBuffer , factor float64 ) { stepSize := crusherStepSize * factor for i := 0 ; i < len ( buf . Data ) ; i ++ { frac , exp := math . Frexp ( buf . Data [ i ] ) frac = signum ( frac ) * math . Floor ( math . Abs ( frac ) / stepSize + 0.5 ) * stepSize buf . Data [ i ] = math . Ldexp ( frac , exp ) } }

// BitCrush reduces the resolution of the sample to the target bit depth
// Note that bit crusher effects are usually made of this feature + a decimator

BitCrush reduces the resolution of the sample to the target bit depth Note that bit crusher effects are usually made of this feature + a decimator


func NormalizeMax(buf *audio.FloatBuffer) {
	if buf == nil {
		return
	}
	max := 0.0

	for i := 0; i < len(buf.Data); i++ {
		if math.Abs(buf.Data[i]) > max {
			max = math.Abs(buf.Data[i])
		}
	}

	if max != 0.0 {
		for i := 0; i < len(buf.Data); i++ {
			buf.Data[i] /= max
		}
	}
}

func NormalizeMax ( buf * audio . FloatBuffer ) { if buf == nil { return } max := 0.0 for i := 0 ; i < len ( buf . Data ) ; i ++ { if math . Abs ( buf . Data [ i ] ) > max { max = math . Abs ( buf . Data [ i ] ) } } if max != 0.0 { for i := 0 ; i < len ( buf . Data ) ; i ++ { buf . Data [ i ] /= max } } }

// NormalizeMax sets the max value to 1 and normalize the rest of the data.

NormalizeMax sets the max value to 1 and normalize the rest of the data .


func Gain(buf *audio.FloatBuffer, multiplier float64) error {
	if buf == nil {
		return audio.ErrInvalidBuffer
	}

	for i := 0; i < len(buf.Data); i++ {
		buf.Data[i] *= multiplier
	}

	return nil
}

func Gain ( buf * audio . FloatBuffer , multiplier float64 ) error { if buf == nil { return audio . ErrInvalidBuffer } for i := 0 ; i < len ( buf . Data ) ; i ++ { buf . Data [ i ] *= multiplier } return nil }

// Gain applies the multiplier to the passed buffer.
// A multipler of 1 would increase the amplitude of the signal by 100%
// while a multiplier of 0 would not do anything.
// Note that this is a very very naive implementation and we will more
// than add a more useful DB gain transform.

Gain applies the multiplier to the passed buffer . A multipler of 1 would increase the amplitude of the signal by 100% while a multiplier of 0 would not do anything . Note that this is a very very naive implementation and we will more than add a more useful DB gain transform .


func MonoDownmix(buf *audio.FloatBuffer) error {
	if buf == nil || buf.Format == nil {
		return audio.ErrInvalidBuffer
	}
	nChans := buf.Format.NumChannels
	if nChans < 2 {
		return nil
	}
	nChansF := float64(nChans)

	frameCount := buf.NumFrames()
	newData := make([]float64, frameCount)
	for i := 0; i < frameCount; i++ {
		newData[i] = 0
		for j := 0; j < nChans; j++ {
			newData[i] += buf.Data[i*nChans+j]
		}
		newData[i] /= nChansF
	}
	buf.Data = newData
	buf.Format.NumChannels = 1

	return nil
}

func MonoDownmix ( buf * audio . FloatBuffer ) error { if buf == nil || buf . Format == nil { return audio . ErrInvalidBuffer } nChans := buf . Format . NumChannels if nChans < 2 { return nil } nChansF := float64 ( nChans ) frameCount := buf . NumFrames ( ) newData := make ( [ ] float64 , frameCount ) for i := 0 ; i < frameCount ; i ++ { newData [ i ] = 0 for j := 0 ; j < nChans ; j ++ { newData [ i ] += buf . Data [ i * nChans + j ] } newData [ i ] /= nChansF } buf . Data = newData buf . Format . NumChannels = 1 return nil }

// MonoDownmix converts the buffer to a mono buffer
// by downmixing the channels together.

MonoDownmix converts the buffer to a mono buffer by downmixing the channels together .


func Quantize(buf *audio.FloatBuffer, bitDepth int) {
	if buf == nil {
		return
	}
	max := math.Pow(2, float64(bitDepth)) - 1

	bufLen := len(buf.Data)
	for i := 0; i < bufLen; i++ {
		buf.Data[i] = round((buf.Data[i]+1)*max)/max - 1.0
	}
}

func Quantize ( buf * audio . FloatBuffer , bitDepth int ) { if buf == nil { return } max := math . Pow ( 2 , float64 ( bitDepth ) ) - 1 bufLen := len ( buf . Data ) for i := 0 ; i < bufLen ; i ++ { buf . Data [ i ] = round ( ( buf . Data [ i ] + 1 ) * max ) / max - 1.0 } }

// Quantize quantizes the audio signal to match the target bitDepth


func PCMScale(buf *audio.FloatBuffer, bitDepth int) error {
	if buf == nil || buf.Format == nil {
		return audio.ErrInvalidBuffer
	}
	factor := math.Pow(2, 8*float64(bitDepth/8)-1)
	for i := 0; i < len(buf.Data); i++ {
		buf.Data[i] *= factor
	}

	return nil
}

func PCMScale ( buf * audio . FloatBuffer , bitDepth int ) error { if buf == nil || buf . Format == nil { return audio . ErrInvalidBuffer } factor := math . Pow ( 2 , 8 * float64 ( bitDepth / 8 ) - 1 ) for i := 0 ; i < len ( buf . Data ) ; i ++ { buf . Data [ i ] *= factor } return nil }

// PCMScale converts a buffer with audio content from -1 to 1 into
// the PCM scale based on the passed bitdepth.
// Note that while the PCM data is scaled, the PCM format is not changed.

PCMScale converts a buffer with audio content from - 1 to 1 into the PCM scale based on the passed bitdepth . Note that while the PCM data is scaled the PCM format is not changed .


func StereoPan(buf *audio.FloatBuffer, pan float64) error {
	if buf == nil || buf.Format == nil || buf.Format.NumChannels != 2 {
		return audio.ErrInvalidBuffer
	}
	if pan < 0 || pan > 1 {
		return errors.New("invalid pan value, should be betwen 0 and 1")
	}
	if pan == 0.5 {
		return nil
	}

	if pan < 0.5 {
		for i := 0; i+2 <= len(buf.Data); i += 2 {
			buf.Data[i+1] *= (pan * 2)
		}
	} else {
		for i := 0; i+2 <= len(buf.Data); i += 2 {
			buf.Data[i] *= ((1 - pan) * 2)
		}
	}

	return nil
}

func StereoPan ( buf * audio . FloatBuffer , pan float64 ) error { if buf == nil || buf . Format == nil || buf . Format . NumChannels != 2 { return audio . ErrInvalidBuffer } if pan < 0 || pan > 1 { return errors . New ( " " ) } if pan == 0.5 { return nil } if pan < 0.5 { for i := 0 ; i + 2 <= len ( buf . Data ) ; i += 2 { buf . Data [ i + 1 ] *= ( pan * 2 ) } } else { for i := 0 ; i + 2 <= len ( buf . Data ) ; i += 2 { buf . Data [ i ] *= ( ( 1 - pan ) * 2 ) } } return nil }

// StereoPan changes the balance of the input buffer by "panning"
// more to the left or the right. The pan value must be between
// 0 and 1 where 0 is full first channel, 0.5 center and 1 full second channel.
// Note that the signal from 1 channel is not sent to the other, this transform
// only reduces the balance of one of the 2 channels.

StereoPan changes the balance of the input buffer by panning more to the left or the right . The pan value must be between 0 and 1 where 0 is full first channel 0 . 5 center and 1 full second channel . Note that the signal from 1 channel is not sent to the other this transform only reduces the balance of one of the 2 channels .


func (f *Follower) Leader() string {
	f.lock.Lock()
	defer f.lock.Unlock()
	return f.leader
}

func ( f * Follower ) Leader ( ) string { f . lock . Lock ( ) defer f . lock . Unlock ( ) return f . leader }


func (c *Candidate) IsLeader() bool {
	c.lock.Lock()
	defer c.lock.Unlock()
	return c.leader
}

func ( c * Candidate ) IsLeader ( ) bool { c . lock . Lock ( ) defer c . lock . Unlock ( ) return c . leader }

// IsLeader returns true if the candidate is currently a leader.

IsLeader returns true if the candidate is currently a leader .


func NewResponse(clientID, redirectURI, userID, exp, code string) Response {
	return Response{ClientID: clientID, RedirectURI: redirectURI, UserID: userID, Exp: exp, Code: code}
}

func NewResponse ( clientID , redirectURI , userID , exp , code string ) Response { return Response { ClientID : clientID , RedirectURI : redirectURI , UserID : userID , Exp : exp , Code : code } }

//NewResponse returns a new OAuth2Response


func GetRequestID(ctx context.Context) (string, error) {
	if ctx == nil {
		return "", errors.New("nil context")
	}

	reqID, ok := ctx.Value(contextRequestID).(string)
	if !ok {
		return "", errors.New("unexpected type")
	}

	if len(reqID) == 0 {
		return "", errors.New("empty value in context")
	}

	return reqID, nil
}

func GetRequestID ( ctx context . Context ) ( string , error ) { if ctx == nil { return " " , errors . New ( " " ) } reqID , ok := ctx . Value ( contextRequestID ) . ( string ) if ! ok { return " " , errors . New ( " " ) } if len ( reqID ) == 0 { return " " , errors . New ( " " ) } return reqID , nil }

// GetRequestID returns a request ID from the given context if one is present.
// Returns the empty string if a request ID cannot be found.

GetRequestID returns a request ID from the given context if one is present . Returns the empty string if a request ID cannot be found .


func (m *monitorableWriter) Log() {
	duration := time.Now().Sub(m.t0)
	if m.Code == 0 {
		m.Code = 200
	}
	if m.opts.Filter != nil && !m.opts.Filter(m.r, m.Code, duration, m.Size) {
		return //skip
	}
	cc := m.colorCode()
	size := ""
	if m.Size > 0 {
		size = sizestr.ToString(m.Size)
	}
	buff := bytes.Buffer{}
	m.opts.formatTmpl.Execute(&buff, &struct {
		*Colors
		Timestamp, Method, Path, CodeColor string
		Code                               int
		Duration, Size, IP                 string
	}{
		m.opts.Colors,
		m.t0.Format(m.opts.TimeFormat), m.method, m.path, cc,
		m.Code,
		fmtDuration(duration), size, m.ip,
	})
	//fmt is threadsafe :)
	fmt.Fprint(m.opts.Writer, buff.String())
}

func
(
m
*
monitorableWriter
)
Log
(
)
{
duration
:=
time
.
Now
(
)
.
Sub
(
m
.
t0
)
if
m
.
Code
==
0
{
m
.
Code
=
200
}
if
m
.
opts
.
Filter
!=
&&
!
m
.
opts
.
Filter
(
m
.
r
,
m
.
Code
,
duration
,
m
.
Size
)
{
return
//skip
}
cc
:=
m
.
colorCode
(
)
size
:=
"
"
if
m
.
Size
>
0
{
size
=
sizestr
.
ToString
(
m
.
Size
)
}
buff
:=
bytes
.
Buffer
{
}
m
.
opts
.
formatTmpl
.
Execute
(
&
buff
,
&
struct
{
*
Colors
Timestamp
,
Method
,
Path
,
CodeColor
string
Code
int
Duration
,
Size
,
IP
string
}
{
m
.
opts
.
Colors
,
m
.
t0
.
Format
(
m
.
opts
.
TimeFormat
)
,
m
.
method
,
m
.
path
,
cc
,
m
.
Code
,
fmtDuration
(
duration
)
,
size
,
m
.
ip
,
}
)
//fmt is threadsafe :)
fmt
.
Fprint
(
m
.
opts
.
Writer
,
buff
.
String
(
)
)
}

//replace ResponseWriter with a monitorable one, return logger

replace ResponseWriter with a monitorable one return logger


func SendMailSSL(addr string, a smtp.Auth, from string, to []string, msg []byte) error {
	conn, err := tls.Dial("tcp", addr, &tls.Config{InsecureSkipVerify: true}) //TODO: Not secure
	if err != nil {
		log.Println("Error Dialing", err)
		return err
	}
	h, _, _ := net.SplitHostPort(addr)
	c, err := smtp.NewClient(conn, h)
	if err != nil {
		log.Println("Error SMTP connection", err)
		return err
	}
	defer c.Close()

	if a != nil {
		if ok, _ := c.Extension("AUTH"); ok {
			if err = c.Auth(a); err != nil {
				log.Printf("Authentication error: %v", err)
				return err
			}
		}
	}

	if err = c.Mail(from); err != nil {
		log.Printf("From error: %v", err)
		return err
	}

	for _, addr := range to {
		if err = c.Rcpt(addr); err != nil {
			log.Printf("Recipient error: %v", err)
			return err
		}
	}

	w, err := c.Data()
	if err != nil {
		return err
	}

	w.Write(msg)
	w.Close()

	return c.Quit()
}

func
SendMailSSL
(
addr
string
,
a
smtp
.
Auth
,
from
string
,
to
[
]
string
,
msg
[
]
byte
)
error
{
conn
,
err
:=
tls
.
Dial
(
"
"
,
addr
,
&
tls
.
Config
{
InsecureSkipVerify
:
true
}
)
//TODO: Not secure
if
err
!=
{
log
.
Println
(
"
"
,
err
)
return
err
}
h
,
_
,
_
:=
net
.
SplitHostPort
(
addr
)
c
,
err
:=
smtp
.
NewClient
(
conn
,
h
)
if
err
!=
{
log
.
Println
(
"
"
,
err
)
return
err
}
defer
c
.
Close
(
)
if
a
!=
{
if
ok
,
_
:=
c
.
Extension
(
"
"
)
;
ok
{
if
err
=
c
.
Auth
(
a
)
;
err
!=
{
log
.
Printf
(
"
"
,
err
)
return
err
}
}
}
if
err
=
c
.
Mail
(
from
)
;
err
!=
{
log
.
Printf
(
"
"
,
err
)
return
err
}
for
_
,
addr
:=
range
to
{
if
err
=
c
.
Rcpt
(
addr
)
;
err
!=
{
log
.
Printf
(
"
"
,
err
)
return
err
}
}
w
,
err
:=
c
.
Data
(
)
if
err
!=
{
return
err
}
w
.
Write
(
msg
)
w
.
Close
(
)
return
c
.
Quit
(
)
}


func (m *MailService) Send(message string, subject string, from string, to string) (err error) {
	t := []string{to}
	msg := []byte("From: " + from + "\r\n" +
		"To: " + to + "\r\n" +
		"Subject: " + subject + "\r\n" +
		"\r\n" +
		message + "\r\n")

	err = m.SMTP.SendMail(from, t, msg)

	return
}

func ( m * MailService ) Send ( message string , subject string , from string , to string ) ( err error ) { t := [ ] string { to } msg := [ ] byte ( " " + from + " \r \n " + " " + to + " \r \n " + " " + subject + " \r \n " + " \r \n " + message + " \r \n " ) err = m . SMTP . SendMail ( from , t , msg ) return }


func WaitForIt(fullConn, host string, port, timeout int) error {
	// fullConn := flag.String("full-connection", "", "full connection")
	// host := flag.String("host", "", "host to connect")
	// port := flag.Int("port", 80, "port to connect")
	// timeout := flag.Int("timeout", 10, "time to wait until port become available")
	// printVersion := flag.Bool("v", false, "show the current version")
	// debug = flag.Bool("debug", false, "enable debug")

	// flag.Parse()

	// if *printVersion {
	// 	fmt.Println("waitforit version " + VERSION)
	// 	return
	// }

	conn := buildConn(host, port, fullConn)
	if conn == nil {
		return errors.New("Invalid connection")
	}

	log.Debug("Waiting " + strconv.Itoa(timeout) + " seconds")
	if err := pingTCP(conn, timeout); err != nil {
		return err
	}

	if conn.Scheme != "http" && conn.Scheme != "https" {
		return nil
	}

	if err := pingHTTP(conn, timeout); err != nil {
		return err
	}

	return nil
}

// WaitForIt waits for a service or URL to become online


func Get(source interface{}, environment string, configEnv Environment) (conf interface{}, err error) {
	if filename, ok := source.(string); ok {
		source, err = ioutil.ReadFile(filename)
		if err != nil {
			log.Printf("Fatal: %v", err)
			return
		}
	}

	err = yaml.Unmarshal(source.([]byte), configEnv)
	if err != nil {
		log.Printf("Fatal: bad config : %v", err)
		return
	}

	conf = configEnv.GetEnvironment(environment)
	if conf == nil {
		err = errors.New("No configuration")
		return
	}
	return
}

func Get ( source interface { } , environment string , configEnv Environment ) ( conf interface { } , err error ) { if filename , ok := source . ( string ) ; ok { source , err = ioutil . ReadFile ( filename ) if err != nil { log . Printf ( " " , err ) return } } err = yaml . Unmarshal ( source . ( [ ] byte ) , configEnv ) if err != nil { log . Printf ( " " , err ) return } conf = configEnv . GetEnvironment ( environment ) if conf == nil { err = errors . New ( " " ) return } return }


func initConfig() {
	if cfgFile != "" { // enable ability to specify config file via flag
		Viper.SetConfigFile(cfgFile)
	}

	Viper.SetConfigName("config") // name of config file (without extension)
	Viper.AddConfigPath("$HOME")  // adding home directory as first search path
	Viper.AddConfigPath("./")     // adding local directory as second search path
	Viper.AutomaticEnv()          // read in environment variables that match

	// If a config file is found, read it in.
	if err := Viper.ReadInConfig(); err == nil {
		fmt.Println("Using config file:", Viper.ConfigFileUsed())
	}
}

// Read in config file and ENV variables if set.

Read in config file and ENV variables if set .


func WritePluginResultsToDatabase(results map[string]interface{}) {

	// connect to RethinkDB
	session, err := r.Connect(r.ConnectOpts{
		Address:  fmt.Sprintf("%s:28015", utils.Getopt("MALICE_RETHINKDB", "rethink")),
		Timeout:  5 * time.Second,
		Database: "malice",
	})
	if err != nil {
		log.Debug(err)
		return
	}
	defer session.Close()

	res, err := r.Table("samples").Get(results["ID"]).Run(session)
	utils.Assert(err)
	defer res.Close()

	if res.IsNil() {
		// upsert into RethinkDB
		resp, err := r.Table("samples").Insert(results, r.InsertOpts{Conflict: "replace"}).RunWrite(session)
		utils.Assert(err)
		log.Debug(resp)
	} else {
		resp, err := r.Table("samples").Get(results["ID"]).Update(map[string]interface{}{
			"plugins": map[string]interface{}{
				category: map[string]interface{}{
					name: results["Data"],
				},
			},
		}).RunWrite(session)
		utils.Assert(err)

		log.Debug(resp)
	}
}

func
WritePluginResultsToDatabase
(
results
map
[
string
]
interface
{
}
)
{
// connect to RethinkDB
session
,
err
:=
r
.
Connect
(
r
.
ConnectOpts
{
Address
:
fmt
.
Sprintf
(
"
"
,
utils
.
Getopt
(
"
"
,
"
"
)
)
,
Timeout
:
5
*
time
.
Second
,
Database
:
"
"
,
}
)
if
err
!=
{
log
.
Debug
(
err
)
return
}
defer
session
.
Close
(
)
res
,
err
:=
r
.
Table
(
"
"
)
.
Get
(
results
[
"
"
]
)
.
Run
(
session
)
utils
.
Assert
(
err
)
defer
res
.
Close
(
)
if
res
.
IsNil
(
)
{
// upsert into RethinkDB
resp
,
err
:=
r
.
Table
(
"
"
)
.
Insert
(
results
,
r
.
InsertOpts
{
Conflict
:
"
"
}
)
.
RunWrite
(
session
)
utils
.
Assert
(
err
)
log
.
Debug
(
resp
)
}
else
{
resp
,
err
:=
r
.
Table
(
"
"
)
.
Get
(
results
[
"
"
]
)
.
Update
(
map
[
string
]
interface
{
}
{
"
"
:
map
[
string
]
interface
{
}
{
category
:
map
[
string
]
interface
{
}
{
name
:
results
[
"
"
]
,
}
,
}
,
}
)
.
RunWrite
(
session
)
utils
.
Assert
(
err
)
log
.
Debug
(
resp
)
}
}

// WritePluginResultsToDatabase upserts plugin results into Database


func NewAuthController(um UserManager, cnf web.Config) *AuthController {
	authController := AuthController{UserManager: um, cnf: cnf}
	return &authController
}

func NewAuthController ( um UserManager , cnf web . Config ) * AuthController { authController := AuthController { UserManager : um , cnf : cnf } return & authController }

//NewAuthController constructs new AuthController


func (c *AuthController) Authenticate(w http.ResponseWriter, r *http.Request) {
	decoder := json.NewDecoder(r.Body)
	var user User
	var data map[string]string
	err := decoder.Decode(&user)
	if err != nil {
		http.Error(w, fmt.Sprintf("%v", err), 400)
		return
	}
	user, _ = c.UserManager.Get(user.Username, user.Password)
	if user.Username != "" {
		token := jwt.New(jwt.GetSigningMethod("HS256"))
		claims := token.Claims.(jwt.MapClaims)

		claims["username"] = user.Username
		claims["email"] = user.Email
		claims["exp"] = time.Now().Add(time.Minute * 10).Unix()
		tokenString, _ := token.SignedString([]byte(c.cnf.Jwt.Key))
		data = map[string]string{
			"id_token": tokenString,
		}
	}
	js, _ := json.Marshal(data)
	w.Write(js)
}

func ( c * AuthController ) Authenticate ( w http . ResponseWriter , r * http . Request ) { decoder := json . NewDecoder ( r . Body ) var user User var data map [ string ] string err := decoder . Decode ( & user ) if err != nil { http . Error ( w , fmt . Sprintf ( " " , err ) , 400 ) return } user , _ = c . UserManager . Get ( user . Username , user . Password ) if user . Username != " " { token := jwt . New ( jwt . GetSigningMethod ( " " ) ) claims := token . Claims . ( jwt . MapClaims ) claims [ " " ] = user . Username claims [ " " ] = user . Email claims [ " " ] = time . Now ( ) . Add ( time . Minute * 10 ) . Unix ( ) tokenString , _ := token . SignedString ( [ ] byte ( c . cnf . Jwt . Key ) ) data = map [ string ] string { " " : tokenString , } } js , _ := json . Marshal ( data ) w . Write ( js ) }


func NewOAuth2Controller(am ApplicationManager, cnf web.Config) *OAuth2Controller {
	oAuth2Controller := OAuth2Controller{cnf: cnf, ApplicationManager: am}
	return &oAuth2Controller
}

func NewOAuth2Controller ( am ApplicationManager , cnf web . Config ) * OAuth2Controller { oAuth2Controller := OAuth2Controller { cnf : cnf , ApplicationManager : am } return & oAuth2Controller }

//NewOAuth2Controller constructs new AuthController


func (c *OAuth2Controller) Refresh(w http.ResponseWriter, r *http.Request) {
	grantType := r.URL.Query().Get("grant_type")
	refreshToken := r.URL.Query().Get("refresh_token")
	if strings.Compare(grantType, "refresh_token") != 0 {
		http.Error(w, errors.New("Parameter grant_type is required").Error(), http.StatusBadRequest)
		return
	}
	if strings.Compare(refreshToken, "") == 0 {
		http.Error(w, errors.New("Parameter refreshToken is required").Error(), http.StatusBadRequest)
		return
	}
	token, err := jwt.Parse(refreshToken, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
		}
		return []byte(c.cnf.Jwt.Key), nil
	})
	if err == nil && token.Valid {
		token := jwt.New(jwt.GetSigningMethod("HS256"))
		claims := token.Claims.(jwt.MapClaims)
		claims["exp"] = time.Now().Add(time.Hour * 1).Unix()
		tokenString, _ := token.SignedString([]byte(c.cnf.Jwt.Key))

		data := map[string]string{
			"access_token": tokenString,
			"token_type":   "bearer",
			"expires_in":   "3600",
		}
		js, _ := json.Marshal(data)
		w.Write(js)
	}
}

func ( c * OAuth2Controller ) Refresh ( w http . ResponseWriter , r * http . Request ) { grantType := r . URL . Query ( ) . Get ( " " ) refreshToken := r . URL . Query ( ) . Get ( " " ) if strings . Compare ( grantType , " " ) != 0 { http . Error ( w , errors . New ( " " ) . Error ( ) , http . StatusBadRequest ) return } if strings . Compare ( refreshToken , " " ) == 0 { http . Error ( w , errors . New ( " " ) . Error ( ) , http . StatusBadRequest ) return } token , err := jwt . Parse ( refreshToken , func ( token * jwt . Token ) ( interface { } , error ) { if _ , ok := token . Method . ( * jwt . SigningMethodHMAC ) ; ! ok { return nil , fmt . Errorf ( " " , token . Header [ " " ] ) } return [ ] byte ( c . cnf . Jwt . Key ) , nil } ) if err == nil && token . Valid { token := jwt . New ( jwt . GetSigningMethod ( " " ) ) claims := token . Claims . ( jwt . MapClaims ) claims [ " " ] = time . Now ( ) . Add ( time . Hour * 1 ) . Unix ( ) tokenString , _ := token . SignedString ( [ ] byte ( c . cnf . Jwt . Key ) ) data := map [ string ] string { " " : tokenString , " " : " " , " " : " " , } js , _ := json . Marshal ( data ) w . Write ( js ) } }


func (c *OAuth2Controller) Token(w http.ResponseWriter, r *http.Request) {
	grantType := r.URL.Query().Get("grant_type")
	code := r.URL.Query().Get("code")
	if strings.Compare(grantType, "authorization_code") != 0 {
		http.Error(w, errors.New("Parameter grant_type is required").Error(), http.StatusBadRequest)
		return
	}
	if strings.Compare(code, "") == 0 {
		http.Error(w, errors.New("Parameter code is required").Error(), http.StatusBadRequest)
		return
	}
	response, err := DecodeOAuth2Code(code, c.cnf.Jwt.Key)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	i, err := strconv.ParseInt(response.Exp, 10, 64)
	exp := time.Unix(i, 0)
	if exp.After(time.Now()) {
		log.Printf("Code is expired")
	} else {
		token := jwt.New(jwt.GetSigningMethod("HS256"))
		claims := token.Claims.(jwt.MapClaims)
		claims["exp"] = time.Now().Add(time.Hour * 1).Unix()
		tokenString, _ := token.SignedString([]byte(c.cnf.Jwt.Key))

		refreshToken := jwt.New(jwt.GetSigningMethod("HS256"))
		refreshClaims := refreshToken.Claims.(jwt.MapClaims)
		refreshClaims["exp"] = 0
		refreshTokenString, _ := refreshToken.SignedString([]byte(c.cnf.Jwt.Key))
		data := map[string]string{
			"access_token":  tokenString,
			"token_type":    "bearer",
			"refresh_token": refreshTokenString,
			"expires_in":    "3600",
		}
		js, _ := json.Marshal(data)
		w.Write(js)
	}
}

func ( c * OAuth2Controller ) Token ( w http . ResponseWriter , r * http . Request ) { grantType := r . URL . Query ( ) . Get ( " " ) code := r . URL . Query ( ) . Get ( " " ) if strings . Compare ( grantType , " " ) != 0 { http . Error ( w , errors . New ( " " ) . Error ( ) , http . StatusBadRequest ) return } if strings . Compare ( code , " " ) == 0 { http . Error ( w , errors . New ( " " ) . Error ( ) , http . StatusBadRequest ) return } response , err := DecodeOAuth2Code ( code , c . cnf . Jwt . Key ) if err != nil { http . Error ( w , err . Error ( ) , http . StatusBadRequest ) return } i , err := strconv . ParseInt ( response . Exp , 10 , 64 ) exp := time . Unix ( i , 0 ) if exp . After ( time . Now ( ) ) { log . Printf ( " " ) } else { token := jwt . New ( jwt . GetSigningMethod ( " " ) ) claims := token . Claims . ( jwt . MapClaims ) claims [ " " ] = time . Now ( ) . Add ( time . Hour * 1 ) . Unix ( ) tokenString , _ := token . SignedString ( [ ] byte ( c . cnf . Jwt . Key ) ) refreshToken := jwt . New ( jwt . GetSigningMethod ( " " ) ) refreshClaims := refreshToken . Claims . ( jwt . MapClaims ) refreshClaims [ " " ] = 0 refreshTokenString , _ := refreshToken . SignedString ( [ ] byte ( c . cnf . Jwt . Key ) ) data := map [ string ] string { " " : tokenString , " " : " " , " " : refreshTokenString , " " : " " , } js , _ := json . Marshal ( data ) w . Write ( js ) } }


func Logging(next http.Handler, log *logrus.Logger) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		srw := StatusResponseWriter{w, 0, 0}
		start := time.Now()
		next.ServeHTTP(&srw, r)
		end := time.Now()
		latency := end.Sub(start)

		log.WithField("client", r.RemoteAddr).WithField("latency", latency).WithField("length", srw.Length()).WithField("code", srw.Status()).Printf("%s %s %s", r.Method, r.URL, r.Proto)
	})
}

func Logging ( next http . Handler , log * logrus . Logger ) http . Handler { return http . HandlerFunc ( func ( w http . ResponseWriter , r * http . Request ) { srw := StatusResponseWriter { w , 0 , 0 } start := time . Now ( ) next . ServeHTTP ( & srw , r ) end := time . Now ( ) latency := end . Sub ( start ) log . WithField ( " " , r . RemoteAddr ) . WithField ( " " , latency ) . WithField ( " " , srw . Length ( ) ) . WithField ( " " , srw . Status ( ) ) . Printf ( " " , r . Method , r . URL , r . Proto ) } ) }


func SingleFile(filename string) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, filename)
	})
}

func SingleFile ( filename string ) http . Handler { return http . HandlerFunc ( func ( w http . ResponseWriter , r * http . Request ) { http . ServeFile ( w , r , filename ) } ) }


func (w *StatusResponseWriter) Write(data []byte) (int, error) {
	w.length = len(data)
	return w.ResponseWriter.Write(data)
}

func ( w * StatusResponseWriter ) Write ( data [ ] byte ) ( int , error ) { w . length = len ( data ) return w . ResponseWriter . Write ( data ) }

// Write Satisfy the http.ResponseWriter interface

Write Satisfy the http . ResponseWriter interface


func (w *StatusResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
	if hj, ok := w.ResponseWriter.(http.Hijacker); ok {
		return hj.Hijack()
	}
	return nil, nil, errors.New("Not a Hijacker")
}

func ( w * StatusResponseWriter ) Hijack ( ) ( net . Conn , * bufio . ReadWriter , error ) { if hj , ok := w . ResponseWriter . ( http . Hijacker ) ; ok { return hj . Hijack ( ) } return nil , nil , errors . New ( " " ) }

//Hijack Satisfy the http.ResponseWriter interface

Hijack Satisfy the http . ResponseWriter interface


func NewMongo(filename string, environment string) (*Mongo, error) {
	ctx := context.Background()
	cnf, err := GetMongo(filename, environment)
	if err != nil {
		return nil, err
	}
	var uri string
	if len(cnf.Username) > 0 && len(cnf.Password) > 0 {
		uri = fmt.Sprintf(`mongodb://%s:%s@%s:%d/%s`,
			cnf.Username,
			cnf.Password,
			cnf.Host,
			cnf.Port,
			cnf.Database,
		)
	} else {
		uri = fmt.Sprintf(`mongodb://%s:%d/%s`,
			cnf.Host,
			cnf.Port,
			cnf.Database,
		)
	}
	client, err := mongo.NewClient(uri)
	if err != nil {
		log.Printf("L'URI du serveur MongoDB est incorrect: %s", uri)
		return nil, err
	}
	err = client.Connect(ctx)
	if err != nil {
		log.Print("Impossible d'utiliser ce context")
		return nil, err
	}

	db := client.Database(cnf.Database)

	err = client.Ping(ctx, nil)
	if err != nil {
		log.Printf("Impossible de contacter %v sur le port %d", cnf.Host, cnf.Port)
		return nil, err
	}
	return &Mongo{Client: client, Database: db, context: ctx}, nil
}

func NewMongo ( filename string , environment string ) ( * Mongo , error ) { ctx := context . Background ( ) cnf , err := GetMongo ( filename , environment ) if err != nil { return nil , err } var uri string if len ( cnf . Username ) > 0 && len ( cnf . Password ) > 0 { uri = fmt . Sprintf ( `mongodb://%s:%s@%s:%d/%s` , cnf . Username , cnf . Password , cnf . Host , cnf . Port , cnf . Database , ) } else { uri = fmt . Sprintf ( `mongodb://%s:%d/%s` , cnf . Host , cnf . Port , cnf . Database , ) } client , err := mongo . NewClient ( uri ) if err != nil { log . Printf ( " " , uri ) return nil , err } err = client . Connect ( ctx ) if err != nil { log . Print ( " " ) return nil , err } db := client . Database ( cnf . Database ) err = client . Ping ( ctx , nil ) if err != nil { log . Printf ( " " , cnf . Host , cnf . Port ) return nil , err } return & Mongo { Client : client , Database : db , context : ctx } , nil }

//NewMongo creates a newinstance of Mongo


func (m *Mongo) Disconnect() error {
	err := m.Client.Disconnect(m.context)
	if err != nil {
		log.Printf("Impossible de fermer la connexion")
		return err
	}
	return nil
}

func ( m * Mongo ) Disconnect ( ) error { err := m . Client . Disconnect ( m . context ) if err != nil { log . Printf ( " " ) return err } return nil }


func New(fields []string) *Table {
	return &Table{
		Fields:     fields,
		Rows:       make([]map[string]string, 0),
		fieldSizes: make(map[string]int),
	}
}

func New ( fields [ ] string ) * Table { return & Table { Fields : fields , Rows : make ( [ ] map [ string ] string , 0 ) , fieldSizes : make ( map [ string ] int ) , } }


func PrintTable(fields []string, rows []map[string]interface{}) {
	table := New(fields)
	for _, r := range rows {
		table.AddRow(r)
	}
	table.Print()
}

func PrintTable ( fields [ ] string , rows [ ] map [ string ] interface { } ) { table := New ( fields ) for _ , r := range rows { table . AddRow ( r ) } table . Print ( ) }


func PrintHorizontal(m map[string]interface{}) {
	table := New([]string{"Key", "Value"})
	rows := mapToRows(m)
	for _, row := range rows {
		table.AddRow(row)
	}
	table.HideHead = true
	table.Print()
}

func PrintHorizontal ( m map [ string ] interface { } ) { table := New ( [ ] string { " " , " " } ) rows := mapToRows ( m ) for _ , row := range rows { table . AddRow ( row ) } table . HideHead = true table . Print ( ) }

// PrintHorizontal - Prints horizontal table from a map.

PrintHorizontal - Prints horizontal table from a map .


func PrintRow(fields []string, row map[string]interface{}) {
	table := New(fields)
	table.AddRow(row)
	table.Print()
}

func PrintRow ( fields [ ] string , row map [ string ] interface { } ) { table := New ( fields ) table . AddRow ( row ) table . Print ( ) }

// PrintRow - Prints table with only one row.

PrintRow - Prints table with only one row .


func (t *Table) AddRow(row map[string]interface{}) {
	newRow := make(map[string]string)
	for _, k := range t.Fields {
		v := row[k]
		// If is not nil format
		// else value is empty string
		var val string
		if v == nil {
			val = ""
		} else {
			val = fmt.Sprintf("%v", v)
		}

		newRow[k] = val
	}

	t.calculateSizes(newRow)

	if len(newRow) > 0 {
		t.Rows = append(t.Rows, newRow)
	}
}

func
(
t
*
Table
)
AddRow
(
row
map
[
string
]
interface
{
}
)
{
newRow
:=
make
(
map
[
string
]
string
)
for
_
,
k
:=
range
t
.
Fields
{
v
:=
row
[
k
]
// If is not nil format
// else value is empty string
var
val
string
if
v
==
{
val
=
"
"
}
else
{
val
=
fmt
.
Sprintf
(
"
"
,
v
)
}
newRow
[
k
]
=
val
}
t
.
calculateSizes
(
newRow
)
if
len
(
newRow
)
>
0
{
t
.
Rows
=
append
(
t
.
Rows
,
newRow
)
}
}


func (t *Table) Print() {
	if len(t.Rows) == 0 && t.Footer == nil {
		return
	}

	t.calculateSizes(t.Footer)

	if !t.Markdown {
		t.printDash()
	}

	if !t.HideHead {
		fmt.Println(t.getHead())
		t.printTableDash()
	}

	for _, r := range t.Rows {
		fmt.Println(t.rowString(r))
		if !t.Markdown {
			t.printDash()
		}
	}

	if t.Footer != nil {
		t.printTableDash()
		fmt.Println(t.rowString(t.Footer))
		if !t.Markdown {
			t.printTableDash()
		}
	}
}

func ( t * Table ) Print ( ) { if len ( t . Rows ) == 0 && t . Footer == nil { return } t . calculateSizes ( t . Footer ) if ! t . Markdown { t . printDash ( ) } if ! t . HideHead { fmt . Println ( t . getHead ( ) ) t . printTableDash ( ) } for _ , r := range t . Rows { fmt . Println ( t . rowString ( r ) ) if ! t . Markdown { t . printDash ( ) } } if t . Footer != nil { t . printTableDash ( ) fmt . Println ( t . rowString ( t . Footer ) ) if ! t . Markdown { t . printTableDash ( ) } } }


func (t *Table) String(title string) string {

	tableString := []string{}

	if len(t.Rows) == 0 && t.Footer == nil {
		return ""
	}

	tableString = append(tableString, "### "+title)

	t.calculateSizes(t.Footer)

	if !t.Markdown {
		// t.printDash()
		tableString = append(tableString, t.stringDash())
	}

	if !t.HideHead {
		tableString = append(tableString, t.getHead())
		tableString = append(tableString, t.stringTableDash())
		// fmt.Println(t.getHead())
		// t.printTableDash()
	}

	for _, r := range t.Rows {
		// fmt.Println(t.rowString(r))
		tableString = append(tableString, t.rowString(r))
		if !t.Markdown {
			tableString = append(tableString, t.stringDash())
		}
	}

	if t.Footer != nil {
		tableString = append(tableString, t.stringTableDash())
		tableString = append(tableString, t.rowString(t.Footer))
		if !t.Markdown {
			tableString = append(tableString, t.stringDash())
		}
	}

	return strings.Join(tableString[:], "\n")
}

func
(
t
*
Table
)
String
(
title
string
)
string
{
tableString
:=
[
]
string
{
}
if
len
(
t
.
Rows
)
==
0
&&
t
.
Footer
==
{
return
"
"
}
tableString
=
append
(
tableString
,
"
"
+
title
)
t
.
calculateSizes
(
t
.
Footer
)
if
!
t
.
Markdown
{
// t.printDash()
tableString
=
append
(
tableString
,
t
.
stringDash
(
)
)
}
if
!
t
.
HideHead
{
tableString
=
append
(
tableString
,
t
.
getHead
(
)
)
tableString
=
append
(
tableString
,
t
.
stringTableDash
(
)
)
// fmt.Println(t.getHead())
// t.printTableDash()
}
for
_
,
r
:=
range
t
.
Rows
{
// fmt.Println(t.rowString(r))
tableString
=
append
(
tableString
,
t
.
rowString
(
r
)
)
if
!
t
.
Markdown
{
tableString
=
append
(
tableString
,
t
.
stringDash
(
)
)
}
}
if
t
.
Footer
!=
{
tableString
=
append
(
tableString
,
t
.
stringTableDash
(
)
)
tableString
=
append
(
tableString
,
t
.
rowString
(
t
.
Footer
)
)
if
!
t
.
Markdown
{
tableString
=
append
(
tableString
,
t
.
stringDash
(
)
)
}
}
return
strings
.
Join
(
tableString
[
:
]
,
"
\n
"
)
}


func (t *Table) getHead() string {
	s := "|"
	for _, name := range t.Fields {
		s += t.fieldString(name, strings.Title(name)) + "|"
	}
	return s
}

func ( t * Table ) getHead ( ) string { s := " " for _ , name := range t . Fields { s += t . fieldString ( name , strings . Title ( name ) ) + " " } return s }

// getHead - Returns table header containing fields names.

getHead - Returns table header containing fields names .


func (t *Table) rowString(row map[string]string) string {
	s := "|"
	for _, name := range t.Fields {
		value := row[name]
		s += t.fieldString(name, value) + "|"
	}
	return s
}

func ( t * Table ) rowString ( row map [ string ] string ) string { s := " " for _ , name := range t . Fields { value := row [ name ] s += t . fieldString ( name , value ) + " " } return s }


func (t *Table) fieldString(name, value string) string {
	value = fmt.Sprintf(" %s ", value)
	spacesLeft := t.fieldSizes[name] - runewidth.StringWidth(value)
	if spacesLeft > 0 {
		for i := 0; i < spacesLeft; i++ {
			value += " "
		}
	}
	return value
}

func ( t * Table ) fieldString ( name , value string ) string { value = fmt . Sprintf ( " " , value ) spacesLeft := t . fieldSizes [ name ] - runewidth . StringWidth ( value ) if spacesLeft > 0 { for i := 0 ; i < spacesLeft ; i ++ { value += " " } } return value }

// fieldString - Creates field value string.

fieldString - Creates field value string .


func (t *Table) stringTableDash() string {
	if t.Markdown {
		return t.stringMarkdownDash()
	}
	return t.stringDash()
}

func ( t * Table ) stringTableDash ( ) string { if t . Markdown { return t . stringMarkdownDash ( ) } return t . stringDash ( ) }

// stringTableDash - output table dash. Markdown or not depending on settings.

stringTableDash - output table dash . Markdown or not depending on settings .


func (t *Table) printMarkdownDash() {
	r := make(map[string]string)
	for _, name := range t.Fields {
		r[name] = strings.Repeat("-", t.fieldSizes[name]-2)
	}
	fmt.Println(t.rowString(r))
}

func ( t * Table ) printMarkdownDash ( ) { r := make ( map [ string ] string ) for _ , name := range t . Fields { r [ name ] = strings . Repeat ( " " , t . fieldSizes [ name ] - 2 ) } fmt . Println ( t . rowString ( r ) ) }

// printMarkdownDash - Prints dash in middle of table.

printMarkdownDash - Prints dash in middle of table .


func (t *Table) stringMarkdownDash() string {
	r := make(map[string]string)
	for _, name := range t.Fields {
		r[name] = strings.Repeat("-", t.fieldSizes[name]-2)
	}
	return t.rowString(r)
}

func ( t * Table ) stringMarkdownDash ( ) string { r := make ( map [ string ] string ) for _ , name := range t . Fields { r [ name ] = strings . Repeat ( " " , t . fieldSizes [ name ] - 2 ) } return t . rowString ( r ) }

// stringMarkdownDash - output dash in middle of table.

stringMarkdownDash - output dash in middle of table .


func HashPassword(password []byte, salt []byte) (hash []byte, err error) {
	hash, err = scrypt.Key(password, salt, N, R, P, KEYLENGTH)
	if err != nil {
		return nil, err
	}
	return
}

func HashPassword ( password [ ] byte , salt [ ] byte ) ( hash [ ] byte , err error ) { hash , err = scrypt . Key ( password , salt , N , R , P , KEYLENGTH ) if err != nil { return nil , err } return }


func EncodeOAuth2Code(clientID, redirectURI, userID, sharedKey string) (code string, err error) {
	rand := RandStringBytesMaskImprSrc(20)
	exp := time.Now().Add(time.Minute * 10).String()
	response := NewResponse(clientID, redirectURI, userID, exp, rand)
	jresponse, err := json.Marshal(response)
	if err != nil {
		log.Printf("Error: %v", err)
	}
	j64response := base64.StdEncoding.EncodeToString(jresponse)
	signer, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.HS512, Key: []byte(sharedKey)}, nil)
	if err != nil {
		log.Printf("Error: %v", err)
	}
	object, err := signer.Sign([]byte(j64response))
	if err != nil {
		log.Printf("Error: %v", err)
	}
	code, err = object.CompactSerialize()
	return
}

func EncodeOAuth2Code ( clientID , redirectURI , userID , sharedKey string ) ( code string , err error ) { rand := RandStringBytesMaskImprSrc ( 20 ) exp := time . Now ( ) . Add ( time . Minute * 10 ) . String ( ) response := NewResponse ( clientID , redirectURI , userID , exp , rand ) jresponse , err := json . Marshal ( response ) if err != nil { log . Printf ( " " , err ) } j64response := base64 . StdEncoding . EncodeToString ( jresponse ) signer , err := jose . NewSigner ( jose . SigningKey { Algorithm : jose . HS512 , Key : [ ] byte ( sharedKey ) } , nil ) if err != nil { log . Printf ( " " , err ) } object , err := signer . Sign ( [ ] byte ( j64response ) ) if err != nil { log . Printf ( " " , err ) } code , err = object . CompactSerialize ( ) return }

//EncodeOAuth2Code generate an OAuth2 code


func DecodeOAuth2Code(code, sharedKey string) (response Response, err error) {
	object, err := jose.ParseSigned(code)
	if err != nil {
		return
	}
	output, err := object.Verify([]byte(sharedKey))
	if err != nil {
		return
	}
	base64Text := make([]byte, base64.StdEncoding.DecodedLen(len(output)))
	l, err := base64.StdEncoding.Decode(base64Text, output)
	if err != nil {
		return
	}
	response = Response{}
	err = json.Unmarshal(base64Text[:l], &response)
	return
}

func DecodeOAuth2Code ( code , sharedKey string ) ( response Response , err error ) { object , err := jose . ParseSigned ( code ) if err != nil { return } output , err := object . Verify ( [ ] byte ( sharedKey ) ) if err != nil { return } base64Text := make ( [ ] byte , base64 . StdEncoding . DecodedLen ( len ( output ) ) ) l , err := base64 . StdEncoding . Decode ( base64Text , output ) if err != nil { return } response = Response { } err = json . Unmarshal ( base64Text [ : l ] , & response ) return }

//DecodeOAuth2Code inverse of EncodeOAuth2Code


func NewServer(filename string, environment string) (server *Server, err error) {
	conf, err := GetConfig(filename, environment)

	logFile, err := os.OpenFile(conf.Log.File+logFilename, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
	if err != nil {
		log.SetOutput(os.Stderr)
		log.Warningf("Can't open logfile: %v", err)
	} else {
		log.SetOutput(logFile)
	}

	level := log.ErrorLevel
	if strings.Compare(conf.Log.Level, "") != 0 {
		level, _ = log.ParseLevel(conf.Log.Level)
	} else {
		log.Infof("Log Level: %v", level)
	}
	log.SetLevel(level)

	server = &Server{Config: conf, Done: make(chan bool, 1), Error: make(chan error, 1), Server: http.Server{Handler: NewLoggingServeMux(conf)}, quit: make(chan bool), isStarted: false}
	return
}

func NewServer ( filename string , environment string ) ( server * Server , err error ) { conf , err := GetConfig ( filename , environment ) logFile , err := os . OpenFile ( conf . Log . File + logFilename , os . O_WRONLY | os . O_CREATE | os . O_APPEND , 0666 ) if err != nil { log . SetOutput ( os . Stderr ) log . Warningf ( " " , err ) } else { log . SetOutput ( logFile ) } level := log . ErrorLevel if strings . Compare ( conf . Log . Level , " " ) != 0 { level , _ = log . ParseLevel ( conf . Log . Level ) } else { log . Infof ( " " , level ) } log . SetLevel ( level ) server = & Server { Config : conf , Done : make ( chan bool , 1 ) , Error : make ( chan error , 1 ) , Server : http . Server { Handler : NewLoggingServeMux ( conf ) } , quit : make ( chan bool ) , isStarted : false } return }

//NewServer create a new instance of Server


func (s *Server) Start() (err error) {
	log.Infof("Lunarc is starting on port :%d", s.Config.Port)
	var l net.Listener
	go func() {
		l, err = net.Listen("tcp", fmt.Sprintf(":%d", s.Config.Port))
		if err != nil {
			log.Errorf("Error: %v", err)
			s.Error <- err
			return
		}
		s.isStarted = true
		if len(s.Config.SSL.Certificate) > 0 && len(s.Config.SSL.Key) > 0 {
			err = s.ServeTLS(l, s.Config.SSL.Certificate, s.Config.SSL.Key)
			if err != nil && err != http.ErrServerClosed {
				log.Errorf("%v", err)
				l.Close()
				s.Error <- err
				s.quit <- true
			}
			close(s.quit)
		} else {
			err = s.Serve(l)
			if err != nil && err != http.ErrServerClosed {
				log.Errorf("%v", err)
				s.Error <- err
				s.quit <- true
			}
			close(s.quit)
		}
	}()

	<-s.quit

	if err = s.Shutdown(context.Background()); err != nil {
		log.Errorf("%v", err)
		s.Error <- err
	}

	<-s.quit

	l = nil
	log.Info("Lunarc terminated.")
	s.isStarted = false
	s.Done <- true
	return
}

func ( s * Server ) Start ( ) ( err error ) { log . Infof ( " " , s . Config . Port ) var l net . Listener go func ( ) { l , err = net . Listen ( " " , fmt . Sprintf ( " " , s . Config . Port ) ) if err != nil { log . Errorf ( " " , err ) s . Error <- err return } s . isStarted = true if len ( s . Config . SSL . Certificate ) > 0 && len ( s . Config . SSL . Key ) > 0 { err = s . ServeTLS ( l , s . Config . SSL . Certificate , s . Config . SSL . Key ) if err != nil && err != http . ErrServerClosed { log . Errorf ( " " , err ) l . Close ( ) s . Error <- err s . quit <- true } close ( s . quit ) } else { err = s . Serve ( l ) if err != nil && err != http . ErrServerClosed { log . Errorf ( " " , err ) s . Error <- err s . quit <- true } close ( s . quit ) } } ( ) <- s . quit if err = s . Shutdown ( context . Background ( ) ) ; err != nil { log . Errorf ( " " , err ) s . Error <- err } <- s . quit l = nil log . Info ( " " ) s . isStarted = false s . Done <- true return }


func (s *Server) Stop() {
	if s.isStarted && s.quit != nil {
		log.Info("Lunarc is stopping...")
		s.quit <- true
	} else {
		log.Info("Lunarc is not running")
		s.Error <- errors.New("Lunarc is not running")
		s.Done <- false
	}
}

func ( s * Server ) Stop ( ) { if s . isStarted && s . quit != nil { log . Info ( " " ) s . quit <- true } else { log . Info ( " " ) s . Error <- errors . New ( " " ) s . Done <- false } }


func NewLoggingServeMux(conf Config) *LoggingServeMux {
	serveMux := http.NewServeMux()
	return &LoggingServeMux{serveMux, conf}
}

func NewLoggingServeMux ( conf Config ) * LoggingServeMux { serveMux := http . NewServeMux ( ) return & LoggingServeMux { serveMux , conf } }

// NewLoggingServeMux allocates and returns a new LoggingServeMux


func (mux *LoggingServeMux) Handler(r *http.Request) (h http.Handler, pattern string) {
	return mux.serveMux.Handler(r)
}

func ( mux * LoggingServeMux ) Handler ( r * http . Request ) ( h http . Handler , pattern string ) { return mux . serveMux . Handler ( r ) }


func (mux *LoggingServeMux) Handle(pattern string, handler http.Handler) {

	var log = logrus.New()

	logFile, err := os.OpenFile(mux.conf.Log.File+aFilename, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
	if err != nil {
		log.Out = os.Stderr
		log.Warningf("Can't open logfile: %v", err)
	} else {
		log.Out = logFile
	}
	mux.serveMux.Handle(pattern, Logging(handler, log))
}

func ( mux * LoggingServeMux ) Handle ( pattern string , handler http . Handler ) { var log = logrus . New ( ) logFile , err := os . OpenFile ( mux . conf . Log . File + aFilename , os . O_WRONLY | os . O_CREATE | os . O_APPEND , 0666 ) if err != nil { log . Out = os . Stderr log . Warningf ( " " , err ) } else { log . Out = logFile } mux . serveMux . Handle ( pattern , Logging ( handler , log ) ) }


func (mux *LoggingServeMux) HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request)) {
	mux.serveMux.Handle(pattern, http.HandlerFunc(handler))
}

func ( mux * LoggingServeMux ) HandleFunc ( pattern string , handler func ( http . ResponseWriter , * http . Request ) ) { mux . serveMux . Handle ( pattern , http . HandlerFunc ( handler ) ) }

// HandleFunc registers the handler function for the given pattern.

HandleFunc registers the handler function for the given pattern .


func (db *Database) Init() error {

	// Create URL from host/port
	db.getURL()

	// Test connection to ElasticSearch
	err := db.TestConnection()
	if err != nil {
		return errors.Wrap(err, "failed to connect to database")
	}

	client, err := elastic.NewSimpleClient(
		elastic.SetURL(db.URL),
		elastic.SetBasicAuth(
			utils.Getopts(db.Username, "MALICE_ELASTICSEARCH_USERNAME", ""),
			utils.Getopts(db.Password, "MALICE_ELASTICSEARCH_PASSWORD", ""),
		),
	)
	if err != nil {
		return errors.Wrap(err, "failed to create elasticsearch simple client")
	}

	exists, err := client.IndexExists(db.Index).Do(context.Background())
	if err != nil {
		return errors.Wrap(err, "failed to check if index exists")
	}

	if !exists {
		// Index does not exist yet.
		createIndex, err := client.CreateIndex(db.Index).BodyString(mapping).Do(context.Background())
		if err != nil {
			return errors.Wrapf(err, "failed to create index: %s", db.Index)
		}

		if !createIndex.Acknowledged {
			log.Error("index creation not acknowledged")
		} else {
			log.Debugf("created index %s", db.Index)
		}
	} else {
		log.Debugf("index %s already exists", db.Index)
	}

	return nil
}

func
(
db
*
Database
)
Init
(
)
error
{
// Create URL from host/port
db
.
getURL
(
)
// Test connection to ElasticSearch
err
:=
db
.
TestConnection
(
)
if
err
!=
{
return
errors
.
Wrap
(
err
,
"
"
)
}
client
,
err
:=
elastic
.
NewSimpleClient
(
elastic
.
SetURL
(
db
.
URL
)
,
elastic
.
SetBasicAuth
(
utils
.
Getopts
(
db
.
Username
,
"
"
,
"
"
)
,
utils
.
Getopts
(
db
.
Password
,
"
"
,
"
"
)
,
)
,
)
if
err
!=
{
return
errors
.
Wrap
(
err
,
"
"
)
}
exists
,
err
:=
client
.
IndexExists
(
db
.
Index
)
.
Do
(
context
.
Background
(
)
)
if
err
!=
{
return
errors
.
Wrap
(
err
,
"
"
)
}
if
!
exists
{
// Index does not exist yet.
createIndex
,
err
:=
client
.
CreateIndex
(
db
.
Index
)
.
BodyString
(
mapping
)
.
Do
(
context
.
Background
(
)
)
if
err
!=
{
return
errors
.
Wrapf
(
err
,
"
"
,
db
.
Index
)
}
if
!
createIndex
.
Acknowledged
{
log
.
Error
(
"
"
)
}
else
{
log
.
Debugf
(
"
"
,
db
.
Index
)
}
}
else
{
log
.
Debugf
(
"
"
,
db
.
Index
)
}
return
}

// Init initalizes ElasticSearch for use with malice


func (db *Database) WaitForConnection(ctx context.Context, timeout int) error {

	var err error

	secondsWaited := 0

	connCtx, cancel := context.WithTimeout(ctx, time.Duration(timeout)*time.Second)
	defer cancel()

	log.Debug("===> trying to connect to elasticsearch")
	for {
		// Try to connect to Elasticsearch
		select {
		case <-connCtx.Done():
			return errors.Wrapf(err, "connecting to elasticsearch timed out after %d seconds", secondsWaited)
		default:
			err = db.TestConnection()
			if err == nil {
				log.Debugf("elasticsearch came online after %d seconds", secondsWaited)
				return nil
			}
			// not ready yet
			secondsWaited++
			log.Debug(" * could not connect to elasticsearch (sleeping for 1 second)")
			time.Sleep(1 * time.Second)
		}
	}
}

func
(
db
*
Database
)
WaitForConnection
(
ctx
context
.
Context
,
timeout
int
)
error
{
var
err
error
secondsWaited
:=
0
connCtx
,
cancel
:=
context
.
WithTimeout
(
ctx
,
time
.
Duration
(
timeout
)
*
time
.
Second
)
defer
cancel
(
)
log
.
Debug
(
"
"
)
for
{
// Try to connect to Elasticsearch
select
{
case
<-
connCtx
.
Done
(
)
:
return
errors
.
Wrapf
(
err
,
"
"
,
secondsWaited
)
default
:
err
=
db
.
TestConnection
(
)
if
err
==
{
log
.
Debugf
(
"
"
,
secondsWaited
)
return
}
// not ready yet
secondsWaited
++
log
.
Debug
(
"
"
)
time
.
Sleep
(
1
*
time
.
Second
)
}
}
}

// WaitForConnection waits for connection to Elasticsearch to be ready